searchfetch 3.3.3 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,24 +1,26 @@
1
- # SearchFetch (MCP Server)
2
-
3
- A fault-tolerant, stealth-enabled Model Context Protocol (MCP) server for web searching and content fetching. Built for AI Agents (Cursor, Claude Code, OpenCode), it uses a stealth browser engine to fetch pages, dynamically handles SPAs/React, and converts bloat into token-optimized Markdown.
4
-
5
- ## Features
6
-
7
- - **Stealth Engine:** Powered by CloakBrowser C++ patches + `humanize` logic. The browser renders and moves like a real user, reducing bot-detection scores.
8
- - **Fault Tolerance:** Auto-healing browser sessions, grace-period timeouts for SPAs, and network-level blocking of tracking scripts and media.
9
- - **Token-Optimized Output:** Strips base64 images, SVGs, scripts, and inline styles from the DOM _before_ Markdown conversion.
10
- - **Dual Runtime:** Natively supports zero-install execution via both Python (`uvx`) and Node.js (`npx`).
11
- - **Template-Driven Extraction:** Structured extraction via shared JSON templates (GitHub, npm, PyPI, crates.io, docs pages, Docker Hub, and more). Supports custom inline templates.
12
-
13
- ---
14
-
15
- ## Usage & Installation
16
-
17
- You do not need to install this repository manually. Configure your agent to use the zero-install commands `npx` or `uvx`.
18
-
19
- ### Claude Desktop Configuration
20
-
21
- **Option A: Python (`uvx` - Recommended)**
1
+ # SearchFetch
2
+
3
+ An [MCP](https://modelcontextprotocol.io) server that gives AI agents web search and page
4
+ fetching through a stealth browser. Pages are rendered with JavaScript, stripped of noise, and
5
+ returned as compact Markdown.
6
+
7
+ - **Browser rendering:** [CloakBrowser](https://github.com/CloakHQ/CloakBrowser) runs Chromium
8
+ with humanized input. Each fetch uses an isolated browser context. Sites may still demand
9
+ logins or challenges.
10
+ - **Fault tolerance:** relaunches a disconnected browser and retries timeouts, network failures
11
+ and HTTP 429 (honoring `Retry-After`, capped at 30 s) once. Built-in search engines fall back
12
+ to DuckDuckGo HTML and then DuckDuckGo Lite.
13
+ - **Token-efficient output:** scripts, styles, SVGs, inline styles and embedded `data:` images
14
+ are removed before conversion; images, media and fonts are blocked at the network layer.
15
+ - **Template-driven extraction:** JSON templates for GitHub, GitLab, npm, PyPI, crates.io,
16
+ docs.rs, Docker Hub, Wikipedia, MDN, Reddit, YouTube, DEV, pkg.go.dev, Javadoc and generic
17
+ documentation sites. Custom templates can be passed inline.
18
+ - **Two runtimes:** Python (`uvx`, Python 3.11.5+) or Node.js (`npx`, Node 24+), with the same
19
+ tools, templates and output. The first run downloads the browser binary.
20
+
21
+ ## Setup
22
+
23
+ No manual install is needed. Point your MCP client at `uvx` or `npx`:
22
24
 
23
25
  ```json
24
26
  {
@@ -31,96 +33,115 @@ You do not need to install this repository manually. Configure your agent to use
31
33
  }
32
34
  ```
33
35
 
34
- **Option B: Node.js (`npx`)**
35
-
36
- ```json
37
- {
38
- "mcpServers": {
39
- "searchfetch": {
40
- "command": "npx",
41
- "args": ["-y", "searchfetch"]
42
- }
43
- }
44
- }
45
- ```
46
-
47
- ### Cursor / IDE Configuration
48
-
49
- Add via the **MCP panel** in Cursor settings:
50
-
51
- - **Type:** `command`
52
- - **Command:** `uvx searchfetch` (or `npx -y searchfetch`)
53
-
54
- ---
55
-
56
- ## Available Tools
57
-
58
- ### 1. `websearch`
59
-
60
- Search the web through the template pipeline. DuckDuckGo and Google are built-in; custom search templates can be selected by name.
61
-
62
- | Parameter | Type | Default | Description |
63
- | ------------- | ------------ | -------------- | ---------------------------------------------------------------------------------------------- |
64
- | `query` | string | _required_ | The search query string. |
65
- | `engine` | string | `"duckduckgo"` | `"duckduckgo"`, `"google"`, or a custom search template name. |
66
- | `max_results` | number | `10` | Maximum number of results to return. |
67
- | `region` | string/null | `null` | Region/language code (e.g. `"us-en"`, `"de-de"`). DDG maps directly; Google maps to `gl`/`hl`. |
68
- | `safe_search` | boolean/null | `null` | Enable safe search. `null` uses the template default. |
69
- | `block_media` | boolean | `true` | Block images, media, and fonts at the network layer. |
70
-
71
- ### 2. `webfetch`
72
-
73
- Fetch a page with the stealth browser and extract structured Markdown using a template. Falls back to generic Markdown extraction for unknown pages.
74
-
75
- | Parameter | Type | Default | Description |
76
- | ------------- | ------- | ---------- | ----------------------------------------------------- |
77
- | `url` | string | _required_ | Full URL (must start with `http`/`https`). |
78
- | `template` | string | `"auto"` | `"auto"`, a built-in name, or inline JSON template. |
79
- | `start_index` | number | `0` | Character offset for pagination. |
80
- | `max_length` | number | `10000` | Maximum characters per request. |
81
- | `block_media` | boolean | `true` | Block images, videos, and fonts at the network layer. |
82
-
83
- Template extraction supports `text`, `markdown`, `attribute`, and `html` formats; nested children; repeated sections; URL-decoding transforms; per-template cookies; and per-template resource blocking.
84
-
85
- Built-in templates live in `templates/*.json` and are shared by the Node.js and Python implementations.
86
-
87
- **Available page templates** (auto-detected by URL or selectable by name):
88
- `wikipedia`, `reddit`, `mdn-web-docs`, `gitlab`, `youtube`, `devto`, `go-pkg`, `javadoc`,
89
- `github-repo`, `github-issue`, `npm-package`, `pypi-package`, `crates-package`,
90
- `docker-hub`, `docs-rs`, `docs-page`
91
-
92
- **`raw`** — special template that applies minimal filtering and returns full body content as markdown. Use when you need the complete page without template-specific extraction.
93
-
94
- ---
95
-
96
- ## Local Development
36
+ For Node.js, use `"command": "npx", "args": ["-y", "searchfetch"]`. In Cursor, add a `command`
37
+ server with `uvx searchfetch` or `npx -y searchfetch`.
38
+
39
+ ## Tools
40
+
41
+ Both tools are read-only. Failures are returned as MCP tool errors.
42
+
43
+ ### `websearch`
44
+
45
+ | Parameter | Type | Default | Description |
46
+ | ------------- | ------------ | -------------- | --------------------------------------------------------------------------------- |
47
+ | `query` | string | _required_ | Search query (must not be blank). |
48
+ | `engine` | string | `"duckduckgo"` | `"duckduckgo"`, `"google"`, a search template name, or an inline JSON template. |
49
+ | `region` | string/null | `null` | Region-language code such as `"us-en"`. DuckDuckGo: `kl`; Google: `gl` and `hl`. |
50
+ | `safe_search` | boolean/null | `null` | `true` or `false` sets the engine's safe search; `null` keeps the engine default. |
51
+ | `max_results` | integer | `10` | Maximum results (positive). |
52
+ | `block_media` | boolean | `true` | Block images, media and fonts at the network layer. |
53
+
54
+ Results are a numbered list of titles, URLs and snippets. When an engine fails or returns no
55
+ results, the next template in its `fallback` chain is tried (`google` → `duckduckgo-search` →
56
+ `duckduckgo-lite-search`), and a `[websearch: …]` note at the top of the output explains why.
57
+
58
+ ### `webfetch`
59
+
60
+ | Parameter | Type | Default | Description |
61
+ | ------------- | ------- | ---------- | ------------------------------------------------------------------- |
62
+ | `url` | string | _required_ | Absolute `http`/`https` URL. |
63
+ | `template` | string | `"auto"` | `"auto"` (detect by URL), a template name, or inline JSON template. |
64
+ | `start_index` | integer | `0` | Start offset in Unicode code points (non-negative). |
65
+ | `max_length` | integer | `10000` | Maximum code points to return (positive). |
66
+ | `block_media` | boolean | `true` | Block images, media and fonts at the network layer. |
67
+
68
+ Output ends with a footer naming the template and the character window, plus the next
69
+ `start_index` when more content remains. Pages that match no template are converted whole after
70
+ removing navigation, headers, footers, sidebars, dialogs and media (`template="auto (fallback)"`).
71
+ The `raw` template converts the full `<body>` with no removal.
72
+
73
+ ## Templates
74
+
75
+ Built-in templates live in [`templates/`](templates/) and are shared by both runtimes. Page
76
+ templates: `github-repo`, `github-issue`, `npm-package`, `pypi-package`, `crates-package`,
77
+ `docs-rs`, `javadoc`, `docs-page`, `docker-hub`, `wikipedia`, `gitlab`, `reddit`,
78
+ `mdn-web-docs`, `devto`, `go-pkg`, `youtube`, `raw`. Search templates: `google-search`,
79
+ `duckduckgo-search`, `duckduckgo-lite-search`.
80
+
81
+ Templates are validated when they are loaded or passed inline:
82
+
83
+ | Field | Description |
84
+ | ----------------- | ------------------------------------------------------------------------------------------------ |
85
+ | `name` | Required unique name (inline templates default to `"custom"`). |
86
+ | `sections` | Required list of sections (see below). |
87
+ | `order` | Precedence for `auto` detection; lower wins. |
88
+ | `url_patterns` | Regular expressions (compatible with JavaScript and Python) that select the template for `auto`. |
89
+ | `remove` | CSS selectors removed before extraction. Defaults to scripts, styles, SVG, nav, footer, iframes. |
90
+ | `source_url` | Raw Markdown source tried first, e.g. `"{url}.md"`; HTML responses are ignored. |
91
+ | `cookies` | Playwright cookies added to the browser context. |
92
+ | `block_resources` | Resource types blocked when `block_media` is on. Default: `image`, `media`, `font`. |
93
+ | `url_template` | Search URL with `{placeholders}`; makes the template usable by `websearch`. |
94
+ | `url_params` | Per placeholder: `required`, `default`, and `encode: "url"`. |
95
+ | `engine` | `"duckduckgo"` or `"google"`: how `region` and `safe_search` map to URL parameters. |
96
+ | `fallback` | Name of the search template to try when this one fails. |
97
+
98
+ Each section has a `name`, a `selector` (empty selects `<body>`), and optionally `format` (`text`, `markdown`,
99
+ `attribute` with `attribute`, or `html`), `transform` (one or a list of `strip`,
100
+ `decode_google_url`, `decode_ddg_url`, `json_parse`, `resolve_href`), `required`, `multiple`,
101
+ `max_items`, and `children` (fields extracted from inside each matched element).
102
+
103
+ Selectors separated by top-level commas are ordered fallbacks: the first selector that matches
104
+ wins, and an empty fallback selects the current element. Children search inside their parent
105
+ element and its ancestors, never neighbouring results, so a missing field stays missing. Missing
106
+ `required` sections or fields are reported as errors.
107
+
108
+ A records section whose first item has `Author`/`User` and `Comment`/`Body` fields is rendered as
109
+ a comment thread; other records render as indented `Key: value` blocks.
110
+
111
+ ## Development
97
112
 
98
113
  ```bash
99
- # Install dependencies
100
- npm install
101
- pip install -e ".[dev]"
102
-
103
- # Run tests
104
- npm test # runs all tests (JS + Python)
105
- npm run test:js # Node.js unit tests (built-in test runner)
106
- npm run test:py # Python unit tests (pytest)
107
-
108
- # Lint
109
- npm run lint # runs all linters
110
- npm run lint:js # ESLint
111
- npm run lint:py # Ruff
112
-
113
- # Format
114
- npm run format # auto-format all source files
115
- npm run format:check # check formatting without changes
116
-
117
- # MCP inspector (for manual testing)
118
- npm run inspector-js # test with MCP Inspector (Node.js)
119
- npm run inspector-py # test with MCP Inspector (Python)
114
+ npm ci && uv sync --locked --extra dev
115
+ git config core.hooksPath .githooks # optional: format, lint and unit tests before commits
116
+
117
+ npm test # Node (node:test) and Python (pytest) unit tests
118
+ npm run lint # ESLint and Ruff
119
+ npm run format # Prettier and Ruff format (format:check to verify)
120
+ npm run e2e # real browser against local fixtures, plus the packed npm and wheel builds
121
+ npm run check # everything CI runs
122
+ npm run inspect:node # MCP Inspector (inspect:py for Python)
120
123
  ```
121
124
 
122
- ---
123
-
124
- ## Architecture
125
-
126
- This repository uses a flat dual-manifest structure (`package.json` and `pyproject.toml` in the root). Both runtimes (`index.js` for Node, `server.py` for Python) share the same `templates/*.json` files and maintain feature parity.
125
+ ### Layout
126
+
127
+ | Path | Contents |
128
+ | ---------------------------- | ------------------------------------------------------------------------- |
129
+ | `src/` | Node.js runtime (`index.js` is the `searchfetch` executable). |
130
+ | `searchfetch/` | Python package (`python -m searchfetch` or the `searchfetch` script). |
131
+ | `templates/` | Shared templates; bundled into the npm package and the Python wheel. |
132
+ | `tests/fixtures/` | Shared fixtures that keep both runtimes' extraction and output identical. |
133
+ | `tests/node`, `tests/python` | Unit tests. |
134
+ | `tests/e2e/` | MCP end-to-end tests over stdio against a local HTTP server. |
135
+
136
+ The runtimes mirror each other module for module (`templates`, `extract`, `markdown`, `compose`,
137
+ `browser`, `server`). Any change to one should be made to the other, with a shared fixture if
138
+ the behavior is observable.
139
+
140
+ ### Limits
141
+
142
+ - HTML-to-Markdown conversion uses turndown (Node) and markdownify (Python). They agree on
143
+ common content, but edge cases such as tables differ.
144
+ - After the DOM is ready, each fetch waits up to five seconds for network activity to settle.
145
+ Pages that keep rendering after that may return partial content.
146
+ - E2E tests use local fixtures. Live search-engine availability and third-party page layouts
147
+ change over time and need separate live checks.
package/package.json CHANGED
@@ -1,51 +1,56 @@
1
1
  {
2
2
  "name": "searchfetch",
3
- "version": "3.3.3",
4
- "description": "Fault-tolerant MCP Server for Stealth Web Search and Fetching",
3
+ "version": "4.0.0",
4
+ "description": "Fault-tolerant MCP server for stealth web search and page fetching",
5
+ "license": "MIT",
6
+ "author": "Max",
5
7
  "type": "module",
6
8
  "bin": {
7
- "searchfetch": "index.js"
9
+ "searchfetch": "src/index.js"
8
10
  },
9
11
  "files": [
10
- "index.js",
12
+ "src/",
11
13
  "templates/"
12
14
  ],
13
- "publishConfig": {
14
- "access": "public"
15
- },
16
15
  "repository": {
17
16
  "type": "git",
18
17
  "url": "git+https://github.com/maxylev/searchfetch.git"
19
18
  },
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
20
22
  "scripts": {
21
- "start": "node ./index.js",
22
- "inspector-js": "npx @modelcontextprotocol/inspector node ./index.js",
23
- "inspector-py": "npx @modelcontextprotocol/inspector uv run python ./server.py",
24
- "test": "npm run test:js && npm run test:py",
25
- "test:js": "node --test \"*.test.js\"",
26
- "test:py": "uv run --extra dev pytest test_*.py -v",
27
- "lint": "npm run lint:js && npm run lint:py",
28
- "lint:js": "npx eslint \"*.js\" \"scripts/*.mjs\"",
29
- "lint:py": "uv run --extra dev ruff check server.py scripts/*.py test_*.py",
30
- "format": "npx prettier --write \"*.js\" \"scripts/*.mjs\" \"*.json\" \"*.md\" && uv run --extra dev ruff format server.py scripts/*.py test_*.py",
31
- "format:check": "npx prettier --check \"*.js\" \"scripts/*.mjs\" \"*.json\" \"*.md\" && uv run --extra dev ruff format --check server.py scripts/*.py test_*.py",
23
+ "start": "node src/index.js",
24
+ "inspect:node": "npx @modelcontextprotocol/inspector node src/index.js",
25
+ "inspect:py": "npx @modelcontextprotocol/inspector uv run searchfetch",
26
+ "test": "npm run test:node && npm run test:py",
27
+ "test:node": "node --test \"tests/node/*.test.js\"",
28
+ "test:py": "uv run --locked --extra dev pytest",
29
+ "lint": "npm run lint:node && npm run lint:py",
30
+ "lint:node": "eslint . --max-warnings=0",
31
+ "lint:py": "uv run --locked --extra dev ruff check .",
32
+ "format": "prettier --write . && uv run --locked --extra dev ruff format .",
33
+ "format:check": "prettier --check . && uv run --locked --extra dev ruff format --check .",
32
34
  "e2e": "npm run e2e:node && npm run e2e:py",
33
- "e2e:node": "node scripts/e2e-node.mjs",
34
- "e2e:py": "uv run python scripts/e2e-python.py"
35
+ "e2e:node": "node tests/e2e/node.mjs",
36
+ "e2e:py": "uv run --locked python tests/e2e/python.py",
37
+ "check": "scripts/ci-check.sh"
35
38
  },
36
39
  "dependencies": {
37
- "@modelcontextprotocol/sdk": "^1.30.0",
40
+ "@modelcontextprotocol/sdk": "^1.32.1",
38
41
  "cheerio": "^1.2.0",
39
- "cloakbrowser": "^0.5.5",
40
- "playwright-core": "^1.62.1",
42
+ "cloakbrowser": "^0.6.3",
43
+ "playwright-core": "^1.64.1",
41
44
  "turndown": "^7.2.4",
42
- "zod": "^4.4.3"
43
- },
44
- "overrides": {
45
- "encoding-sniffer": "1.0.2"
45
+ "zod": "^4.6.7"
46
46
  },
47
47
  "devDependencies": {
48
- "eslint": "^10.8.0",
49
- "prettier": "^3.9.6"
48
+ "@eslint/js": "^10.0.1",
49
+ "eslint": "^10.12.0",
50
+ "globals": "^17.13.0",
51
+ "prettier": "^3.9.10"
52
+ },
53
+ "engines": {
54
+ "node": ">=24.0.0"
50
55
  }
51
56
  }
package/src/browser.js ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Shared stealth browser and page fetching.
3
+ *
4
+ * One CloakBrowser instance is reused; every fetch attempt gets an isolated context so cookies
5
+ * and storage never leak between requests. Mirrors `searchfetch/browser.py`.
6
+ */
7
+ import * as cheerio from "cheerio";
8
+ import { launch } from "cloakbrowser";
9
+ import { cleanSourceMarkdown, isMarkdown } from "./markdown.js";
10
+ import { validateUrl } from "./templates.js";
11
+
12
+ export const NAVIGATION_TIMEOUT_MS = 15_000;
13
+ export const SOURCE_TIMEOUT_MS = 10_000;
14
+ export const NETWORK_IDLE_TIMEOUT_MS = 5_000;
15
+ export const MAX_ATTEMPTS = 2;
16
+ export const RATE_LIMIT_DELAY_MS = 2_000;
17
+ export const MAX_RATE_LIMIT_DELAY_MS = 30_000;
18
+ export const NETWORK_RETRY_DELAY_MS = 500;
19
+ export const DEFAULT_BLOCKED_RESOURCES = ["image", "media", "font"];
20
+
21
+ const LAUNCH_ARGS = ["--disable-blink-features=AutomationControlled", "--disable-dev-shm-usage"];
22
+
23
+ export class BrowserManager {
24
+ #browser = null;
25
+ #launching = null;
26
+ #launcher;
27
+
28
+ /** `launcher` is injectable so tests can avoid starting a real browser. */
29
+ constructor(launcher = launch) {
30
+ this.#launcher = launcher;
31
+ }
32
+
33
+ /** Return the connected browser, launching (once, even under concurrency) when needed. */
34
+ async get() {
35
+ if (this.#browser?.isConnected()) return this.#browser;
36
+ this.#launching ??= this.#launcher({ headless: true, humanize: true, args: LAUNCH_ARGS })
37
+ .then((browser) => {
38
+ this.#browser = browser;
39
+ browser.on("disconnected", () => {
40
+ if (this.#browser === browser) this.#browser = null;
41
+ });
42
+ return browser;
43
+ })
44
+ .finally(() => {
45
+ this.#launching = null;
46
+ });
47
+ return this.#launching;
48
+ }
49
+
50
+ /** Close the browser, waiting for an in-flight launch so it cannot outlive shutdown. */
51
+ async close() {
52
+ const browser = await (this.#launching ?? this.#browser);
53
+ this.#browser = null;
54
+ await browser?.close();
55
+ }
56
+ }
57
+
58
+ export class HttpStatusError extends Error {
59
+ constructor(status, url, retryAfterMs = null) {
60
+ super(`HTTP ${status} when fetching ${url}`);
61
+ this.name = "HttpStatusError";
62
+ this.status = status;
63
+ this.retryAfterMs = retryAfterMs;
64
+ }
65
+ }
66
+
67
+ /** Parse a Retry-After header (seconds or HTTP date) into a capped delay in milliseconds. */
68
+ export function parseRetryAfterMs(value, now = Date.now()) {
69
+ if (!value) return RATE_LIMIT_DELAY_MS;
70
+ const seconds = Number(value);
71
+ const delay = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - now;
72
+ if (!Number.isFinite(delay)) return RATE_LIMIT_DELAY_MS;
73
+ return Math.min(Math.max(delay, 0), MAX_RATE_LIMIT_DELAY_MS);
74
+ }
75
+
76
+ const DENIED_TITLES = [
77
+ "access denied",
78
+ "are you a human",
79
+ "are you a robot",
80
+ "ddos protection",
81
+ "forbidden",
82
+ "one more step",
83
+ "security check",
84
+ "sorry, you have been blocked",
85
+ "unusual traffic",
86
+ "verify you are human",
87
+ ];
88
+ const DENIED_BODY = [
89
+ "bots use duckduckgo too",
90
+ "our systems have detected unusual traffic",
91
+ "sorry, you have been blocked",
92
+ "to continue, please type the characters",
93
+ ];
94
+ /** Only conclusive on short pages; long articles may legitimately mention these phrases. */
95
+ const DENIED_SHORT_BODY = ["access denied", "are you a robot", "verify you are human"];
96
+ const SHORT_BODY_LENGTH = 1200;
97
+
98
+ /** Heuristically detect CAPTCHA, bot-check and block pages. */
99
+ export function isAccessDenied($) {
100
+ const title = $("title").text().toLowerCase();
101
+ const body = $("body").text().replace(/\s+/g, " ").trim().toLowerCase();
102
+ return (
103
+ DENIED_TITLES.some((phrase) => title.includes(phrase)) ||
104
+ DENIED_BODY.some((phrase) => body.includes(phrase)) ||
105
+ (body.length < SHORT_BODY_LENGTH && DENIED_SHORT_BODY.some((phrase) => body.includes(phrase)))
106
+ );
107
+ }
108
+
109
+ const TRANSIENT_ERROR =
110
+ /net::|ERR_|navigation|navigating|connection|target closed|browser has been closed/i;
111
+
112
+ /** Rate limits, timeouts and network/browser failures are worth one more attempt. */
113
+ export function retryDelayMs(err) {
114
+ if (err instanceof HttpStatusError) {
115
+ return err.status === 429 ? (err.retryAfterMs ?? RATE_LIMIT_DELAY_MS) : null;
116
+ }
117
+ if (err?.name === "TimeoutError" || TRANSIENT_ERROR.test(err?.message ?? "")) {
118
+ return NETWORK_RETRY_DELAY_MS;
119
+ }
120
+ return null;
121
+ }
122
+
123
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
124
+
125
+ /** Open a page in a fresh context with template cookies and resource blocking applied. */
126
+ async function openPage(browser, template, blockMedia) {
127
+ const context = await browser.newContext();
128
+ try {
129
+ if (template?.cookies?.length) await context.addCookies(template.cookies);
130
+ const page = await context.newPage();
131
+ const blocked = new Set(template?.block_resources ?? DEFAULT_BLOCKED_RESOURCES);
132
+ if (blockMedia && blocked.size > 0) {
133
+ await page.route("**/*", (route) =>
134
+ blocked.has(route.request().resourceType()) ? route.abort() : route.continue(),
135
+ );
136
+ }
137
+ return { context, page };
138
+ } catch (err) {
139
+ await context.close();
140
+ throw err;
141
+ }
142
+ }
143
+
144
+ async function fetchHtmlOnce(browserManager, url, template, blockMedia) {
145
+ const { context, page } = await openPage(await browserManager.get(), template, blockMedia);
146
+ try {
147
+ // Check the status before waiting for rendering so a slow page cannot hide an HTTP error.
148
+ const response = await page.goto(url, {
149
+ waitUntil: "domcontentloaded",
150
+ timeout: NAVIGATION_TIMEOUT_MS,
151
+ });
152
+ const status = response?.status() ?? 0;
153
+ if (status >= 400) {
154
+ const retryAfter =
155
+ status === 429 ? parseRetryAfterMs(response.headers()["retry-after"]) : null;
156
+ throw new HttpStatusError(status, url, retryAfter);
157
+ }
158
+ try {
159
+ await page.waitForLoadState("networkidle", { timeout: NETWORK_IDLE_TIMEOUT_MS });
160
+ } catch (err) {
161
+ // Long polling must not prevent extraction of an already loaded document.
162
+ if (err.name !== "TimeoutError") throw err;
163
+ }
164
+ const html = await page.content();
165
+ if (isAccessDenied(cheerio.load(html))) {
166
+ throw new Error(`Access denied: CAPTCHA or block page detected at ${url}.`);
167
+ }
168
+ return html;
169
+ } finally {
170
+ await context.close();
171
+ }
172
+ }
173
+
174
+ /** Render `url` and return its HTML, retrying rate limits and transient failures once. */
175
+ export async function fetchHtml(browserManager, url, template, blockMedia) {
176
+ validateUrl(url);
177
+ for (let attempt = 1; ; attempt++) {
178
+ try {
179
+ return await fetchHtmlOnce(browserManager, url, template, blockMedia);
180
+ } catch (err) {
181
+ const delay = retryDelayMs(err);
182
+ if (attempt >= MAX_ATTEMPTS || delay === null) throw err;
183
+ await sleep(delay);
184
+ }
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Best-effort fetch of a raw Markdown source (e.g. `page.md`). Returns the cleaned Markdown, or
190
+ * null when the source is missing, is HTML, or does not look like Markdown.
191
+ */
192
+ export async function fetchSourceMarkdown(browserManager, url, template, blockMedia) {
193
+ validateUrl(url);
194
+ let opened;
195
+ try {
196
+ opened = await openPage(await browserManager.get(), template, blockMedia);
197
+ const response = await opened.page.goto(url, {
198
+ waitUntil: "domcontentloaded",
199
+ timeout: SOURCE_TIMEOUT_MS,
200
+ });
201
+ if (!response || response.status() >= 400) return null;
202
+ const contentType = (response.headers()["content-type"] ?? "").toLowerCase();
203
+ if (contentType.includes("text/html") || contentType.includes("application/xhtml+xml")) {
204
+ return null;
205
+ }
206
+ const text = cleanSourceMarkdown(await response.text());
207
+ return isMarkdown(text) ? text : null;
208
+ } catch {
209
+ return null;
210
+ } finally {
211
+ await opened?.context.close();
212
+ }
213
+ }