Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix(fetch-page): unify --json key set between raw and rendered fetches

Agrici Daniel3c396ff79caa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 85c28ea..e17d811 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `fetch_page.py --json` exposes full response metadata and content for raw and
rendered fetches, including structured fetch errors (#282).
+- `fetch_page.py --json --max-text N` truncates content fields, matching
+ `render_page.py`'s option.
+
+### Fixed
+
+- `fetch_page.py --json` emitted a different key set for the raw path than the
+ rendered path (raw dumped `fetch_page()`'s own dict as-is; rendered dumped
+ `render_page()`'s dict as-is). Both paths now go through
+ `render_page._json_summary` after the raw result is mapped onto the
+ render_page contract, so `--json` output has one shared shape and `--max-text`
+ applies to both (#297).
## [2.2.6] - 2026-09-10
diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md
index 140f6f5..5df6e31 100644
--- a/docs/COMMANDS.md
+++ b/docs/COMMANDS.md
@@ -7,11 +7,21 @@ All Claude SEO commands start with `/seo` followed by a subcommand.
## Page-fetching script
Use `./bin/claude-seo run fetch_page.py https://example.com --json` for structured
-retrieval. JSON includes `url`, `status_code`, `content`, `headers`,
-`redirect_chain`, and `error`. Raw fetches also include `redirect_details`;
-`--render auto` or `--render always` includes the renderer's additional fields.
-Content is returned in full. Fetch errors still emit JSON and exit 1; successful
-fetches exit 0. HTTP status codes are reported without changing this behavior.
+retrieval. Both the raw path (default, `--render never`) and the rendered path
+(`--render auto` or `--render always`) emit JSON through the same
+`render_page._json_summary` contract, so the two share one key set: `url`,
+`status_code`, `content`, `raw_content`, `is_spa`, `extracted_text`,
+`publication_date`, `accessibility_tree`, `accessibility_error`,
+`accessibility_partial`, `headers`, `redirect_chain`, `console_errors`,
+`render_diagnostics`, `render_engine`, `render_ms`, `mode_used`, `error`,
+`structured_data`, and `truncation`. The raw path fills renderer-only fields
+(`is_spa`, `extracted_text`, `render_engine`, ...) with `None`/empty defaults.
+Fetch errors still emit JSON and exit 1; successful fetches exit 0. HTTP status
+codes are reported without changing this behavior.
+
+Pass `--max-text N` to cap the `content`, `raw_content`, and `extracted_text`
+fields at N characters each; `truncation.fields` reports the original and
+returned character counts per field. `--max-text 0` (default) keeps full text.
Combine `--json --output page.html` to save successful HTML while keeping JSON
on stdout. `output_written` indicates whether HTML was saved. On fetch errors,
diff --git a/scripts/fetch_page.py b/scripts/fetch_page.py
index 7e81ffb..f63df20 100755
--- a/scripts/fetch_page.py
+++ b/scripts/fetch_page.py
@@ -197,15 +197,67 @@ def fetch_page(
return result
-def _emit_json(result: dict, output: Optional[str]) -> None:
- """Emit a fetch result, optionally saving successful HTML separately."""
+def _non_negative_int(value: str) -> int:
+ parsed = int(value)
+ if parsed < 0:
+ raise argparse.ArgumentTypeError("must be zero or greater")
+ return parsed
+
+
+def _as_render_result(result: dict, *, mode_used: str) -> dict:
+ """Map a raw ``fetch_page()`` result onto the ``render_page()`` contract.
+
+ ``render_page._json_summary`` is written against the render_page result
+ shape. Normalizing the raw-fetch result onto that same shape before
+ calling it (rather than dumping the raw dict as-is) means ``--json``
+ emits an identical key set whether or not ``--render`` was used, and the
+ raw path gets ``--max-text`` truncation for free.
+ """
+ redirect_chain = result.get("redirect_details")
+ if not redirect_chain:
+ redirect_chain = [
+ {"url": u, "status_code": None} for u in result.get("redirect_chain") or []
+ ]
+ return {
+ "url": result.get("url"),
+ "status_code": result.get("status_code"),
+ "content": result.get("content"),
+ "raw_content": result.get("content"),
+ "is_spa": None,
+ "extracted_text": None,
+ "publication_date": None,
+ "accessibility_tree": None,
+ "accessibility_error": None,
+ "accessibility_partial": False,
+ "headers": result.get("headers", {}),
+ "redirect_chain": redirect_chain,
+ "console_errors": [],
+ "render_diagnostics": [],
+ "render_engine": None,
+ "render_ms": None,
+ "mode_used": mode_used,
+ "error": result.get("error"),
+ }
+
+
+def _emit_json(result: dict, output: Optional[str], *, max_text: int = 0) -> None:
+ """Emit a fetch result as JSON via ``render_page._json_summary``.
+
+ Both the raw and rendered fetch paths are normalized onto the render_page
+ result contract before this is called, so the emitted JSON has an
+ identical key set (and honours ``--max-text``) regardless of ``--render``.
+ """
+ from render_page import _json_summary
+
output_written = False
- if output and not result["error"]:
+ if output and not result.get("error"):
with open(output, "w", encoding="utf-8") as f:
- f.write(result["content"] or "")
+ f.write(result.get("content") or "")
output_written = True
- print(json.dumps({**result, "output_written": output_written}, indent=2))
- sys.exit(1 if result["error"] else 0)
+ summary = _json_summary(result, max_text=max_text)
+ summary["output_written"] = output_written
+ print(json.dumps(summary, indent=2, default=str))
+ sys.exit(1 if result.get("error") else 0)
def main():
@@ -213,6 +265,16 @@ def main():
parser.add_argument("url", help="URL to fetch")
parser.add_argument("--output", "-o", help="Output file path")
parser.add_argument("--json", action="store_true", help="Emit full fetch result as JSON")
+ parser.add_argument(
+ "--max-text",
+ type=_non_negative_int,
+ default=0,
+ help=(
+ "maximum characters returned for each JSON content field "
+ "(content, raw_content, extracted_text); 0 keeps full text "
+ "(default: 0). Only applies with --json."
+ ),
+ )
parser.add_argument("--timeout", "-t", type=int, default=30, help="Timeout in seconds")
parser.add_argument("--no-redirects", action="store_true", help="Don't follow redirects")
parser.add_argument("--user-agent", help="Custom User-Agent string")
@@ -252,7 +314,7 @@ def main():
user_agent=ua,
)
if args.json:
- _emit_json(rendered, args.output)
+ _emit_json(rendered, args.output, max_text=args.max_text)
if rendered["error"]:
print(f"Error: {rendered['error']}", file=sys.stderr)
sys.exit(1)
@@ -278,7 +340,11 @@ def main():
)
if args.json:
- _emit_json(result, args.output)
+ _emit_json(
+ _as_render_result(result, mode_used="raw"),
+ args.output,
+ max_text=args.max_text,
+ )
if result["error"]:
print(f"Error: {result['error']}", file=sys.stderr)
diff --git a/tests/test_fetch_page_cli.py b/tests/test_fetch_page_cli.py
index 9df38de..f3912cd 100644
--- a/tests/test_fetch_page_cli.py
+++ b/tests/test_fetch_page_cli.py
@@ -1,4 +1,12 @@
-"""CLI output contracts for raw and rendered page fetching."""
+"""CLI output contracts for raw and rendered page fetching.
+
+``--json`` routes both the raw (``--render never``) and rendered
+(``--render auto``/``--render always``) fetch paths through
+``render_page._json_summary`` so the emitted JSON has one shared key
+set and one shared ``--max-text`` truncation contract, regardless of
+which path produced the fetch. The raw path is mapped onto the
+render_page result shape by ``fetch_page._as_render_result`` first.
+"""
import json
import sys
@@ -10,54 +18,139 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
import fetch_page # noqa: E402
import render_page # noqa: E402
+_CONTENT = '<p>Café "hello"\n世界</p>' + "x" * 12000
+
+RAW_RESULT = {
+ "url": "https://example.com/final",
+ "status_code": 200,
+ "content": _CONTENT,
+ "headers": {"Content-Type": "text/html; charset=utf-8"},
+ "redirect_chain": ["https://example.com"],
+ "redirect_details": [{"url": "https://example.com", "status_code": 301}],
+ "error": None,
+}
+
+# A complete render_page() result contract (every key render_page() promises
+# in its module docstring), so the "rendered" fixture branch matches the raw
+# branch's key set once both go through fetch_page._as_render_result /
+# render_page._json_summary.
+RENDERED_RESULT = {
+ "url": "https://example.com/final",
+ "status_code": 200,
+ "content": _CONTENT,
+ "raw_content": _CONTENT,
+ "is_spa": True,
+ "extracted_text": "Cafe hello",
+ "publication_date": None,
+ "accessibility_tree": None,
+ "accessibility_error": None,
+ "accessibility_partial": False,
+ "headers": {"Content-Type": "text/html; charset=utf-8"},
+ "redirect_chain": [{"url": "https://example.com", "status_code": 301}],
+ "console_errors": [],
+ "render_diagnostics": [],
+ "render_engine": "playwright-chromium",
+ "render_ms": 12.5,
+ "mode_used": "rendered",
+ "error": None,
+}
+
@pytest.fixture(params=["never", "auto", "always"])
def fetch_result(request, monkeypatch):
- result = {
- "url": "https://example.com/final",
- "status_code": 200,
- "content": '<p>Café "hello"\n世界</p>' + "x" * 12000,
- "headers": {"Content-Type": "text/html; charset=utf-8"},
- "redirect_chain": ["https://example.com"],
- "redirect_details": [{"url": "https://example.com", "status_code": 301}],
- "error": None,
- }
+ """Mock the raw or rendered fetcher (no network, no browser)."""
if request.param == "never":
- monkeypatch.setattr(fetch_page, "fetch_page", lambda *a, **kw: result)
+ result = dict(RAW_RESULT)
+ monkeypatch.setattr(fetch_page, "fetch_page", lambda *a, **kw: dict(result))
else:
- result.update(mode_used="rendered", is_spa=True, render_ms=12.5)
- monkeypatch.setattr(render_page, "render_page", lambda *a, **kw: result)
- monkeypatch.setattr(sys, "argv", ["fetch_page.py", "https://example.com", "--render", request.param])
+ result = dict(RENDERED_RESULT)
+ monkeypatch.setattr(render_page, "render_page", lambda *a, **kw: dict(result))
+ monkeypatch.setattr(
+ sys, "argv", ["fetch_page.py", "https://example.com", "--render", request.param]
+ )
return result
+def _expected_json(raw_source: dict, *, mode: str, output_written: bool, max_text: int = 0) -> dict:
+ """Compute the exact JSON the CLI must emit for a given mocked result."""
+ normalized = (
+ raw_source if mode != "never" else fetch_page._as_render_result(raw_source, mode_used="raw")
+ )
+ summary = render_page._json_summary(normalized, max_text=max_text)
+ summary["output_written"] = output_written
+ return json.loads(json.dumps(summary, default=str))
+
+
@pytest.mark.parametrize("save_html", [False, True])
-def test_json_preserves_full_result(fetch_result, save_html, tmp_path, capsys):
+def test_json_preserves_full_result(fetch_result, save_html, tmp_path, capsys, monkeypatch):
sys.argv += ["--json"]
output = tmp_path / "page.html"
if save_html:
sys.argv += ["--output", str(output)]
+ mode = [a for a in sys.argv if a in ("never", "auto", "always")][-1]
with pytest.raises(SystemExit) as exc:
fetch_page.main()
assert exc.value.code == 0
captured = capsys.readouterr()
- assert json.loads(captured.out) == {**fetch_result, "output_written": save_html}
+ assert json.loads(captured.out) == _expected_json(
+ fetch_result, mode=mode, output_written=save_html
+ )
assert captured.err == ""
assert output.exists() == save_html
if save_html:
assert output.read_text(encoding="utf-8") == fetch_result["content"]
+def test_json_output_keys_match_between_raw_and_rendered(monkeypatch, capsys):
+ """The headline contract: raw and rendered --json share one key set."""
+ monkeypatch.setattr(fetch_page, "fetch_page", lambda *a, **kw: dict(RAW_RESULT))
+ monkeypatch.setattr(sys, "argv", ["fetch_page.py", "https://example.com", "--json"])
+ with pytest.raises(SystemExit):
+ fetch_page.main()
+ raw_keys = set(json.loads(capsys.readouterr().out).keys())
+
+ monkeypatch.setattr(render_page, "render_page", lambda *a, **kw: dict(RENDERED_RESULT))
+ monkeypatch.setattr(
+ sys, "argv", ["fetch_page.py", "https://example.com", "--render", "always", "--json"]
+ )
+ with pytest.raises(SystemExit):
+ fetch_page.main()
+ rendered_keys = set(json.loads(capsys.readouterr().out).keys())
+
+ assert raw_keys == rendered_keys
+
+
[email protected]("mode", ["never", "always"])
+def test_json_max_text_truncates_content_fields(mode, monkeypatch, capsys):
+ if mode == "never":
+ monkeypatch.setattr(fetch_page, "fetch_page", lambda *a, **kw: dict(RAW_RESULT))
+ else:
+ monkeypatch.setattr(render_page, "render_page", lambda *a, **kw: dict(RENDERED_RESULT))
+ monkeypatch.setattr(
+ sys,
+ "argv",
+ ["fetch_page.py", "https://example.com", "--render", mode, "--json", "--max-text", "10"],
+ )
+ with pytest.raises(SystemExit) as exc:
+ fetch_page.main()
+ assert exc.value.code == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["content"] == _CONTENT[:10]
+ assert payload["truncation"]["fields"]["content"]["truncated"] is True
+ assert payload["truncation"]["fields"]["content"]["original_chars"] == len(_CONTENT)
+
+
def test_json_fetch_error_preserves_existing_file(fetch_result, tmp_path, capsys):
fetch_result.update(error="Request timed out", content=None, status_code=None)
output = tmp_path / "page.html"
output.write_text("existing", encoding="utf-8")
sys.argv += ["--json", "--output", str(output)]
+ mode = [a for a in sys.argv if a in ("never", "auto", "always")][-1]
with pytest.raises(SystemExit) as exc:
fetch_page.main()
assert exc.value.code == 1
captured = capsys.readouterr()
- assert json.loads(captured.out) == {**fetch_result, "output_written": False}
+ assert json.loads(captured.out) == _expected_json(fetch_result, mode=mode, output_written=False)
assert captured.err == ""
assert output.read_text(encoding="utf-8") == "existing"