omnirank 0.5.0__py3-none-any.whl

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 (183) hide show
  1. omnirank/__init__.py +14 -0
  2. omnirank/__main__.py +6 -0
  3. omnirank/adapters/__init__.py +202 -0
  4. omnirank/adapters/astro.py +338 -0
  5. omnirank/adapters/base.py +372 -0
  6. omnirank/adapters/html.py +561 -0
  7. omnirank/adapters/jsx.py +340 -0
  8. omnirank/adapters/nextjs.py +692 -0
  9. omnirank/aeo/__init__.py +9 -0
  10. omnirank/aeo/extract.py +383 -0
  11. omnirank/aeo/propose.py +84 -0
  12. omnirank/aeo/rules.py +964 -0
  13. omnirank/aeo/runner.py +148 -0
  14. omnirank/applicability.py +98 -0
  15. omnirank/apply/__init__.py +23 -0
  16. omnirank/apply/engine.py +1254 -0
  17. omnirank/apply/journal.py +139 -0
  18. omnirank/apply/patch.py +144 -0
  19. omnirank/audit.py +185 -0
  20. omnirank/bands.py +106 -0
  21. omnirank/brief/__init__.py +0 -0
  22. omnirank/brief/analyze.py +197 -0
  23. omnirank/brief/constants.py +89 -0
  24. omnirank/brief/cost.py +62 -0
  25. omnirank/brief/egress.py +23 -0
  26. omnirank/brief/fetchpages.py +239 -0
  27. omnirank/brief/render.py +151 -0
  28. omnirank/brief/runner.py +369 -0
  29. omnirank/brief/serp.py +274 -0
  30. omnirank/brief/text.py +181 -0
  31. omnirank/cli.py +844 -0
  32. omnirank/clock.py +22 -0
  33. omnirank/cms/__init__.py +1 -0
  34. omnirank/cms/runner.py +170 -0
  35. omnirank/cms/wordpress.py +495 -0
  36. omnirank/cms/wordpress_apply.py +508 -0
  37. omnirank/cms/wordpress_plan.py +280 -0
  38. omnirank/config.py +81 -0
  39. omnirank/connect/__init__.py +4 -0
  40. omnirank/connect/bing.py +284 -0
  41. omnirank/connect/cloud_setup.py +43 -0
  42. omnirank/connect/confirm.py +242 -0
  43. omnirank/connect/constants.py +226 -0
  44. omnirank/connect/doctor.py +270 -0
  45. omnirank/connect/ga4.py +749 -0
  46. omnirank/connect/ga4_ai.py +123 -0
  47. omnirank/connect/google_auth.py +657 -0
  48. omnirank/connect/gsc.py +630 -0
  49. omnirank/connect/gsc_reports.py +169 -0
  50. omnirank/connect/http.py +310 -0
  51. omnirank/connect/indexnow.py +373 -0
  52. omnirank/connect/naver.py +536 -0
  53. omnirank/connect/runner.py +515 -0
  54. omnirank/connect/runner_ga4_ai.py +59 -0
  55. omnirank/connect/runner_more.py +489 -0
  56. omnirank/connect/runner_regional.py +260 -0
  57. omnirank/connect/secrets.py +190 -0
  58. omnirank/connect/urlcheck.py +41 -0
  59. omnirank/connect/yandex.py +350 -0
  60. omnirank/crawl/__init__.py +11 -0
  61. omnirank/crawl/analyze.py +493 -0
  62. omnirank/crawl/crawler.py +491 -0
  63. omnirank/crawl/custom.py +175 -0
  64. omnirank/crawl/export.py +67 -0
  65. omnirank/crawl/fetcher.py +212 -0
  66. omnirank/crawl/parse.py +102 -0
  67. omnirank/crawl/render.py +148 -0
  68. omnirank/crawl/robotsgate.py +198 -0
  69. omnirank/crawl/runner.py +295 -0
  70. omnirank/crawl/sitemap.py +99 -0
  71. omnirank/crawl/text.py +20 -0
  72. omnirank/crawl/urls.py +100 -0
  73. omnirank/crawlers.py +564 -0
  74. omnirank/data/ai_crawlers.json +269 -0
  75. omnirank/data/ai_referrers.json +42 -0
  76. omnirank/fetch.py +107 -0
  77. omnirank/fixes/__init__.py +92 -0
  78. omnirank/fixes/base.py +232 -0
  79. omnirank/fixes/canonical.py +243 -0
  80. omnirank/fixes/schema.py +126 -0
  81. omnirank/formats.py +134 -0
  82. omnirank/framework.py +223 -0
  83. omnirank/gates/__init__.py +48 -0
  84. omnirank/gates/aeo.py +114 -0
  85. omnirank/gates/contradictions.py +280 -0
  86. omnirank/gates/crawler_policy.py +85 -0
  87. omnirank/gates/geo.py +152 -0
  88. omnirank/gates/hygiene.py +81 -0
  89. omnirank/gates/jsonld.py +282 -0
  90. omnirank/gates/onpage.py +177 -0
  91. omnirank/gates/perf.py +115 -0
  92. omnirank/gates/security.py +264 -0
  93. omnirank/gates/seo.py +118 -0
  94. omnirank/gates/site.py +248 -0
  95. omnirank/geo_artifacts.py +199 -0
  96. omnirank/html.py +79 -0
  97. omnirank/keywords/__init__.py +5 -0
  98. omnirank/keywords/constants.py +69 -0
  99. omnirank/keywords/engine.py +384 -0
  100. omnirank/keywords/report.py +143 -0
  101. omnirank/keywords/runner.py +160 -0
  102. omnirank/keywords/source.py +60 -0
  103. omnirank/keywords/text.py +45 -0
  104. omnirank/locator.py +480 -0
  105. omnirank/logs/__init__.py +0 -0
  106. omnirank/logs/analyze.py +127 -0
  107. omnirank/logs/bots.py +69 -0
  108. omnirank/logs/ipranges.py +191 -0
  109. omnirank/logs/parse.py +452 -0
  110. omnirank/logs/paths.py +22 -0
  111. omnirank/logs/privacy.py +105 -0
  112. omnirank/logs/runner.py +179 -0
  113. omnirank/mcp_server.py +1480 -0
  114. omnirank/netguard.py +525 -0
  115. omnirank/packs/__init__.py +6 -0
  116. omnirank/packs/backlinks.py +535 -0
  117. omnirank/packs/blog.py +544 -0
  118. omnirank/packs/blog_cross.py +468 -0
  119. omnirank/packs/crawlers.py +23 -0
  120. omnirank/packs/entity.py +492 -0
  121. omnirank/packs/feeds.py +150 -0
  122. omnirank/packs/frontmatter.py +59 -0
  123. omnirank/packs/gsc.py +421 -0
  124. omnirank/packs/local.py +879 -0
  125. omnirank/packs/mdscan.py +326 -0
  126. omnirank/packs/miniyaml.py +378 -0
  127. omnirank/packs/model.py +46 -0
  128. omnirank/packs/product.py +979 -0
  129. omnirank/packs/refresh.py +165 -0
  130. omnirank/packs/runner.py +277 -0
  131. omnirank/packs/sitescan.py +294 -0
  132. omnirank/packs/textsafe.py +79 -0
  133. omnirank/packs/xmlsafe.py +92 -0
  134. omnirank/page.py +42 -0
  135. omnirank/registry.py +302 -0
  136. omnirank/report.py +251 -0
  137. omnirank/report_cmd/__init__.py +7 -0
  138. omnirank/report_cmd/delta.py +58 -0
  139. omnirank/report_cmd/files.py +64 -0
  140. omnirank/report_cmd/model.py +208 -0
  141. omnirank/report_cmd/notify.py +195 -0
  142. omnirank/report_cmd/pdf.py +83 -0
  143. omnirank/report_cmd/portfolio.py +342 -0
  144. omnirank/report_cmd/render.py +379 -0
  145. omnirank/report_cmd/runner.py +267 -0
  146. omnirank/robots.py +172 -0
  147. omnirank/scanner/__init__.py +10 -0
  148. omnirank/scanner/badge.py +90 -0
  149. omnirank/scanner/cache.py +69 -0
  150. omnirank/scanner/cli.py +96 -0
  151. omnirank/scanner/engine.py +289 -0
  152. omnirank/scanner/limits.py +98 -0
  153. omnirank/scanner/server.py +143 -0
  154. omnirank/scanner/service.py +328 -0
  155. omnirank/schema/__init__.py +13 -0
  156. omnirank/schema/catalog.py +679 -0
  157. omnirank/schema/catalog_specs.py +350 -0
  158. omnirank/schema/core.py +306 -0
  159. omnirank/schema/extract.py +396 -0
  160. omnirank/schema/gate.py +121 -0
  161. omnirank/schema/runner.py +213 -0
  162. omnirank/schema/validate.py +504 -0
  163. omnirank/schema/vocab.py +305 -0
  164. omnirank/schemas/omnirank.config.schema.json +268 -0
  165. omnirank/track/__init__.py +0 -0
  166. omnirank/track/ai_prompts.py +207 -0
  167. omnirank/track/analysis.py +197 -0
  168. omnirank/track/constants.py +155 -0
  169. omnirank/track/cost.py +229 -0
  170. omnirank/track/discover.py +277 -0
  171. omnirank/track/discover_cli.py +309 -0
  172. omnirank/track/discover_constants.py +95 -0
  173. omnirank/track/engines.py +216 -0
  174. omnirank/track/estimate_view.py +212 -0
  175. omnirank/track/history.py +261 -0
  176. omnirank/track/runner.py +586 -0
  177. omnirank/track/stats.py +138 -0
  178. omnirank/track/storage.py +128 -0
  179. omnirank-0.5.0.dist-info/METADATA +47 -0
  180. omnirank-0.5.0.dist-info/RECORD +183 -0
  181. omnirank-0.5.0.dist-info/WHEEL +5 -0
  182. omnirank-0.5.0.dist-info/entry_points.txt +2 -0
  183. omnirank-0.5.0.dist-info/top_level.txt +1 -0
