omnirank 0.5.0__tar.gz

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.
Files changed (188) hide show
  1. omnirank-0.5.0/PKG-INFO +47 -0
  2. omnirank-0.5.0/README.md +14 -0
  3. omnirank-0.5.0/omnirank/__init__.py +14 -0
  4. omnirank-0.5.0/omnirank/__main__.py +6 -0
  5. omnirank-0.5.0/omnirank/adapters/__init__.py +202 -0
  6. omnirank-0.5.0/omnirank/adapters/astro.py +338 -0
  7. omnirank-0.5.0/omnirank/adapters/base.py +372 -0
  8. omnirank-0.5.0/omnirank/adapters/html.py +561 -0
  9. omnirank-0.5.0/omnirank/adapters/jsx.py +340 -0
  10. omnirank-0.5.0/omnirank/adapters/nextjs.py +692 -0
  11. omnirank-0.5.0/omnirank/aeo/__init__.py +9 -0
  12. omnirank-0.5.0/omnirank/aeo/extract.py +383 -0
  13. omnirank-0.5.0/omnirank/aeo/propose.py +84 -0
  14. omnirank-0.5.0/omnirank/aeo/rules.py +964 -0
  15. omnirank-0.5.0/omnirank/aeo/runner.py +148 -0
  16. omnirank-0.5.0/omnirank/applicability.py +98 -0
  17. omnirank-0.5.0/omnirank/apply/__init__.py +23 -0
  18. omnirank-0.5.0/omnirank/apply/engine.py +1254 -0
  19. omnirank-0.5.0/omnirank/apply/journal.py +139 -0
  20. omnirank-0.5.0/omnirank/apply/patch.py +144 -0
  21. omnirank-0.5.0/omnirank/audit.py +185 -0
  22. omnirank-0.5.0/omnirank/bands.py +106 -0
  23. omnirank-0.5.0/omnirank/brief/__init__.py +0 -0
  24. omnirank-0.5.0/omnirank/brief/analyze.py +197 -0
  25. omnirank-0.5.0/omnirank/brief/constants.py +89 -0
  26. omnirank-0.5.0/omnirank/brief/cost.py +62 -0
  27. omnirank-0.5.0/omnirank/brief/egress.py +23 -0
  28. omnirank-0.5.0/omnirank/brief/fetchpages.py +239 -0
  29. omnirank-0.5.0/omnirank/brief/render.py +151 -0
  30. omnirank-0.5.0/omnirank/brief/runner.py +369 -0
  31. omnirank-0.5.0/omnirank/brief/serp.py +274 -0
  32. omnirank-0.5.0/omnirank/brief/text.py +181 -0
  33. omnirank-0.5.0/omnirank/cli.py +844 -0
  34. omnirank-0.5.0/omnirank/clock.py +22 -0
  35. omnirank-0.5.0/omnirank/cms/__init__.py +1 -0
  36. omnirank-0.5.0/omnirank/cms/runner.py +170 -0
  37. omnirank-0.5.0/omnirank/cms/wordpress.py +495 -0
  38. omnirank-0.5.0/omnirank/cms/wordpress_apply.py +508 -0
  39. omnirank-0.5.0/omnirank/cms/wordpress_plan.py +280 -0
  40. omnirank-0.5.0/omnirank/config.py +81 -0
  41. omnirank-0.5.0/omnirank/connect/__init__.py +4 -0
  42. omnirank-0.5.0/omnirank/connect/bing.py +284 -0
  43. omnirank-0.5.0/omnirank/connect/cloud_setup.py +43 -0
  44. omnirank-0.5.0/omnirank/connect/confirm.py +242 -0
  45. omnirank-0.5.0/omnirank/connect/constants.py +226 -0
  46. omnirank-0.5.0/omnirank/connect/doctor.py +270 -0
  47. omnirank-0.5.0/omnirank/connect/ga4.py +749 -0
  48. omnirank-0.5.0/omnirank/connect/ga4_ai.py +123 -0
  49. omnirank-0.5.0/omnirank/connect/google_auth.py +657 -0
  50. omnirank-0.5.0/omnirank/connect/gsc.py +630 -0
  51. omnirank-0.5.0/omnirank/connect/gsc_reports.py +169 -0
  52. omnirank-0.5.0/omnirank/connect/http.py +310 -0
  53. omnirank-0.5.0/omnirank/connect/indexnow.py +373 -0
  54. omnirank-0.5.0/omnirank/connect/naver.py +536 -0
  55. omnirank-0.5.0/omnirank/connect/runner.py +515 -0
  56. omnirank-0.5.0/omnirank/connect/runner_ga4_ai.py +59 -0
  57. omnirank-0.5.0/omnirank/connect/runner_more.py +489 -0
  58. omnirank-0.5.0/omnirank/connect/runner_regional.py +260 -0
  59. omnirank-0.5.0/omnirank/connect/secrets.py +190 -0
  60. omnirank-0.5.0/omnirank/connect/urlcheck.py +41 -0
  61. omnirank-0.5.0/omnirank/connect/yandex.py +350 -0
  62. omnirank-0.5.0/omnirank/crawl/__init__.py +11 -0
  63. omnirank-0.5.0/omnirank/crawl/analyze.py +493 -0
  64. omnirank-0.5.0/omnirank/crawl/crawler.py +491 -0
  65. omnirank-0.5.0/omnirank/crawl/custom.py +175 -0
  66. omnirank-0.5.0/omnirank/crawl/export.py +67 -0
  67. omnirank-0.5.0/omnirank/crawl/fetcher.py +212 -0
  68. omnirank-0.5.0/omnirank/crawl/parse.py +102 -0
  69. omnirank-0.5.0/omnirank/crawl/render.py +148 -0
  70. omnirank-0.5.0/omnirank/crawl/robotsgate.py +198 -0
  71. omnirank-0.5.0/omnirank/crawl/runner.py +295 -0
  72. omnirank-0.5.0/omnirank/crawl/sitemap.py +99 -0
  73. omnirank-0.5.0/omnirank/crawl/text.py +20 -0
  74. omnirank-0.5.0/omnirank/crawl/urls.py +100 -0
  75. omnirank-0.5.0/omnirank/crawlers.py +564 -0
  76. omnirank-0.5.0/omnirank/data/ai_crawlers.json +269 -0
  77. omnirank-0.5.0/omnirank/data/ai_referrers.json +42 -0
  78. omnirank-0.5.0/omnirank/fetch.py +107 -0
  79. omnirank-0.5.0/omnirank/fixes/__init__.py +92 -0
  80. omnirank-0.5.0/omnirank/fixes/base.py +232 -0
  81. omnirank-0.5.0/omnirank/fixes/canonical.py +243 -0
  82. omnirank-0.5.0/omnirank/fixes/schema.py +126 -0
  83. omnirank-0.5.0/omnirank/formats.py +134 -0
  84. omnirank-0.5.0/omnirank/framework.py +223 -0
  85. omnirank-0.5.0/omnirank/gates/__init__.py +48 -0
  86. omnirank-0.5.0/omnirank/gates/aeo.py +114 -0
  87. omnirank-0.5.0/omnirank/gates/contradictions.py +280 -0
  88. omnirank-0.5.0/omnirank/gates/crawler_policy.py +85 -0
  89. omnirank-0.5.0/omnirank/gates/geo.py +152 -0
  90. omnirank-0.5.0/omnirank/gates/hygiene.py +81 -0
  91. omnirank-0.5.0/omnirank/gates/jsonld.py +282 -0
  92. omnirank-0.5.0/omnirank/gates/onpage.py +177 -0
  93. omnirank-0.5.0/omnirank/gates/perf.py +115 -0
  94. omnirank-0.5.0/omnirank/gates/security.py +264 -0
  95. omnirank-0.5.0/omnirank/gates/seo.py +118 -0
  96. omnirank-0.5.0/omnirank/gates/site.py +248 -0
  97. omnirank-0.5.0/omnirank/geo_artifacts.py +199 -0
  98. omnirank-0.5.0/omnirank/html.py +79 -0
  99. omnirank-0.5.0/omnirank/keywords/__init__.py +5 -0
  100. omnirank-0.5.0/omnirank/keywords/constants.py +69 -0
  101. omnirank-0.5.0/omnirank/keywords/engine.py +384 -0
  102. omnirank-0.5.0/omnirank/keywords/report.py +143 -0
  103. omnirank-0.5.0/omnirank/keywords/runner.py +160 -0
  104. omnirank-0.5.0/omnirank/keywords/source.py +60 -0
  105. omnirank-0.5.0/omnirank/keywords/text.py +45 -0
  106. omnirank-0.5.0/omnirank/locator.py +480 -0
  107. omnirank-0.5.0/omnirank/logs/__init__.py +0 -0
  108. omnirank-0.5.0/omnirank/logs/analyze.py +127 -0
  109. omnirank-0.5.0/omnirank/logs/bots.py +69 -0
  110. omnirank-0.5.0/omnirank/logs/ipranges.py +191 -0
  111. omnirank-0.5.0/omnirank/logs/parse.py +452 -0
  112. omnirank-0.5.0/omnirank/logs/paths.py +22 -0
  113. omnirank-0.5.0/omnirank/logs/privacy.py +105 -0
  114. omnirank-0.5.0/omnirank/logs/runner.py +179 -0
  115. omnirank-0.5.0/omnirank/mcp_server.py +1480 -0
  116. omnirank-0.5.0/omnirank/netguard.py +525 -0
  117. omnirank-0.5.0/omnirank/packs/__init__.py +6 -0
  118. omnirank-0.5.0/omnirank/packs/backlinks.py +535 -0
  119. omnirank-0.5.0/omnirank/packs/blog.py +544 -0
  120. omnirank-0.5.0/omnirank/packs/blog_cross.py +468 -0
  121. omnirank-0.5.0/omnirank/packs/crawlers.py +23 -0
  122. omnirank-0.5.0/omnirank/packs/entity.py +492 -0
  123. omnirank-0.5.0/omnirank/packs/feeds.py +150 -0
  124. omnirank-0.5.0/omnirank/packs/frontmatter.py +59 -0
  125. omnirank-0.5.0/omnirank/packs/gsc.py +421 -0
  126. omnirank-0.5.0/omnirank/packs/local.py +879 -0
  127. omnirank-0.5.0/omnirank/packs/mdscan.py +326 -0
  128. omnirank-0.5.0/omnirank/packs/miniyaml.py +378 -0
  129. omnirank-0.5.0/omnirank/packs/model.py +46 -0
  130. omnirank-0.5.0/omnirank/packs/product.py +979 -0
  131. omnirank-0.5.0/omnirank/packs/refresh.py +165 -0
  132. omnirank-0.5.0/omnirank/packs/runner.py +277 -0
  133. omnirank-0.5.0/omnirank/packs/sitescan.py +294 -0
  134. omnirank-0.5.0/omnirank/packs/textsafe.py +79 -0
  135. omnirank-0.5.0/omnirank/packs/xmlsafe.py +92 -0
  136. omnirank-0.5.0/omnirank/page.py +42 -0
  137. omnirank-0.5.0/omnirank/registry.py +302 -0
  138. omnirank-0.5.0/omnirank/report.py +251 -0
  139. omnirank-0.5.0/omnirank/report_cmd/__init__.py +7 -0
  140. omnirank-0.5.0/omnirank/report_cmd/delta.py +58 -0
  141. omnirank-0.5.0/omnirank/report_cmd/files.py +64 -0
  142. omnirank-0.5.0/omnirank/report_cmd/model.py +208 -0
  143. omnirank-0.5.0/omnirank/report_cmd/notify.py +195 -0
  144. omnirank-0.5.0/omnirank/report_cmd/pdf.py +83 -0
  145. omnirank-0.5.0/omnirank/report_cmd/portfolio.py +342 -0
  146. omnirank-0.5.0/omnirank/report_cmd/render.py +379 -0
  147. omnirank-0.5.0/omnirank/report_cmd/runner.py +267 -0
  148. omnirank-0.5.0/omnirank/robots.py +172 -0
  149. omnirank-0.5.0/omnirank/scanner/__init__.py +10 -0
  150. omnirank-0.5.0/omnirank/scanner/badge.py +90 -0
  151. omnirank-0.5.0/omnirank/scanner/cache.py +69 -0
  152. omnirank-0.5.0/omnirank/scanner/cli.py +96 -0
  153. omnirank-0.5.0/omnirank/scanner/engine.py +289 -0
  154. omnirank-0.5.0/omnirank/scanner/limits.py +98 -0
  155. omnirank-0.5.0/omnirank/scanner/server.py +143 -0
  156. omnirank-0.5.0/omnirank/scanner/service.py +328 -0
  157. omnirank-0.5.0/omnirank/schema/__init__.py +13 -0
  158. omnirank-0.5.0/omnirank/schema/catalog.py +679 -0
  159. omnirank-0.5.0/omnirank/schema/catalog_specs.py +350 -0
  160. omnirank-0.5.0/omnirank/schema/core.py +306 -0
  161. omnirank-0.5.0/omnirank/schema/extract.py +396 -0
  162. omnirank-0.5.0/omnirank/schema/gate.py +121 -0
  163. omnirank-0.5.0/omnirank/schema/runner.py +213 -0
  164. omnirank-0.5.0/omnirank/schema/validate.py +504 -0
  165. omnirank-0.5.0/omnirank/schema/vocab.py +305 -0
  166. omnirank-0.5.0/omnirank/schemas/omnirank.config.schema.json +268 -0
  167. omnirank-0.5.0/omnirank/track/__init__.py +0 -0
  168. omnirank-0.5.0/omnirank/track/ai_prompts.py +207 -0
  169. omnirank-0.5.0/omnirank/track/analysis.py +197 -0
  170. omnirank-0.5.0/omnirank/track/constants.py +155 -0
  171. omnirank-0.5.0/omnirank/track/cost.py +229 -0
  172. omnirank-0.5.0/omnirank/track/discover.py +277 -0
  173. omnirank-0.5.0/omnirank/track/discover_cli.py +309 -0
  174. omnirank-0.5.0/omnirank/track/discover_constants.py +95 -0
  175. omnirank-0.5.0/omnirank/track/engines.py +216 -0
  176. omnirank-0.5.0/omnirank/track/estimate_view.py +212 -0
  177. omnirank-0.5.0/omnirank/track/history.py +261 -0
  178. omnirank-0.5.0/omnirank/track/runner.py +586 -0
  179. omnirank-0.5.0/omnirank/track/stats.py +138 -0
  180. omnirank-0.5.0/omnirank/track/storage.py +128 -0
  181. omnirank-0.5.0/omnirank.egg-info/PKG-INFO +47 -0
  182. omnirank-0.5.0/omnirank.egg-info/SOURCES.txt +186 -0
  183. omnirank-0.5.0/omnirank.egg-info/dependency_links.txt +1 -0
  184. omnirank-0.5.0/omnirank.egg-info/entry_points.txt +2 -0
  185. omnirank-0.5.0/omnirank.egg-info/requires.txt +12 -0
  186. omnirank-0.5.0/omnirank.egg-info/top_level.txt +1 -0
  187. omnirank-0.5.0/pyproject.toml +53 -0
  188. omnirank-0.5.0/setup.cfg +4 -0
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.4
2
+ Name: omnirank
3
+ Version: 0.5.0
4
+ Summary: Open-source SEO, AEO and GEO CLI: sweep a site, preview fixes, generate llms.txt and facts.json.
5
+ Author-email: S M Moshiur Rahman <moshiur@ticonsys.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/bemoshiur/OmniRank
8
+ Project-URL: Repository, https://github.com/bemoshiur/OmniRank
9
+ Project-URL: Issues, https://github.com/bemoshiur/OmniRank/issues
10
+ Project-URL: Changelog, https://github.com/bemoshiur/OmniRank/blob/main/CHANGELOG.md
11
+ Keywords: seo,aeo,geo,schema-org,json-ld,llms-txt,claude-code,agent-skills,structured-data,technical-seo
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
20
+ Requires-Python: >=3.11
21
+ Description-Content-Type: text/markdown
22
+ Requires-Dist: httpx>=0.27
23
+ Requires-Dist: beautifulsoup4>=4.12
24
+ Requires-Dist: lxml>=5.2
25
+ Requires-Dist: jsonschema>=4.22
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8.2; extra == "dev"
28
+ Requires-Dist: respx>=0.21; extra == "dev"
29
+ Requires-Dist: ruff>=0.5; extra == "dev"
30
+ Requires-Dist: rfc3339-validator>=0.1.4; extra == "dev"
31
+ Requires-Dist: pyyaml>=6.0; extra == "dev"
32
+ Requires-Dist: pillow>=10.0; extra == "dev"
33
+
34
+ # omnirank
35
+
36
+ Open-source SEO, AEO and GEO CLI: sweep a site, preview fixes, generate `llms.txt` [experimental] (not a ranking or citation lever) and `facts.json`.
37
+
38
+ Full documentation: https://github.com/bemoshiur/OmniRank
39
+
40
+ PyPI: not published yet. Install from git:
41
+
42
+ ```bash
43
+ pip install "git+https://github.com/bemoshiur/OmniRank.git#subdirectory=scripts/py"
44
+ omnirank sweep https://example.com
45
+ ```
46
+
47
+ Contributor note: `omnirank/schemas/omnirank.config.schema.json` is a packaged copy of the repo-root `schemas/omnirank.config.schema.json`; edit both (a test fails if they differ).
@@ -0,0 +1,14 @@
1
+ # omnirank
2
+
3
+ Open-source SEO, AEO and GEO CLI: sweep a site, preview fixes, generate `llms.txt` [experimental] (not a ranking or citation lever) and `facts.json`.
4
+
5
+ Full documentation: https://github.com/bemoshiur/OmniRank
6
+
7
+ PyPI: not published yet. Install from git:
8
+
9
+ ```bash
10
+ pip install "git+https://github.com/bemoshiur/OmniRank.git#subdirectory=scripts/py"
11
+ omnirank sweep https://example.com
12
+ ```
13
+
14
+ Contributor note: `omnirank/schemas/omnirank.config.schema.json` is a packaged copy of the repo-root `schemas/omnirank.config.schema.json`; edit both (a test fails if they differ).
@@ -0,0 +1,14 @@
1
+ from __future__ import annotations
2
+
3
+ import warnings
4
+
5
+ from bs4 import XMLParsedAsHTMLWarning
6
+
7
+ # OmniRank fetches sitemap and sitemap-index XML directly, and any audited target
8
+ # can itself be an XML document. BeautifulSoup always parses with the HTML parser
9
+ # (page.py hard-codes "lxml"), which is correct for HTML but prints this warning
10
+ # on every XML document — roughly 50 lines of noise per URL. Silenced once, here,
11
+ # rather than at every call site.
12
+ warnings.filterwarnings("ignore", category=XMLParsedAsHTMLWarning)
13
+
14
+ __version__ = "0.5.0"
@@ -0,0 +1,6 @@
1
+ """`python -m omnirank` runs the CLI (used by `omnirank mcp` client configs)."""
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ sys.exit(main())
@@ -0,0 +1,202 @@
1
+ """Framework adapters: abstract page edits -> a framework's source file.
2
+
3
+ `plan()` takes a URL and a list of `Edit`s (set title / meta description /
4
+ canonical / Open Graph / robots / lang, inject a JSON-LD node such as one built
5
+ by `omnirank.schema`) and returns the edited text of the ONE file that owns
6
+ that URL, as a unified diff. It writes nothing; `omnirank.apply.engine`
7
+ writes (hash-checked, journaled, undoable) -- see `engine.plan_edits`.
8
+
9
+ The adapter is chosen from `framework.detect`, never guessed:
10
+
11
+ | framework detected | adapter | edits |
12
+ |---|---|---|
13
+ | static, jekyll, hugo | `html` | `<head>` of `.html`/`.htm` files |
14
+ | next-app-router | `nextjs` | `export const metadata` + JSON-LD in the page component |
15
+ | astro | `astro` | the page's `<head>` or its layout component's props |
16
+
17
+ Any other framework (Next.js pages router, Nuxt, SvelteKit, Eleventy,
18
+ WordPress, unknown) is skipped with that reason.
19
+
20
+ `route_finding()` lets `omnirank apply` express two mechanical canonical fixes
21
+ through an adapter for Next.js and Astro pages, where the generic HTML
22
+ generator declines.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ from collections.abc import Sequence
27
+ from dataclasses import dataclass, field, replace
28
+ from pathlib import Path
29
+
30
+ from ..fixes.base import FixOutcome, outcome, read_text, unified_diff
31
+ from ..framework import Detection, detect
32
+ from ..locator import Location, blast_radius, locate
33
+ from ..report import Finding
34
+ from .astro import AstroAdapter
35
+ from .base import (
36
+ Adapter,
37
+ Context,
38
+ Edit,
39
+ Rendered,
40
+ inject_jsonld,
41
+ set_canonical,
42
+ set_description,
43
+ set_lang,
44
+ set_og,
45
+ set_robots,
46
+ set_title,
47
+ )
48
+ from .html import HtmlAdapter
49
+ from .nextjs import NextAdapter
50
+
51
+ ADAPTERS: tuple[Adapter, ...] = (HtmlAdapter(), NextAdapter(), AstroAdapter())
52
+ BY_NAME: dict[str, Adapter] = {adapter.name: adapter for adapter in ADAPTERS}
53
+
54
+ __all__ = ["ADAPTERS", "BY_NAME", "Adapter", "Edit", "Planned", "explain", "for_detection",
55
+ "inject_jsonld", "plan", "route_finding", "set_canonical", "set_description",
56
+ "set_lang", "set_og", "set_robots", "set_title", "suffixes_for"]
57
+
58
+
59
+ def for_detection(detection: Detection) -> Adapter | str:
60
+ """The adapter for a detected framework, or the reason there is none."""
61
+ for adapter in ADAPTERS:
62
+ if detection.framework in adapter.frameworks:
63
+ return adapter
64
+ return (f"skipped: no adapter for framework {detection.framework!r} "
65
+ f"(adapters exist for plain HTML, Next.js App Router and Astro); "
66
+ "nothing is guessed")
67
+
68
+
69
+ def suffixes_for(name: str | None) -> tuple[str, ...] | None:
70
+ adapter = BY_NAME.get(name or "")
71
+ return adapter.suffixes if adapter is not None else None
72
+
73
+
74
+ @dataclass
75
+ class Planned:
76
+ """One URL's adapter plan: the file, its text before and after, per-edit results."""
77
+
78
+ url: str
79
+ detection: Detection
80
+ location: Location
81
+ adapter: str | None
82
+ before: str | None = None
83
+ after: str | None = None
84
+ reason: str | None = None # set when no edit could be considered
85
+ rendered: Rendered | None = None
86
+ refused: list[tuple[Edit, str]] = field(default_factory=list)
87
+
88
+ @property
89
+ def diff(self) -> str:
90
+ if self.location.path is None or self.before is None or self.after is None:
91
+ return ""
92
+ return unified_diff(self.location.path, self.before, self.after)
93
+
94
+
95
+ def plan(root: str | Path, url: str, edits: Sequence[Edit], *,
96
+ detection: Detection | None = None) -> Planned:
97
+ """Plan `edits` for the file that serves `url`. Reads only."""
98
+ root = Path(root)
99
+ detection = detection or detect(root)
100
+ chosen = for_detection(detection)
101
+ location = locate(url, detection=detection, root=root)
102
+ if isinstance(chosen, str):
103
+ return Planned(url, detection, location, None, reason=chosen,
104
+ refused=[(e, chosen) for e in edits])
105
+
106
+ def whole(reason: str) -> Planned:
107
+ return Planned(url, detection, location, chosen.name, reason=reason,
108
+ refused=[(e, reason) for e in edits])
109
+
110
+ if location.path is None:
111
+ return whole(f"skipped: no source file could be located for {url} "
112
+ f"({detection.framework}); nothing is guessed")
113
+ if not chosen.owns(location.path):
114
+ return whole(f"skipped: {location.path} is not a file the {chosen.name} adapter "
115
+ f"edits ({', '.join(chosen.suffixes)})")
116
+ routes = blast_radius(location, detection=detection, root=root)
117
+ if routes != 1:
118
+ seen = "an unknown number of" if routes is None else str(routes)
119
+ return whole(f"refused: {location.path} serves {seen} routes; a page-level "
120
+ "value written there would apply to every one of them")
121
+ text = read_text(root / location.path)
122
+ if text is None:
123
+ return whole(f"refused: {location.path} could not be read as UTF-8 text")
124
+ rendered = chosen.render(Context(root, location.path), text, edits)
125
+ return Planned(url, detection, location, chosen.name, before=text,
126
+ after=rendered.text, rendered=rendered,
127
+ refused=list(rendered.refused))
128
+
129
+
130
+ def explain(location: Location, root: Path, detection: Detection) -> str | None:
131
+ """The adapter's own file-wide refusal (e.g. Next.js `generateMetadata`),
132
+ used to say WHY a located file is not editable. Reads only."""
133
+ chosen = for_detection(detection)
134
+ if isinstance(chosen, str) or location.path is None or not chosen.owns(location.path):
135
+ return None
136
+ text = read_text(root / location.path)
137
+ return None if text is None else chosen.describe(Context(root, location.path), text)
138
+
139
+
140
+ # --- mechanical findings through adapters (apply only) -------------------------------------
141
+
142
+ ROUTED = ("seo.canonical.missing", "seo.canonical.chained")
143
+ _ROUTED_FRAMEWORKS = ("next-app-router", "astro")
144
+
145
+
146
+ def route_finding(finding: Finding, location: Location, root: Path,
147
+ findings: Sequence[Finding], detection: Detection) -> FixOutcome | None:
148
+ """An adapter-made outcome for `finding`, or None to use the generator.
149
+
150
+ Only for Next.js and Astro pages, and only `seo.canonical.missing` (add a
151
+ canonical where none is declared) and `seo.canonical.chained` (repoint an
152
+ existing canonical at a proven-terminal target). Called after the
153
+ applicability gate in `fixes.generate`, so the tier, locator-confidence
154
+ and blast-radius ceilings have already passed.
155
+ """
156
+ if finding.id not in ROUTED or detection.framework not in _ROUTED_FRAMEWORKS:
157
+ return None
158
+ chosen = for_detection(detection)
159
+ if isinstance(chosen, str) or location.path is None or not chosen.owns(location.path):
160
+ return None
161
+ from ..fixes.canonical import onward_target
162
+
163
+ if finding.id == "seo.canonical.chained":
164
+ onward = onward_target(finding.observed)
165
+ if onward is None:
166
+ return outcome(finding, location, reason=(
167
+ "the onward target could not be recovered from the finding text; "
168
+ "refusing to guess which URL this canonical should point at"))
169
+ if any(other.id == "seo.canonical.chained" and other.url == onward
170
+ for other in findings):
171
+ return outcome(finding, location, reason=(
172
+ f"{onward} is not terminal -- it canonicalises onward too, so "
173
+ "repointing here would land mid-chain again"))
174
+ target, mode = onward, "replace"
175
+ else:
176
+ target, mode = finding.url, "insert"
177
+ try:
178
+ edit = replace(set_canonical(target), mode=mode)
179
+ except ValueError as exc:
180
+ return outcome(finding, location, reason=f"refused: the canonical URL is not "
181
+ f"usable ({exc})")
182
+ text = read_text(root / location.path)
183
+ if text is None:
184
+ return outcome(finding, location,
185
+ reason=f"{location.path} could not be read as UTF-8 text")
186
+ rendered = chosen.render(Context(root, location.path), text, [edit])
187
+ made = _adapter_outcome(finding, location, chosen, text, rendered)
188
+ return made
189
+
190
+
191
+ def _adapter_outcome(finding: Finding, location: Location, adapter: Adapter,
192
+ text: str, rendered: Rendered) -> FixOutcome:
193
+ if rendered.refused:
194
+ return outcome(finding, location, reason=f"{adapter.name} adapter: "
195
+ f"{rendered.refused[0][1]}")
196
+ if rendered.unchanged:
197
+ return outcome(finding, location, reason="already in the desired state")
198
+ diff = unified_diff(location.path or "", text, rendered.text)
199
+ made = outcome(finding, location, diff=diff)
200
+ return FixOutcome(finding_id=made.finding_id, url=made.url, fix_tier=made.fix_tier,
201
+ applicability=made.applicability, path=made.path, diff=made.diff,
202
+ reason=None, adapter=adapter.name)
@@ -0,0 +1,338 @@
1
+ """Astro adapter: a page's `<head>`, or the props it passes to its layout.
2
+
3
+ Two page shapes are recognised; everything else is refused:
4
+
5
+ 1. **The page has its own `<head>`.** Tags are edited exactly as in plain HTML
6
+ (shared `Markup` machinery). A value written as `{name}` is followed to a
7
+ `const name = "..."` in the frontmatter and that literal is edited -- only
8
+ when `name` is used exactly once, so the edit cannot leak into another tag.
9
+ Any other expression is refused.
10
+ 2. **The page is wrapped in one layout component** (`<Base title="...">...
11
+ </Base>`, imported from an `.astro` file). The layout is READ, never
12
+ written: an edit is made only when the layout renders that tag from a prop
13
+ (`<title>{title}</title>` with `title` from `Astro.props`), and then the
14
+ page's prop is set. A layout that hard-codes the tag, or does not render it,
15
+ is refused -- editing the layout would change every page that uses it.
16
+
17
+ JSON-LD is written as `<script type="application/ld+json" set:html={"..."} />`
18
+ (a JS string literal, so Astro never parses the JSON as an expression), in the
19
+ `<head>` for shape 1 and as the first child of the layout element for shape 2.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import re
25
+
26
+ from ..fixes.base import newline_style
27
+ from .base import (
28
+ Adapter,
29
+ Context,
30
+ Edit,
31
+ Refused,
32
+ check_mode,
33
+ compact_jsonld,
34
+ js_string,
35
+ jsonld_match,
36
+ jsonld_type,
37
+ line_indent,
38
+ parse_js_string,
39
+ )
40
+ from .html import Markup, Tag, _is_ldjson, _script_body, canonical_tags, edit_head, meta_tags
41
+
42
+ _FRONTMATTER = re.compile(r"\A(?)---[ \t]*\r?\n(.*?)(?:\r?\n)?---[ \t]*(?:\r?\n|\Z)",
43
+ re.DOTALL)
44
+ _IMPORT = re.compile(r"""^\s*import\s+([A-Za-z_$][\w$]*)\s+from\s+(['"])([^'"]+\.astro)\2""",
45
+ re.MULTILINE)
46
+ _PROPS = re.compile(r"\bconst\s*\{([^{}]*)\}\s*=\s*Astro\.props\b")
47
+ _IDENT = re.compile(r"[A-Za-z_$][\w$]*")
48
+
49
+
50
+ def split(text: str) -> tuple[int, int, int]:
51
+ """(frontmatter body start, frontmatter body end, template start)."""
52
+ match = _FRONTMATTER.match(text)
53
+ if match is None:
54
+ if text.lstrip("").startswith("---"):
55
+ raise Refused("the frontmatter fence is not closed")
56
+ return 0, 0, 0
57
+ return match.start(2), match.end(2), match.end()
58
+
59
+
60
+ def _resolver(text: str, fm: tuple[int, int], template_start: int):
61
+ def resolve(expr: str) -> tuple[int, int, str, str]:
62
+ name = expr.strip()
63
+ if not _IDENT.fullmatch(name):
64
+ raise Refused(f"the value is an expression ({{{expr.strip()}}}), not text "
65
+ "OmniRank can read")
66
+ front = text[fm[0]:fm[1]]
67
+ decls = list(re.finditer(rf"\b(const|let|var)\s+{re.escape(name)}\b\s*=\s*", front))
68
+ if len(decls) != 1 or decls[0].group(1) != "const":
69
+ raise Refused(f"{{{name}}} is not a single `const {name} = \"...\"` in the "
70
+ "frontmatter")
71
+ start = fm[0] + decls[0].end()
72
+ quote = text[start:start + 1]
73
+ if quote not in "'\"`":
74
+ raise Refused(f"`const {name}` is not a string literal")
75
+ end = start + 1
76
+ while end < len(text) and text[end] != quote:
77
+ end += 2 if text[end] == "\\" else 1
78
+ value = parse_js_string(text[start:end + 1])
79
+ if value is None or not re.match(r"[ \t]*(?:;|\r?\n|\Z)", text[end + 1:fm[1]] or ""):
80
+ raise Refused(f"`const {name}` is not a plain string literal")
81
+ uses = _uses(name, front) + sum(
82
+ _uses(name, expr) for expr in re.findall(r"\{([^{}]*)\}", text[template_start:]))
83
+ if uses != 2:
84
+ raise Refused(f"`{name}` is used {uses - 1} times; editing it would change "
85
+ "more than this one tag")
86
+ return start, end + 1, value, quote if quote in "'\"" else '"'
87
+ return resolve
88
+
89
+
90
+ _STRINGS = re.compile(r"""'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`"""
91
+ r"|//[^\n]*|/\*.*?\*/", re.DOTALL)
92
+
93
+
94
+ def _uses(name: str, code: str) -> int:
95
+ """How often identifier `name` occurs in JS `code`, ignoring strings/comments."""
96
+ bare = _STRINGS.sub("''", code)
97
+ return len(re.findall(rf"(?<![\w$.]){re.escape(name)}(?![\w$])", bare))
98
+
99
+
100
+ def _ld_scripts(doc: Markup) -> list[tuple[Tag, str, int, int, object | None]]:
101
+ """(tag, form, value start, value end, parsed JSON or None if computed)."""
102
+ out = []
103
+ for tag in doc.tags("script"):
104
+ if not _is_ldjson(tag):
105
+ continue
106
+ html = tag.attr("set:html")
107
+ if html is not None:
108
+ if html.kind == "expr":
109
+ raw = (html.value or "").strip()
110
+ value = parse_js_string(raw)
111
+ if value is None:
112
+ out.append((tag, "computed", 0, 0, None))
113
+ continue
114
+ offset = html.value_start + 1 + (html.value or "").index(raw)
115
+ out.append((tag, "literal", offset, offset + len(raw), _loads(value)))
116
+ else:
117
+ out.append((tag, "attr", html.value_start, html.value_end,
118
+ _loads(html.value or "")))
119
+ continue
120
+ if tag.self_closing:
121
+ continue
122
+ start, end = _script_body(doc, tag)
123
+ out.append((tag, "body", start, end, _loads(doc.text[start:end])))
124
+ return out
125
+
126
+
127
+ def _loads(raw: str):
128
+ try:
129
+ return json.loads(raw)
130
+ except (json.JSONDecodeError, RecursionError) as exc:
131
+ raise Refused("an existing JSON-LD block does not parse; fix it first so a "
132
+ "duplicate node is never added beside it") from exc
133
+
134
+
135
+ def _jsonld(doc: Markup, edit: Edit, insert) -> str:
136
+ wanted = edit.value
137
+ matches = []
138
+ for _tag, form, start, end, existing in _ld_scripts(doc):
139
+ if form == "computed":
140
+ raise Refused("an existing JSON-LD <script> is computed (set:html with an "
141
+ "expression), so it cannot be proven to be a different node; "
142
+ "refusing to add a second one")
143
+ if jsonld_match(existing, wanted):
144
+ matches.append((form, start, end, existing))
145
+ if len(matches) > 1:
146
+ raise Refused(f"{len(matches)} JSON-LD blocks hold {jsonld_type(wanted)}; "
147
+ "which one to replace is ambiguous")
148
+ if matches:
149
+ form, start, end, existing = matches[0]
150
+ if existing == wanted:
151
+ return doc.text
152
+ if form == "literal":
153
+ return doc.splice(start, end, js_string(compact_jsonld(wanted)))
154
+ if form == "body":
155
+ return doc.splice(start, end, compact_jsonld(wanted))
156
+ raise Refused("the existing JSON-LD block is a quoted set:html attribute; "
157
+ "rewrite it as set:html={...} first")
158
+ element = (f'<script type="application/ld+json" '
159
+ f"set:html={{{js_string(compact_jsonld(wanted))}}} />")
160
+ return insert(element)
161
+
162
+
163
+ # --- shape 2: a page wrapped in a layout component ----------------------------------------
164
+
165
+
166
+ def _wrapper(text: str, fm: tuple[int, int], template_start: int) -> tuple[str, str] | None:
167
+ """(component name, import path) when the template is one imported
168
+ `.astro` component wrapping everything, else None."""
169
+ doc = Markup(text, start=template_start, astro=True)
170
+ first = re.compile(r"<([A-Za-z][\w.]*)").search(text, template_start)
171
+ while first is not None and not doc.live(first.start()):
172
+ first = re.compile(r"<([A-Za-z][\w.]*)").search(text, first.end())
173
+ if first is None or not first.group(1)[:1].isupper():
174
+ return None
175
+ name = first.group(1)
176
+ imports = {m.group(1): m.group(3) for m in _IMPORT.finditer(text[fm[0]:fm[1]])}
177
+ if name not in imports:
178
+ return None
179
+ if not text.rstrip().endswith(f"</{name}>") or len(doc.tags(name)) != 1:
180
+ return None
181
+ if re.sub(r"<!--.*?-->", "", text[template_start:first.start()], flags=re.DOTALL).strip():
182
+ return None
183
+ return name, imports[name]
184
+
185
+
186
+ def _layout_prop(layout: str, layout_rel: str, edit: Edit) -> str:
187
+ """The prop name through which the layout renders `edit`'s tag."""
188
+ fm0, fm1, tstart = split(layout)
189
+ front = layout[fm0:fm1]
190
+ local_to_prop: dict[str, str] = {}
191
+ for match in _PROPS.finditer(front):
192
+ for part in match.group(1).split(","):
193
+ part = part.split("=")[0].strip()
194
+ if not part or part.startswith("..."):
195
+ continue
196
+ prop, _, local = part.partition(":")
197
+ prop, local = prop.strip(), (local.strip() or prop.strip())
198
+ if _IDENT.fullmatch(prop) and _IDENT.fullmatch(local):
199
+ local_to_prop[local] = prop
200
+
201
+ def prop_of(expr: str | None) -> str | None:
202
+ expr = (expr or "").strip()
203
+ direct = re.fullmatch(r"Astro\.props\.([A-Za-z_$][\w$]*)", expr)
204
+ if direct:
205
+ return direct.group(1)
206
+ return local_to_prop.get(expr)
207
+
208
+ doc = Markup(layout, start=tstart, astro=True)
209
+ what = {"title": "<title>", "description": "<meta name=description>",
210
+ "robots": "<meta name=robots>", "canonical": "<link rel=canonical>",
211
+ "og": f"<meta property={edit.name}>", "lang": "<html lang>"}[edit.kind]
212
+ if edit.kind == "title":
213
+ tags = doc.tags("title")
214
+ if len(tags) == 1:
215
+ close = re.compile(r"</title\s*>", re.IGNORECASE).search(layout, tags[0].end)
216
+ body = layout[tags[0].end:close.start()] if close else ""
217
+ expr = re.fullmatch(r"\s*\{([^{}]*)\}\s*", body)
218
+ prop = prop_of(expr.group(1)) if expr else None
219
+ if prop:
220
+ return prop
221
+ else:
222
+ if edit.kind == "lang":
223
+ tags, attr = doc.tags("html"), "lang"
224
+ elif edit.kind == "canonical":
225
+ tags, attr = canonical_tags(doc), "href"
226
+ else:
227
+ tags, attr = meta_tags(doc, edit)[0], "content"
228
+ if len(tags) == 1:
229
+ value = tags[0].attr(attr)
230
+ prop = prop_of(value.value) if value is not None and value.kind == "expr" else None
231
+ if prop:
232
+ return prop
233
+ elif len(tags) > 1:
234
+ raise Refused(f"the layout {layout_rel} renders {len(tags)} {what} tags")
235
+ raise Refused(f"the page's <head> comes from the layout {layout_rel}, which does not "
236
+ f"render {what} from a prop; editing the layout would change every "
237
+ "page that uses it, so set it there by hand")
238
+
239
+
240
+ class AstroAdapter(Adapter):
241
+ name = "astro"
242
+ frameworks = ("astro",)
243
+ suffixes = (".astro",)
244
+
245
+ def edit_one(self, ctx: Context, text: str, edit: Edit) -> str:
246
+ fm0, fm1, tstart = split(text)
247
+ doc = Markup(text, start=tstart, astro=True,
248
+ resolve=_resolver(text, (fm0, fm1), tstart))
249
+ try:
250
+ doc.head()
251
+ has_head = True
252
+ except Refused:
253
+ has_head = bool(re.search(r"</head\s*>", text[tstart:], re.IGNORECASE))
254
+ if has_head:
255
+ raise
256
+ if has_head:
257
+ if edit.kind == "jsonld":
258
+ return _jsonld(doc, edit, lambda element: doc.insert_in_head(
259
+ [element], element))
260
+ return edit_head(doc, edit)
261
+ return self._via_layout(ctx, text, doc, (fm0, fm1), tstart, edit)
262
+
263
+ def _via_layout(self, ctx: Context, text: str, doc: Markup, fm, tstart, edit) -> str:
264
+ wrapper = _wrapper(text, fm, tstart)
265
+ if wrapper is None:
266
+ raise Refused("the page has no <head> and is not one imported layout "
267
+ "component wrapping the whole template; where its head tags "
268
+ "come from cannot be proven")
269
+ name, spec = wrapper
270
+ tag = doc.tags(name)[0]
271
+ if edit.kind == "jsonld":
272
+ if tag.self_closing:
273
+ raise Refused(f"<{name} /> has no children to add a JSON-LD <script> to")
274
+
275
+ def insert(element: str) -> str:
276
+ eol = newline_style(text)
277
+ indent = line_indent(text, tag.start) + " "
278
+ return text[:tag.end] + f"{eol}{indent}{element}" + text[tag.end:]
279
+ return _jsonld(doc, edit, insert)
280
+ if not spec.startswith("."):
281
+ raise Refused(f"the layout {spec} is not a relative import inside the project")
282
+ root = ctx.root.resolve()
283
+ layout_path = (ctx.path.parent / spec).resolve()
284
+ if not layout_path.is_relative_to(root) or not layout_path.is_file():
285
+ raise Refused(f"the layout {spec} is not a file inside the project")
286
+ try:
287
+ layout = layout_path.read_text(encoding="utf-8")
288
+ except (OSError, UnicodeDecodeError) as exc:
289
+ raise Refused(f"the layout {spec} cannot be read ({exc})") from exc
290
+ layout_rel = layout_path.relative_to(root).as_posix()
291
+ prop = _layout_prop(layout, layout_rel, edit)
292
+ check_mode(edit, tag.attr(prop) is not None, f"a {prop} prop on <{name}>")
293
+ compare = {"title": lambda a, b: " ".join(a.split()) == " ".join(b.split()),
294
+ "lang": lambda a, b: a.strip().lower() == b.lower()}.get(
295
+ edit.kind, lambda a, b: a.strip() == b.strip())
296
+ return doc.set_attr(tag, prop, edit.text, compare=compare)
297
+
298
+ def jsonld_health(self, text: str) -> tuple[int, int]:
299
+ try:
300
+ _, _, tstart = split(text)
301
+ doc = Markup(text, start=tstart, astro=True)
302
+ found = _ld_scripts_lenient(doc)
303
+ except Refused:
304
+ return (-1, -1)
305
+ return len(found), sum(1 for ok in found if ok)
306
+
307
+
308
+ def _ld_scripts_lenient(doc: Markup) -> list[bool]:
309
+ """Like `_ld_scripts`, but a block that does not parse counts as not-ok."""
310
+ out = []
311
+ for tag in doc.tags("script"):
312
+ if not _is_ldjson(tag):
313
+ continue
314
+ html = tag.attr("set:html")
315
+ if html is not None:
316
+ raw = (html.value or "").strip()
317
+ if html.kind == "expr":
318
+ value = parse_js_string(raw)
319
+ if value is None:
320
+ out.append(True) # computed: counted, not evaluated
321
+ continue
322
+ raw = value
323
+ out.append(_parses(raw))
324
+ continue
325
+ if tag.self_closing:
326
+ continue
327
+ start, end = _script_body(doc, tag)
328
+ out.append(_parses(doc.text[start:end]))
329
+ return out
330
+
331
+
332
+ def _parses(raw: str) -> bool:
333
+ try:
334
+ json.loads(raw)
335
+ return True
336
+ except (json.JSONDecodeError, RecursionError):
337
+ return False
338
+