omnirank/packs/blog.py ADDED
@@ -0,0 +1,544 @@
1
+ """Blog pack (spec section 8). Read-only: reads a content directory, writes nothing.
2
+
3
+ What it checks, and the honest limits of each check, are in docs/blog-pack.md. The rules
4
+ that shape every check here:
5
+
6
+ * Nothing is defaulted. A missing author, date or description is reported; it is never
7
+ filled from a file's mtime, a git date, the directory name or the first paragraph.
8
+ * Hidden content (HTML comments, fenced code, elements hidden from readers) is never
9
+ evidence for a visible date or a link.
10
+ * A check that cannot be decided from the files (ambiguous sitemap match, no git) says so
11
+ in ``notes`` instead of guessing.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import re
17
+ import unicodedata
18
+ from dataclasses import dataclass, field
19
+ from datetime import date, datetime
20
+ from pathlib import Path
21
+ from urllib.parse import unquote, urlsplit
22
+
23
+ from ..clock import today as clock_today
24
+ from . import feeds as feedmod
25
+ from .frontmatter import Frontmatter, split
26
+ from .mdscan import (
27
+ Line,
28
+ explicit_anchor_ids,
29
+ headings,
30
+ hidden_line_numbers,
31
+ html_tags,
32
+ inline_refs,
33
+ prose_lines,
34
+ strip_inline_code,
35
+ word_count,
36
+ )
37
+ from .model import ADVICE, ERROR, WARNING, PackError, PackFinding
38
+
39
+ MD_SUFFIXES = {".md", ".mdx", ".markdown"}
40
+ SKIP_DIRS = {"node_modules", ".git", ".omnirank", "dist", "build", "out", "_site", ".next",
41
+ ".astro", ".nuxt", ".svelte-kit", "vendor", "venv", ".venv", "__pycache__",
42
+ "target", "coverage"}
43
+ SKIP_STEMS = {"readme", "changelog", "license", "licence", "contributing", "code_of_conduct",
44
+ "agents", "claude", "gemini", "security", "notice", "authors", "history"}
45
+ ARCHIVE_DIRS = {"tags", "tag", "categories", "category"}
46
+ ARCHIVE_TYPES = {"tag", "category", "archive", "taxonomy"}
47
+ MAX_FILE_BYTES = 2_000_000
48
+ MAX_FILES = 20_000
49
+ MAX_DEPTH = 12
50
+ WPM = 200
51
+ THIN_ARCHIVE_POSTS = 3
52
+ TOC_MIN_WORDS = 1200
53
+ TOC_MIN_HEADINGS = 5
54
+ MAX_SUGGESTIONS_PER_POST = 5
55
+ NO_WORD_BOUNDARY_LANGS = ("zh", "ja", "ko", "th", "lo", "km", "my")
56
+ IMAGE_DIRS = ("", "public", "static", "assets", "src", "src/assets", "content", "app", "web")
57
+
58
+ ALIASES = {
59
+ "title": ("title",),
60
+ "description": ("description", "summary", "excerpt"),
61
+ "date": ("date", "datePublished", "published", "pubDate", "publishDate"),
62
+ "updated": ("updated", "dateModified", "lastmod", "modified", "last_modified_at"),
63
+ "author": ("author", "authors"),
64
+ "tags": ("tags", "keywords"),
65
+ "canonical": ("canonical", "canonicalUrl", "canonical_url"),
66
+ "image": ("image", "cover", "featured_image", "thumbnail", "og_image"),
67
+ "language": ("language", "lang"),
68
+ "slug": ("slug",),
69
+ }
70
+ TOC_HEADINGS = {"table of contents", "contents", "toc", "on this page", "in this article",
71
+ "সূচিপত্র"}
72
+ GENERIC_ALTS = {"image", "img", "photo", "picture", "pic", "screenshot", "graphic",
73
+ "untitled", "image of", "photo of", "picture of", "banner", "thumbnail"}
74
+ FILENAME_PREFIXES = ("img", "dsc", "dscn", "pxl", "mvimg", "image", "photo", "picture",
75
+ "untitled", "unnamed", "capture", "scan", "screenshot", "screen shot",
76
+ "snapshot")
77
+ FATAL_FM = {"fm-unterminated", "fm-binary", "fm-too-large", "fm-toml-unsupported",
78
+ "fm-too-deep"}
79
+
80
+
81
+ @dataclass
82
+ class _Post:
83
+ path: str
84
+ abs: Path
85
+ fm: Frontmatter
86
+ lines: list[Line] = field(default_factory=list)
87
+ slug: str = ""
88
+ stem: str = ""
89
+ title: str | None = None
90
+ draft: bool = False
91
+ ok: bool = False
92
+ archive: bool = False
93
+ words: int = 0
94
+ tags: list[str] = field(default_factory=list)
95
+ heads: list = field(default_factory=list)
96
+ refs: list = field(default_factory=list) # (line_no, Ref)
97
+ out_slugs: set[str] = field(default_factory=set)
98
+ dates: dict = field(default_factory=dict)
99
+ raw: str = ""
100
+
101
+
102
+ @dataclass
103
+ class BlogReport:
104
+ root: str
105
+ findings: list[PackFinding] = field(default_factory=list)
106
+ posts: list[dict] = field(default_factory=list)
107
+ clusters: list[dict] = field(default_factory=list)
108
+ link_suggestions: list[dict] = field(default_factory=list)
109
+ gsc: dict | None = None
110
+ notes: list[str] = field(default_factory=list)
111
+ assumptions: dict = field(default_factory=dict)
112
+
113
+ def to_dict(self) -> dict:
114
+ return {
115
+ "root": self.root, "writes": False,
116
+ "findings": [f.to_dict() for f in self.findings],
117
+ "posts": self.posts, "clusters": self.clusters,
118
+ "linkSuggestions": self.link_suggestions, "gsc": self.gsc,
119
+ "notes": self.notes, "assumptions": self.assumptions,
120
+ }
121
+
122
+
123
+ # --- small helpers ---------------------------------------------------------------------
124
+
125
+
126
+ def _nfc(text: str) -> str:
127
+ return unicodedata.normalize("NFC", text)
128
+
129
+
130
+ def _pick(data: dict, field_name: str):
131
+ for key in ALIASES[field_name]:
132
+ if key in data and data[key] is not None:
133
+ return key, data[key]
134
+ return None, None
135
+
136
+
137
+ def parse_iso_date(value) -> date | None:
138
+ """A real calendar date in extended ISO 8601 (YYYY-MM-DD[Thh:mm[:ss][zone]]), else None."""
139
+ if not isinstance(value, str):
140
+ return None
141
+ s = value.strip()
142
+ if len(s) < 10 or len(s) > 40 or s[4] != "-" or s[7] != "-":
143
+ return None
144
+ if len(s) > 10 and s[10] not in "T ":
145
+ return None
146
+ try:
147
+ if len(s) == 10:
148
+ return date.fromisoformat(s)
149
+ return datetime.fromisoformat(s).date()
150
+ except ValueError:
151
+ return None
152
+
153
+
154
+ def _key_line(text: str, key: str) -> int | None:
155
+ lines = text.removeprefix("").split("\n", 600)
156
+ for idx, ln in enumerate(lines[:600]):
157
+ if ln.startswith((key + ":", f'"{key}":')):
158
+ return idx + 1
159
+ return None
160
+
161
+
162
+ def _as_text(value) -> str | None:
163
+ if isinstance(value, str) and value.strip():
164
+ return value.strip()
165
+ return None
166
+
167
+
168
+ def _is_absolute_url(value) -> bool:
169
+ if not isinstance(value, str) or len(value) > 2000:
170
+ return False
171
+ parts = urlsplit(value.strip())
172
+ return parts.scheme in ("http", "https") and bool(parts.netloc)
173
+
174
+
175
+ _LANG_OK = re.compile(r"[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,4}")
176
+
177
+
178
+ def _language_ok(value) -> bool:
179
+ return isinstance(value, str) and len(value) <= 35 and bool(_LANG_OK.fullmatch(value.strip()))
180
+
181
+
182
+ # --- discovery ----------------------------------------------------------------------------
183
+
184
+
185
+ def _walk(root: Path, notes: list[str]):
186
+ md, html, xmls = [], [], []
187
+ seen = 0
188
+ for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
189
+ rel_depth = len(Path(dirpath).relative_to(root).parts)
190
+ dirnames[:] = sorted(d for d in dirnames
191
+ if d not in SKIP_DIRS and not d.startswith(".")
192
+ and rel_depth < MAX_DEPTH)
193
+ for name in sorted(filenames):
194
+ seen += 1
195
+ if seen > MAX_FILES:
196
+ notes.append(f"scan stopped after {MAX_FILES} files; the rest was not read")
197
+ return md, html, xmls
198
+ p = Path(dirpath) / name
199
+ if p.is_symlink():
200
+ continue
201
+ suffix = p.suffix.lower()
202
+ if suffix in MD_SUFFIXES:
203
+ if p.stem.lower() in SKIP_STEMS:
204
+ continue
205
+ md.append(p)
206
+ elif suffix in (".html", ".htm"):
207
+ html.append(p)
208
+ elif suffix == ".xml" or name.lower() in feedmod.FEED_NAMES:
209
+ xmls.append(p)
210
+ return md, html, xmls
211
+
212
+
213
+ def _rel(root: Path, p: Path) -> str:
214
+ return p.relative_to(root).as_posix()
215
+
216
+
217
+ # --- the pack ------------------------------------------------------------------------------
218
+
219
+
220
+ class _Run:
221
+ def __init__(self, root: Path, today: date):
222
+ self.root = root
223
+ self.today = today
224
+ self.rep = BlogReport(str(root))
225
+ self.rep.assumptions = {
226
+ "reading_time_wpm": WPM, "thin_archive_posts": THIN_ARCHIVE_POSTS,
227
+ "toc_min_words": TOC_MIN_WORDS, "toc_min_headings": TOC_MIN_HEADINGS,
228
+ "dates_compared_as": "calendar date as written (no time zone conversion)",
229
+ "images": "markdown and <img> in prose; fenced code and HTML comments are skipped",
230
+ }
231
+ self.posts: list[_Post] = []
232
+ self.own_hosts: set[str] = set()
233
+
234
+ # -- reporting
235
+ def add(self, id_, severity, message, evidence, path=None, line=None):
236
+ self.rep.findings.append(PackFinding(id_, severity, message, evidence, path, line))
237
+
238
+ def note(self, text):
239
+ self.rep.notes.append(text)
240
+
241
+ # -- loading
242
+ def load_posts(self, md_files):
243
+ for p in md_files:
244
+ rel = _rel(self.root, p)
245
+ try:
246
+ size = p.stat().st_size
247
+ except OSError:
248
+ continue
249
+ if size > MAX_FILE_BYTES:
250
+ self.add("blog.file.too-large", WARNING,
251
+ f"{size} bytes is over the {MAX_FILE_BYTES} byte limit; file not read",
252
+ "[guideline]", rel)
253
+ continue
254
+ try:
255
+ text = p.read_bytes().decode("utf-8")
256
+ except (OSError, UnicodeDecodeError) as exc:
257
+ self.add("blog.file.unreadable", ERROR,
258
+ f"cannot read as UTF-8 text: {exc.__class__.__name__}",
259
+ "[guideline]", rel)
260
+ continue
261
+ fm = split(text)
262
+ post = _Post(rel, p, fm, raw=text)
263
+ parts = Path(rel).parts
264
+ post.archive = (_as_text(fm.data.get("type")) or "").lower() in ARCHIVE_TYPES \
265
+ or any(part.lower() in ARCHIVE_DIRS for part in parts[:-1])
266
+ stem = _nfc(p.stem if p.stem.lower() not in ("index", "_index") else p.parent.name)
267
+ post.stem = stem
268
+ fatal = any(i.code in FATAL_FM for i in fm.issues)
269
+ for issue in fm.issues:
270
+ sev = ERROR if issue.code in FATAL_FM else WARNING
271
+ self.add(f"blog.fm.{issue.code[3:]}", sev, issue.message, "[guideline]", rel,
272
+ issue.line)
273
+ post.ok = not fatal and (fm.present or post.archive)
274
+ if not fm.present and not post.archive:
275
+ self.add("blog.fm.missing", WARNING,
276
+ "no frontmatter block; the post has no title, description, date or "
277
+ "author for the checks (and none is invented)", "[guideline]", rel, 1)
278
+ data = fm.data if post.ok else {}
279
+ _, slug = _pick(data, "slug")
280
+ post.slug = _nfc(slug.strip()) if isinstance(slug, str) and slug.strip() else stem
281
+ _, t = _pick(data, "title")
282
+ post.title = _as_text(t)
283
+ post.draft = data.get("draft") is True or str(data.get("draft")).lower() == "true"
284
+ _, tg = _pick(data, "tags")
285
+ if isinstance(tg, list):
286
+ post.tags = [t.strip() for t in tg if isinstance(t, str) and t.strip()]
287
+ body_lines, _unclosed = prose_lines(fm.body, fm.body_line) if post.ok else ([], False)
288
+ post.lines = body_lines
289
+ post.words = word_count(body_lines)
290
+ self.posts.append(post)
291
+
292
+ # -- per-post validation ---------------------------------------------------------------
293
+ def validate_post(self, p: _Post):
294
+ if not p.ok or p.archive:
295
+ return
296
+ data, text_path = p.fm.data, p.path
297
+ raw = p.raw
298
+
299
+ def line_for(key):
300
+ return _key_line(raw, key) or 1
301
+
302
+ # required-ish fields: reported, never defaulted
303
+ if not p.title:
304
+ self.add("blog.field.title-missing", WARNING,
305
+ "no title in frontmatter (not defaulted from the heading or filename)",
306
+ "[guideline]", text_path, 1)
307
+ if not _as_text(_pick(data, "description")[1]):
308
+ self.add("blog.field.description-missing", WARNING,
309
+ "no description in frontmatter (not defaulted from the first paragraph)",
310
+ "[guideline]", text_path, 1)
311
+ dkey, dval = _pick(data, "date")
312
+ if dval is None:
313
+ self.add("blog.field.date-missing", WARNING,
314
+ "no publish date in frontmatter; file mtime and git dates are never used "
315
+ "as a substitute", "[guideline]", text_path, 1)
316
+ aval = _pick(data, "author")[1]
317
+ has_author = bool(_as_text(aval)) or (isinstance(aval, dict) and _as_text(aval.get("name"))) \
318
+ or (isinstance(aval, list) and any(_as_text(x) or (isinstance(x, dict) and _as_text(x.get("name")))
319
+ for x in aval))
320
+ if not has_author:
321
+ self.add("blog.field.author-missing", WARNING,
322
+ "no author in frontmatter; an author is never defaulted (not from the "
323
+ "site, the git committer or the filename)", "[guideline]", text_path, 1)
324
+ tkey, tval = _pick(data, "tags")
325
+ if tval is not None and not (isinstance(tval, list)
326
+ and all(isinstance(t, str) for t in tval)):
327
+ self.add("blog.field.tags-type", WARNING,
328
+ f"{tkey} must be a list of strings, got {type(tval).__name__}",
329
+ "[guideline]", text_path, line_for(tkey))
330
+ ckey, cval = _pick(data, "canonical")
331
+ if cval is not None and not _is_absolute_url(cval):
332
+ self.add("blog.field.canonical-url", WARNING,
333
+ f"{ckey} {str(cval)[:80]!r} is not an absolute http(s) URL",
334
+ "[standard]", text_path, line_for(ckey))
335
+ lkey, lval = _pick(data, "language")
336
+ if lval is not None and not _language_ok(lval):
337
+ self.add("blog.field.language-code", WARNING,
338
+ f"{lkey} {str(lval)[:40]!r} is not a language tag such as 'en' or 'bn'",
339
+ "[standard]", text_path, line_for(lkey))
340
+ skey, sval = _pick(data, "slug")
341
+ if sval is not None:
342
+ bad = not isinstance(sval, str) or not sval.strip() or any(
343
+ c.isspace() or c in '?#&%<>"\\' or ("A" <= c <= "Z") for c in sval)
344
+ if bad:
345
+ self.add("blog.field.slug-format", WARNING,
346
+ f"slug {str(sval)[:60]!r} contains whitespace, upper-case ASCII or "
347
+ "URL-reserved characters", "[guideline]", text_path, line_for(skey))
348
+ # dates
349
+ dates: dict[str, date | None] = {}
350
+ for fname, key, val in (("date", dkey, dval), ("updated", *_pick(data, "updated"))):
351
+ if val is None:
352
+ dates[fname] = None
353
+ continue
354
+ parsed = parse_iso_date(val)
355
+ dates[fname] = parsed
356
+ if parsed is None:
357
+ self.add("blog.date.format", ERROR,
358
+ f"{key} {str(val)[:40]!r} is not an ISO 8601 date (YYYY-MM-DD) or a "
359
+ "real calendar date", "[standard]", text_path, line_for(key))
360
+ elif parsed > self.today:
361
+ self.add("blog.date.future", WARNING,
362
+ f"{key} {parsed.isoformat()} is after today ({self.today.isoformat()}); "
363
+ "keep scheduled posts as drafts until they are live",
364
+ "[guideline]", text_path, line_for(key))
365
+ if dates.get("date") and dates.get("updated") and dates["updated"] < dates["date"]:
366
+ self.add("blog.date.updated-before-published", ERROR,
367
+ f"updated {dates['updated'].isoformat()} is earlier than the publish date "
368
+ f"{dates['date'].isoformat()}", "[guideline]", text_path,
369
+ line_for(_pick(data, "updated")[0]))
370
+ p.dates = dates
371
+ # image (frontmatter)
372
+ ikey, ival = _pick(data, "image")
373
+ if isinstance(ival, str) and ival.strip():
374
+ self.check_image_target(p, ival.strip(), line_for(ikey), where="frontmatter image")
375
+ self.check_body(p)
376
+
377
+ def check_body(self, p: _Post):
378
+ lines = p.lines
379
+ hs = headings(lines)
380
+ p.heads = hs
381
+ text_all = "\n".join(ln.text for ln in lines)
382
+ valid_ids = {h.anchor for h in hs} | explicit_anchor_ids(text_all)
383
+ # duplicate heading anchors
384
+ groups: dict[str, list] = {}
385
+ for h in hs:
386
+ if not h.custom and h.base:
387
+ groups.setdefault(h.base, []).append(h)
388
+ for base, items in groups.items():
389
+ if len(items) > 1:
390
+ self.add("blog.anchors.duplicate", ADVICE,
391
+ f"{len(items)} headings share the anchor {base!r} (lines "
392
+ f"{', '.join(str(i.line) for i in items)}); generators number the "
393
+ f"later ones ({base}-1, ...), so deep links to them depend on the "
394
+ "numbering scheme. Rename the headings for stable anchors",
395
+ "[guideline]", p.path, items[1].line)
396
+ # TOC
397
+ toc_fm = p.fm.data.get("toc")
398
+ has_toc = bool(toc_fm) and str(toc_fm).lower() != "false"
399
+ has_toc = has_toc or any(h.text.strip().lower() in TOC_HEADINGS for h in hs) \
400
+ or "[toc]" in text_all.lower() or "{:toc}" in text_all.lower() \
401
+ or "<!-- toc" in p.fm.body.lower()
402
+ mid = [h for h in hs if h.level in (2, 3)]
403
+ if p.words >= TOC_MIN_WORDS and len(mid) >= TOC_MIN_HEADINGS and not has_toc:
404
+ self.add("blog.toc.missing", ADVICE,
405
+ f"{p.words} words and {len(mid)} h2/h3 headings but no table of contents "
406
+ "(many themes generate one; ignore this if yours does)",
407
+ "[guideline]", p.path, mid[0].line)
408
+ hidden = hidden_line_numbers(lines)
409
+ # links and images, line by line (so findings carry a line number)
410
+ for ln in lines:
411
+ if ln.no in hidden:
412
+ continue
413
+ for ref in inline_refs(ln.text):
414
+ if ref.kind == "image":
415
+ self.check_image_ref(p, ln.no, ref.text, ref.target, None)
416
+ else:
417
+ tgt = ref.target
418
+ if tgt.startswith("#"):
419
+ frag = _nfc(unquote(tgt[1:]))
420
+ if frag and frag not in {_nfc(v) for v in valid_ids}:
421
+ self.add("blog.anchors.broken", WARNING,
422
+ f"link to #{frag} but no heading or id produces that "
423
+ "anchor (generators differ in how they slugify; check "
424
+ "your site's output)", "[guideline]", p.path, ln.no)
425
+ else:
426
+ p.refs.append((ln.no, ref))
427
+ for _, attrs, raw in html_tags(strip_inline_code(ln.text), "img"):
428
+ self.check_image_ref(p, ln.no, attrs.get("alt"), attrs.get("src", ""), attrs,
429
+ raw_html=True)
430
+
431
+ # -- images
432
+ def resolve_local(self, base_dir: Path, target: str) -> Path | None | bool:
433
+ """Path if found, False if not found, None if the target is not a local file."""
434
+ t = target.split("#", 1)[0].split("?", 1)[0].strip()
435
+ t = unquote(t)
436
+ if not t or t.startswith(("http://", "https://", "//", "data:", "@", "~", "mailto:")) \
437
+ or any(m in t for m in ("{{", "${", "<%", "{%")):
438
+ return None
439
+ rootp = self.root.resolve()
440
+ cands: list[Path] = []
441
+ if t.startswith("/"):
442
+ cands += [self.root / d / t.lstrip("/") for d in IMAGE_DIRS]
443
+ else:
444
+ cands.append(base_dir / t)
445
+ clean = t
446
+ while clean.startswith(("./", "../")):
447
+ clean = clean.split("/", 1)[1]
448
+ cands += [self.root / d / clean for d in IMAGE_DIRS]
449
+ for c in cands:
450
+ try:
451
+ rc = c.resolve()
452
+ if rc.is_relative_to(rootp) and rc.is_file():
453
+ return rc
454
+ except (OSError, ValueError, RuntimeError):
455
+ continue
456
+ return False
457
+
458
+ def check_image_target(self, p: _Post, target: str, line: int, where: str):
459
+ found = self.resolve_local(p.abs.parent, target)
460
+ if found is False:
461
+ self.add("blog.image.missing-file", ERROR,
462
+ f"{where} {target!r}: no such file under the project",
463
+ "[guideline]", p.path, line)
464
+ stem = Path(unquote(target.split("?", 1)[0])).stem
465
+ if stem and self.generic_filename(stem) and not target.startswith(("http://", "https://")):
466
+ self.add("blog.image.filename", ADVICE,
467
+ f"{where} file name {Path(target).name!r} is camera/auto-generated; a "
468
+ "descriptive file name tells readers and crawlers what the image shows",
469
+ "[guideline]", p.path, line)
470
+
471
+ @staticmethod
472
+ def generic_filename(stem: str) -> bool:
473
+ s = stem.casefold()
474
+ if len(s) > 200:
475
+ return False
476
+ if len(s) >= 16 and all(c in "0123456789abcdef" for c in s):
477
+ return True
478
+ if len(s) >= 6 and s.isdigit():
479
+ return True
480
+ for pre in FILENAME_PREFIXES:
481
+ if s.startswith(pre):
482
+ rest = s[len(pre):]
483
+ if pre in ("screenshot", "screen shot", "snapshot"):
484
+ return True
485
+ if all(c.isdigit() or c in " _-()." for c in rest):
486
+ return True
487
+ return False
488
+
489
+ def check_image_ref(self, p: _Post, line: int, alt, src: str, attrs, raw_html=False):
490
+ if not src:
491
+ return
492
+ found = self.resolve_local(p.abs.parent, src)
493
+ if found is False:
494
+ self.add("blog.image.missing-file", ERROR, f"image {src!r}: no such file under "
495
+ "the project", "[guideline]", p.path, line)
496
+ name = Path(unquote(src.split("#", 1)[0].split("?", 1)[0])).name
497
+ if raw_html:
498
+ if alt is None:
499
+ self.add("blog.image.no-alt", WARNING, f"<img src={src!r}> has no alt "
500
+ "attribute (use alt=\"\" only for purely decorative images)",
501
+ "[standard]", p.path, line)
502
+ if attrs is not None and not (attrs.get("width") and attrs.get("height")):
503
+ self.add("blog.image.no-dimensions", ADVICE,
504
+ f"<img src={src!r}> has no width and height; reserving the space "
505
+ "avoids layout shift while the image loads", "[guideline]", p.path, line)
506
+ elif not (alt or "").strip():
507
+ self.add("blog.image.no-alt", WARNING,
508
+ f"image {src!r} has empty alt text; describe it, or use "
509
+ "<img alt=\"\"> if it is decorative", "[standard]", p.path, line)
510
+ if alt and alt.strip():
511
+ a = alt.strip().casefold()
512
+ stem = Path(name).stem.casefold()
513
+ generic = a in GENERIC_ALTS or a == name.casefold() or a == stem or (
514
+ a.rstrip("0123456789 _-") in GENERIC_ALTS and a != a.rstrip("0123456789 _-"))
515
+ if generic:
516
+ self.add("blog.image.generic-alt", ADVICE,
517
+ f"alt text {alt.strip()!r} on {src!r} does not describe the image",
518
+ "[guideline]", p.path, line)
519
+ stem = Path(name).stem
520
+ if stem and self.generic_filename(stem) and not src.startswith(("http://", "https://")):
521
+ self.add("blog.image.filename", ADVICE,
522
+ f"image file name {name!r} is camera/auto-generated; a descriptive "
523
+ "file name tells readers and crawlers what the image shows",
524
+ "[guideline]", p.path, line)
525
+
526
+
527
+ def run_blog(root: str | Path, *, gsc_csv: str | Path | None = None,
528
+ gsc_prev_csv: str | Path | None = None, today: date | None = None,
529
+ use_git: bool = True) -> BlogReport:
530
+ root = Path(root)
531
+ if not root.is_dir():
532
+ raise PackError(f"--root {root} is not a directory")
533
+ try:
534
+ run = _Run(root, today or clock_today())
535
+ except ValueError as exc:
536
+ raise PackError(str(exc)) from None
537
+ md, html, xmls = _walk(root, run.rep.notes)
538
+ run.load_posts(md)
539
+ for p in run.posts:
540
+ run.validate_post(p)
541
+ from .blog_cross import cross_checks # split for size; see blog_cross.py
542
+ cross_checks(run, html, xmls, gsc_csv, gsc_prev_csv, use_git)
543
+ run.rep.findings.sort(key=lambda f: (f.path or "", f.line or 0, f.id, f.message))
544
+ return run.rep