seo-supervisor 1.2.0 → 2.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.
Files changed (207) hide show
  1. package/.claude-plugin/icon.png +0 -0
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.claude-plugin/plugin.json +16 -3
  4. package/CHANGELOG.md +430 -0
  5. package/NOTICE +7 -0
  6. package/README.md +230 -25
  7. package/agents/seo-auditor.md +16 -0
  8. package/agents/seo-reviewer.md +16 -0
  9. package/bin/agents.mjs +194 -29
  10. package/bin/extras.mjs +422 -0
  11. package/bin/prompt.mjs +34 -14
  12. package/bin/seo-supervisor.mjs +386 -53
  13. package/commands/seo-audit.md +29 -3
  14. package/commands/seo-brief.md +28 -0
  15. package/commands/seo-connect.md +27 -0
  16. package/commands/seo-fix.md +24 -3
  17. package/commands/seo-grow.md +26 -0
  18. package/commands/seo-launch.md +17 -3
  19. package/commands/seo-review.md +13 -1
  20. package/commands/seo-rewrite.md +25 -0
  21. package/commands/seo-setup.md +17 -1
  22. package/commands/seo-watch.md +28 -0
  23. package/hooks/hooks.json +117 -0
  24. package/package.json +20 -7
  25. package/skills/seo-supervisor/NOTICE +7 -0
  26. package/skills/seo-supervisor/SKILL.md +302 -21
  27. package/skills/seo-supervisor/audience.md +61 -0
  28. package/skills/seo-supervisor/examples/drafts/security.md +41 -0
  29. package/skills/seo-supervisor/examples/hooks/README.md +28 -0
  30. package/skills/seo-supervisor/examples/hooks/claude-code-settings.json +15 -0
  31. package/skills/seo-supervisor/examples/hooks/codex-hooks.json +17 -0
  32. package/skills/seo-supervisor/examples/hooks/copilot-hooks.json +15 -0
  33. package/skills/seo-supervisor/examples/hooks/cursor-hooks.json +11 -0
  34. package/skills/seo-supervisor/examples/hooks/github-actions.yml +21 -0
  35. package/skills/seo-supervisor/examples/hooks/pre-commit +17 -0
  36. package/skills/seo-supervisor/examples/hooks/reading-ease.yml +24 -0
  37. package/skills/seo-supervisor/examples/sample-audit.json +94 -2
  38. package/skills/seo-supervisor/examples/sample-report.html +111 -61
  39. package/skills/seo-supervisor/examples/sample-report.md +147 -44
  40. package/skills/seo-supervisor/examples/scheduled-runs.md +89 -0
  41. package/skills/seo-supervisor/examples/snippets.md +648 -1
  42. package/skills/seo-supervisor/grow.md +342 -0
  43. package/skills/seo-supervisor/og-images.md +85 -0
  44. package/skills/seo-supervisor/page-types.md +124 -0
  45. package/skills/seo-supervisor/planning.md +19 -7
  46. package/skills/seo-supervisor/profile-template.md +41 -0
  47. package/skills/seo-supervisor/report-format.md +177 -10
  48. package/skills/seo-supervisor/rewrite.md +59 -0
  49. package/skills/seo-supervisor/rules/ai-search.md +65 -12
  50. package/skills/seo-supervisor/rules/content.md +33 -9
  51. package/skills/seo-supervisor/rules/crawl-index.md +33 -6
  52. package/skills/seo-supervisor/rules/internal-linking.md +49 -6
  53. package/skills/seo-supervisor/rules/launch-monitoring.md +17 -8
  54. package/skills/seo-supervisor/rules/media.md +13 -1
  55. package/skills/seo-supervisor/rules/metadata.md +41 -9
  56. package/skills/seo-supervisor/rules/performance.md +50 -5
  57. package/skills/seo-supervisor/rules/rendering.md +39 -2
  58. package/skills/seo-supervisor/rules/search-intent.md +32 -0
  59. package/skills/seo-supervisor/rules/sitemaps-robots.md +24 -12
  60. package/skills/seo-supervisor/rules/structured-data.md +37 -14
  61. package/skills/seo-supervisor/rules/trust-security.md +25 -2
  62. package/skills/seo-supervisor/rules/urls.md +10 -2
  63. package/skills/seo-supervisor/scripts/ai-answers.mjs +314 -0
  64. package/skills/seo-supervisor/scripts/backlinks.mjs +412 -0
  65. package/skills/seo-supervisor/scripts/change-check.mjs +281 -0
  66. package/skills/seo-supervisor/scripts/checks/agents.mjs +488 -0
  67. package/skills/seo-supervisor/scripts/checks/assets.mjs +404 -0
  68. package/skills/seo-supervisor/scripts/checks/bots.mjs +146 -0
  69. package/skills/seo-supervisor/scripts/checks/business-type.mjs +193 -0
  70. package/skills/seo-supervisor/scripts/checks/content.mjs +391 -0
  71. package/skills/seo-supervisor/scripts/checks/coverage.mjs +184 -0
  72. package/skills/seo-supervisor/scripts/checks/crawl.mjs +95 -0
  73. package/skills/seo-supervisor/scripts/checks/hreflang.mjs +396 -0
  74. package/skills/seo-supervisor/scripts/checks/hygiene.mjs +227 -0
  75. package/skills/seo-supervisor/scripts/checks/lighthouse.mjs +271 -0
  76. package/skills/seo-supervisor/scripts/checks/link-strength.mjs +59 -0
  77. package/skills/seo-supervisor/scripts/checks/links.mjs +360 -0
  78. package/skills/seo-supervisor/scripts/checks/local.mjs +101 -0
  79. package/skills/seo-supervisor/scripts/checks/media.mjs +194 -0
  80. package/skills/seo-supervisor/scripts/checks/outbound.mjs +53 -0
  81. package/skills/seo-supervisor/scripts/checks/page.mjs +223 -0
  82. package/skills/seo-supervisor/scripts/checks/probes.mjs +130 -0
  83. package/skills/seo-supervisor/scripts/checks/render.mjs +552 -0
  84. package/skills/seo-supervisor/scripts/checks/robots.mjs +144 -0
  85. package/skills/seo-supervisor/scripts/checks/schema.mjs +206 -0
  86. package/skills/seo-supervisor/scripts/checks/site-agents.mjs +79 -0
  87. package/skills/seo-supervisor/scripts/checks/site-content.mjs +135 -0
  88. package/skills/seo-supervisor/scripts/checks/site-hygiene.mjs +202 -0
  89. package/skills/seo-supervisor/scripts/checks/site-pages.mjs +474 -0
  90. package/skills/seo-supervisor/scripts/checks/site-security.mjs +102 -0
  91. package/skills/seo-supervisor/scripts/checks/sitemap.mjs +473 -0
  92. package/skills/seo-supervisor/scripts/checks/speed.mjs +267 -0
  93. package/skills/seo-supervisor/scripts/checks/technical.mjs +368 -0
  94. package/skills/seo-supervisor/scripts/checks/tls.mjs +297 -0
  95. package/skills/seo-supervisor/scripts/checks/trust.mjs +421 -0
  96. package/skills/seo-supervisor/scripts/checks/visual.mjs +1132 -0
  97. package/skills/seo-supervisor/scripts/checks/writing.mjs +192 -0
  98. package/skills/seo-supervisor/scripts/commoncrawl.mjs +452 -0
  99. package/skills/seo-supervisor/scripts/connect-keys.mjs +422 -0
  100. package/skills/seo-supervisor/scripts/content-scan.mjs +515 -158
  101. package/skills/seo-supervisor/scripts/crawl/catalog.mjs +1248 -0
  102. package/skills/seo-supervisor/scripts/crawl/fetch.mjs +362 -0
  103. package/skills/seo-supervisor/scripts/crawl/page.mjs +741 -0
  104. package/skills/seo-supervisor/scripts/crawl/queue.mjs +190 -0
  105. package/skills/seo-supervisor/scripts/dashboard.mjs +140 -0
  106. package/skills/seo-supervisor/scripts/data/ai-bots.json +38 -0
  107. package/skills/seo-supervisor/scripts/data/build-schema-vocab.mjs +57 -0
  108. package/skills/seo-supervisor/scripts/data/business-types.json +338 -0
  109. package/skills/seo-supervisor/scripts/data/google-rich-results.json +79 -0
  110. package/skills/seo-supervisor/scripts/data/schema-vocab.json +1 -0
  111. package/skills/seo-supervisor/scripts/deploy-check.mjs +462 -0
  112. package/skills/seo-supervisor/scripts/disavow.mjs +176 -0
  113. package/skills/seo-supervisor/scripts/doctor.mjs +174 -0
  114. package/skills/seo-supervisor/scripts/geo-grid.mjs +371 -0
  115. package/skills/seo-supervisor/scripts/google/search-console.mjs +151 -0
  116. package/skills/seo-supervisor/scripts/google/session.mjs +167 -0
  117. package/skills/seo-supervisor/scripts/google-updates.mjs +189 -0
  118. package/skills/seo-supervisor/scripts/google.mjs +1341 -0
  119. package/skills/seo-supervisor/scripts/gsc-import.mjs +298 -0
  120. package/skills/seo-supervisor/scripts/guard/adapters/claude-code.mjs +149 -0
  121. package/skills/seo-supervisor/scripts/guard/adapters/cline.mjs +28 -0
  122. package/skills/seo-supervisor/scripts/guard/adapters/codex.mjs +26 -0
  123. package/skills/seo-supervisor/scripts/guard/adapters/copilot.mjs +36 -0
  124. package/skills/seo-supervisor/scripts/guard/adapters/cursor.mjs +33 -0
  125. package/skills/seo-supervisor/scripts/guard/adapters/devin.mjs +25 -0
  126. package/skills/seo-supervisor/scripts/guard/adapters/edits.mjs +124 -0
  127. package/skills/seo-supervisor/scripts/guard/mode.mjs +37 -0
  128. package/skills/seo-supervisor/scripts/guard/rules.mjs +931 -0
  129. package/skills/seo-supervisor/scripts/guard.mjs +74 -0
  130. package/skills/seo-supervisor/scripts/images.mjs +408 -0
  131. package/skills/seo-supervisor/scripts/indexnow.mjs +300 -0
  132. package/skills/seo-supervisor/scripts/issues.mjs +217 -0
  133. package/skills/seo-supervisor/scripts/keys/authority.mjs +135 -0
  134. package/skills/seo-supervisor/scripts/keys/bing.mjs +239 -0
  135. package/skills/seo-supervisor/scripts/keys/clarity.mjs +137 -0
  136. package/skills/seo-supervisor/scripts/keys/dataforseo.mjs +57 -0
  137. package/skills/seo-supervisor/scripts/keys/googleplaces.mjs +26 -0
  138. package/skills/seo-supervisor/scripts/keys/http.mjs +212 -0
  139. package/skills/seo-supervisor/scripts/keys/matomo.mjs +138 -0
  140. package/skills/seo-supervisor/scripts/keys/openai.mjs +26 -0
  141. package/skills/seo-supervisor/scripts/keys/perplexity.mjs +26 -0
  142. package/skills/seo-supervisor/scripts/keys/posthog.mjs +165 -0
  143. package/skills/seo-supervisor/scripts/keys/semrush.mjs +25 -0
  144. package/skills/seo-supervisor/scripts/keys/services.mjs +41 -0
  145. package/skills/seo-supervisor/scripts/keys/store.mjs +140 -0
  146. package/skills/seo-supervisor/scripts/keys/visits.mjs +58 -0
  147. package/skills/seo-supervisor/scripts/keys/youtube.mjs +84 -0
  148. package/skills/seo-supervisor/scripts/keyword-data.mjs +316 -0
  149. package/skills/seo-supervisor/scripts/keyword-ideas.mjs +503 -0
  150. package/skills/seo-supervisor/scripts/lib/args.mjs +56 -0
  151. package/skills/seo-supervisor/scripts/lib/business.mjs +27 -0
  152. package/skills/seo-supervisor/scripts/lib/cdp.mjs +242 -0
  153. package/skills/seo-supervisor/scripts/lib/cli.mjs +56 -0
  154. package/skills/seo-supervisor/scripts/lib/csv.mjs +38 -0
  155. package/skills/seo-supervisor/scripts/lib/findings.mjs +100 -0
  156. package/skills/seo-supervisor/scripts/lib/google-client.mjs +9 -0
  157. package/skills/seo-supervisor/scripts/lib/html.mjs +146 -0
  158. package/skills/seo-supervisor/scripts/lib/http.mjs +28 -0
  159. package/skills/seo-supervisor/scripts/lib/image-size.mjs +78 -0
  160. package/skills/seo-supervisor/scripts/lib/is-main.mjs +13 -0
  161. package/skills/seo-supervisor/scripts/lib/net.mjs +116 -0
  162. package/skills/seo-supervisor/scripts/lib/proxy.mjs +47 -0
  163. package/skills/seo-supervisor/scripts/lib/recheck.mjs +106 -0
  164. package/skills/seo-supervisor/scripts/lib/redact.mjs +78 -0
  165. package/skills/seo-supervisor/scripts/lib/robots.mjs +73 -0
  166. package/skills/seo-supervisor/scripts/lib/score.mjs +266 -0
  167. package/skills/seo-supervisor/scripts/lib/settings-dir.mjs +81 -0
  168. package/skills/seo-supervisor/scripts/links-import.mjs +603 -0
  169. package/skills/seo-supervisor/scripts/log-scan.mjs +597 -0
  170. package/skills/seo-supervisor/scripts/og-card.mjs +273 -0
  171. package/skills/seo-supervisor/scripts/osm.mjs +359 -0
  172. package/skills/seo-supervisor/scripts/rdap.mjs +164 -0
  173. package/skills/seo-supervisor/scripts/render-report.mjs +324 -690
  174. package/skills/seo-supervisor/scripts/report/client.js +37 -0
  175. package/skills/seo-supervisor/scripts/report/diff.mjs +264 -0
  176. package/skills/seo-supervisor/scripts/report/findings.mjs +165 -0
  177. package/skills/seo-supervisor/scripts/report/format.mjs +111 -0
  178. package/skills/seo-supervisor/scripts/report/markdown.mjs +250 -0
  179. package/skills/seo-supervisor/scripts/report/model.mjs +171 -0
  180. package/skills/seo-supervisor/scripts/report/overview-lines.mjs +158 -0
  181. package/skills/seo-supervisor/scripts/report/overview.mjs +224 -0
  182. package/skills/seo-supervisor/scripts/report/page.mjs +127 -0
  183. package/skills/seo-supervisor/scripts/report/panel.mjs +172 -0
  184. package/skills/seo-supervisor/scripts/report/panels/ai.mjs +211 -0
  185. package/skills/seo-supervisor/scripts/report/panels/connections.mjs +139 -0
  186. package/skills/seo-supervisor/scripts/report/panels/content.mjs +204 -0
  187. package/skills/seo-supervisor/scripts/report/panels/data-search.mjs +379 -0
  188. package/skills/seo-supervisor/scripts/report/panels/data-site.mjs +44 -0
  189. package/skills/seo-supervisor/scripts/report/panels/links.mjs +380 -0
  190. package/skills/seo-supervisor/scripts/report/panels/local.mjs +221 -0
  191. package/skills/seo-supervisor/scripts/report/panels/site.mjs +359 -0
  192. package/skills/seo-supervisor/scripts/report/panels/speed-media.mjs +267 -0
  193. package/skills/seo-supervisor/scripts/report/sources.mjs +163 -0
  194. package/skills/seo-supervisor/scripts/report/styles.css +223 -0
  195. package/skills/seo-supervisor/scripts/report/traffic.mjs +264 -0
  196. package/skills/seo-supervisor/scripts/report-plan.mjs +112 -33
  197. package/skills/seo-supervisor/scripts/schema-check.mjs +717 -0
  198. package/skills/seo-supervisor/scripts/seo-crawl.mjs +1086 -638
  199. package/skills/seo-supervisor/scripts/seo-diff.mjs +584 -0
  200. package/skills/seo-supervisor/scripts/update-check.mjs +82 -0
  201. package/skills/seo-supervisor/site-types/content.md +34 -1
  202. package/skills/seo-supervisor/site-types/ecommerce.md +38 -1
  203. package/skills/seo-supervisor/site-types/local-business.md +96 -6
  204. package/skills/seo-supervisor/site-types/services.md +46 -0
  205. package/skills/seo-supervisor/site-types/tools.md +3 -3
  206. package/skills/seo-supervisor/strategy.md +232 -0
  207. package/skills/seo-supervisor/troubleshooting.md +56 -0
@@ -0,0 +1,1132 @@
1
+ // @ts-check
2
+ // Loads sample pages at desktop and phone size in an installed Chrome or Edge for the phone, render and lab speed
3
+ // checks, with screenshots. The pages' own scripts, analytics included, run.
4
+ import { mkdirSync, writeFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { containerArgs } from "../lib/cdp.mjs";
7
+ import { quote } from "../lib/findings.mjs";
8
+ import { redact } from "../lib/redact.mjs";
9
+ import { addressCheck, compareRendered, gateOf, guardTab, openSession } from "./render.mjs";
10
+
11
+ export const CHECKS = {
12
+ "mobile-content-missing": [
13
+ "REND-07",
14
+ "high",
15
+ n => `${n} page(s) show less content on a phone than on desktop`,
16
+ "Google indexes the mobile version of every page. Text or a heading that only desktop visitors get doesn't count for ranking.",
17
+ "Serve the same main text and H1 at every screen size. Restyle it for small screens (stack it, or collapse it into sections that stay in the HTML) instead of leaving it out of the phone version.",
18
+ ],
19
+ "mobile-overflow": [
20
+ "REND-09",
21
+ "medium",
22
+ n => `${n} page(s) scroll sideways on a phone`,
23
+ "Content wider than the screen makes visitors scroll sideways or zoom out, and reads as a page that isn't built for phones.",
24
+ "Find the wide element (a fixed-width table, image, iframe or long unbroken text) and let it shrink: `max-width: 100%`, `overflow-x: auto` on a wrapper for tables, `overflow-wrap: anywhere` for long words.",
25
+ ],
26
+ "mobile-small-text": [
27
+ "REND-09",
28
+ "low",
29
+ n => `${n} page(s) use body text under 12 px on a phone`,
30
+ "Text this small is hard to read on a phone, so visitors zoom in or leave.",
31
+ "Set body text to at least 16 px on small screens (1rem from the browser's default).",
32
+ ],
33
+ "mobile-interstitial": [
34
+ "PERF-07",
35
+ "high",
36
+ n => `${n} page(s) cover most of the phone screen with a popup on arrival`,
37
+ "Visitors from search see the popup instead of the page they came for. Google's page-experience guidance calls this an intrusive interstitial, and many visitors leave instead of closing it.",
38
+ "Use a small banner instead, or show the popup later (after the visitor interacts). Required age or legal notices should cover only part of the screen.",
39
+ ],
40
+ "input-zoom": [
41
+ "REND-09",
42
+ "low",
43
+ n => `${n} page(s) have form fields with text under 16 px, which iPhones zoom into`,
44
+ "When a visitor taps a field whose text is smaller than 16 px, Safari on iPhone zooms the page in to make it readable (WebKit's rule: 16 px divided by the field's text size), so part of the form moves off the screen while they type.",
45
+ "Set inputs, selects and text areas to `font-size: 16px` (or `1rem`), at least on small screens. Don't stop the zoom with `maximum-scale=1` or `user-scalable=no` in the viewport tag: on Android that also stops visitors zooming in to read.",
46
+ ],
47
+ "tap-targets-small": [
48
+ "REND-09",
49
+ "low",
50
+ n => `${n} page(s) have links or buttons too small and too close together to tap on a phone`,
51
+ "A finger covers more than a small link, so visitors tap the wrong one and have to go back. The accessibility standard (WCAG 2.2, success criterion 2.5.8) asks for at least 24×24 px, or enough space around smaller ones.",
52
+ "Give links and buttons padding so each is at least 24×24 px, or space small ones out: icons in a row need 24 px from the centre of one to the next. Links inside a sentence are fine as they are.",
53
+ ],
54
+ "bfcache-blocked": [
55
+ "PERF-10",
56
+ "medium",
57
+ n => `${n} page(s) load again instead of showing instantly when a visitor goes Back (Chrome's own test)`,
58
+ "Chrome opened the page, went on to another page of the site and pressed Back, and had to load the page again instead of restoring it from memory (the back/forward cache). One in five page views on phones comes from Back or Forward, and a restored page counts as an instant load in Core Web Vitals.",
59
+ "Remove what Chrome names for each page. The usual causes are an `unload` handler (use `pagehide`), `Cache-Control: no-store` on an ordinary page (use `no-cache`), and connections left open (close WebSockets on `pagehide`). Chrome DevTools > Application > Back/forward cache runs the same test.",
60
+ ],
61
+ };
62
+
63
+ const DESKTOP = { width: 1366, height: 768, deviceScaleFactor: 1, mobile: false };
64
+ const PHONE = { width: 390, height: 844, deviceScaleFactor: 3, mobile: true };
65
+ const SLOW_4G = {
66
+ offline: false,
67
+ latency: 150,
68
+ downloadThroughput: (1.6 * 1024 * 1024) / 8,
69
+ uploadThroughput: (750 * 1024) / 8,
70
+ }; // Lighthouse's mobile profile
71
+ const sleep = ms => new Promise(ok => setTimeout(ok, ms));
72
+
73
+ // Resolves at the load event, or after 15 s for a page that never finishes loading.
74
+ const LOADED = `new Promise(ok => { if (document.readyState === "complete") ok(); addEventListener("load", () => ok()); setTimeout(ok, 15000); })`;
75
+ // Two animation frames: the page has laid itself out and drawn at a new size; 250 ms at most (a page with no frames).
76
+ const DRAWN = `new Promise(ok => { requestAnimationFrame(() => requestAnimationFrame(() => ok())); setTimeout(ok, 250); })`;
77
+ // Local cap: each back/forward cache test costs a page load and up to 10 s, so only the first few pages get one.
78
+ const BF_PAGES = 3;
79
+ // Words come from the DOM, so a collapsed accordion or closed <details> still counts, as it does for Google. The popup
80
+ // is the biggest fixed layer on top covering half the screen; consent tools are kept apart.
81
+ const MEASURE = `(() => {
82
+ const shown = e => e.checkVisibility({ opacityProperty: true, visibilityProperty: true }), css = e => getComputedStyle(e);
83
+ const main = document.querySelector("main") || document.body, h1 = document.querySelector("h1");
84
+ const vw = innerWidth, vh = innerHeight;
85
+ const name = e => e.tagName.toLowerCase() + (e.id ? "#" + e.id : "") + (typeof e.className === "string" && e.className.trim() ? "." + e.className.trim().split(/\\s+/).join(".") : "");
86
+ const cmp = e => /onetrust|cookiebot|cybot|didomi|usercentrics|quantcast|qc-cmp|\\bcmp\\b|consent|cookie/i.test(e.id + " " + (typeof e.className === "string" ? e.className : ""));
87
+ const popup = { cover: 0, by: "" }, consent = { cover: 0, by: "" };
88
+ for (const e of document.body.querySelectorAll("*")) {
89
+ const s = css(e);
90
+ if (s.position !== "fixed" || parseInt(s.zIndex) < 0 || !shown(e)) continue;
91
+ if ((main !== document.body && e.contains(main)) || (h1 && e.contains(h1))) continue; // a layer holding the page is an app shell
92
+ const r = e.getBoundingClientRect(), x0 = Math.max(r.left, 0), x1 = Math.min(r.right, vw), y0 = Math.max(r.top, 0), y1 = Math.min(r.bottom, vh);
93
+ const share = Math.max(0, x1 - x0) * Math.max(0, y1 - y0) / (vw * vh);
94
+ if (share < 0.5 || !e.contains(document.elementFromPoint((x0 + x1) / 2, (y0 + y1) / 2))) continue; // a layer behind the content isn't a popup
95
+ let isCmp = [...e.querySelectorAll("[id], [class]")].some(cmp);
96
+ for (let a = e; a && a !== document.body && !isCmp; a = a.parentElement) isCmp = cmp(a);
97
+ const slot = isCmp ? consent : popup;
98
+ if (share > slot.cover) { slot.cover = share; slot.by = name(e); }
99
+ }
100
+ let text = "";
101
+ for (const w = document.createTreeWalker(main, NodeFilter.SHOW_TEXT); w.nextNode();) if (!w.currentNode.parentElement.closest("script, style, noscript, template")) text += " " + w.currentNode.data;
102
+ const sizes = {};
103
+ for (const e of main.querySelectorAll("p, li, td")) { const n = e.textContent.trim().length; if (n && shown(e)) sizes[css(e).fontSize] = (sizes[css(e).fontSize] || 0) + n; }
104
+ return {
105
+ words: text.split(/\\s+/).filter(Boolean).length,
106
+ h1: [...document.querySelectorAll("h1")].filter(shown).map(h => h.innerText.replace(/\\s+/g, " ").trim().toLowerCase()).filter(Boolean),
107
+ viewport: /width\\s*=\\s*device-width/i.test(document.querySelector('meta[name="viewport" i]')?.content || ""),
108
+ scrollWidth: document.documentElement.scrollWidth,
109
+ clipped: [document.documentElement, document.body].some(e => /^(hidden|clip)$/.test(css(e).overflowX)),
110
+ fontSize: parseFloat(Object.entries(sizes).sort((a, b) => b[1] - a[1])[0]?.[0] || css(main).fontSize),
111
+ popup, consent,
112
+ };
113
+ })()`;
114
+ // A target under 24×24 CSS px fails unless a 24 px circle on its centre touches no other target and no other small
115
+ // one's circle. Links in a sentence, visually hidden ones (skip links) and ones off screen sideways (closed drawers)
116
+ // are exempt. Whole-box geometry: a clipped or covered target still counts. Lighthouse 12 uses the same rule.
117
+ // https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum
118
+ const TAPS = `(() => {
119
+ const SEL = 'a[href], button, [role="button"], input[type="button" i], input[type="submit" i], input[type="reset" i], input[type="image" i]';
120
+ const css = e => getComputedStyle(e), letters = s => (s.match(/[\\p{L}\\p{N}]/gu) || []).length;
121
+ const inSentence = e => {
122
+ if (css(e).display !== "inline") return false;
123
+ let b = e.parentElement;
124
+ while (b && css(b).display.startsWith("inline")) b = b.parentElement;
125
+ return !!b && letters(b.textContent) > letters(e.textContent);
126
+ };
127
+ const all = [...document.querySelectorAll(SEL)].filter(e => !e.parentElement?.closest(SEL) && e.checkVisibility({ opacityProperty: true, visibilityProperty: true }))
128
+ .map(e => ({ e, r: e.getBoundingClientRect() })).filter(({ r }) => r.width >= 2 && r.height >= 2 && r.right > 0 && r.left < innerWidth);
129
+ const small = all.filter(x => (x.r.width < 24 || x.r.height < 24) && !inSentence(x.e));
130
+ for (const x of small) x.c = [(x.r.left + x.r.right) / 2, (x.r.top + x.r.bottom) / 2];
131
+ const toBox = ([px, py], r) => Math.hypot(Math.max(r.left - px, 0, px - r.right), Math.max(r.top - py, 0, py - r.bottom));
132
+ const bad = small.filter(x => all.some(y => y !== x && toBox(x.c, y.r) < 12) || small.some(y => y !== x && Math.hypot(x.c[0] - y.c[0], x.c[1] - y.c[1]) < 24));
133
+ const name = e => (e.getAttribute("aria-label") || e.innerText || e.title || e.querySelector("img")?.alt || e.tagName.toLowerCase()).replace(/\\s+/g, " ").trim().slice(0, 40);
134
+ return { count: bad.length, examples: bad.slice(0, 3).map(x => \`“\${name(x.e)}” \${Math.round(x.r.width)}×\${Math.round(x.r.height)} px\`) };
135
+ })()`;
136
+ // iOS Safari zooms a focused field to 16 ÷ its text size, capped at maximum-scale, skips a change under 10%, and
137
+ // doesn't zoom under user-scalable=no. Fields off screen sideways, out of the tab order or inside aria-hidden are
138
+ // skipped: a sign-up form's spam trap is all three (Mailchimp's is).
139
+ // https://github.com/WebKit/WebKit/blob/main/Source/WebKit/UIProcess/API/ios/WKWebViewIOS.mm
140
+ const FIELDS = `(() => {
141
+ const vp = (document.querySelector('meta[name="viewport" i]')?.content || "").toLowerCase();
142
+ const max = /user-scalable\\s*=\\s*(no|0)\\b/.test(vp) ? 1 : parseFloat(vp.match(/maximum-scale\\s*=\\s*([\\d.]+)/)?.[1]) || Infinity;
143
+ const NO_KEYS = /^(hidden|checkbox|radio|button|submit|reset|image|file|range|color)$/i;
144
+ const small = [...document.querySelectorAll("input, select, textarea")]
145
+ .filter(e => !(e.tagName === "INPUT" && NO_KEYS.test(e.type)) && !e.disabled && !e.readOnly && e.tabIndex >= 0 && !e.closest('[aria-hidden="true"]') && e.checkVisibility({ opacityProperty: true, visibilityProperty: true }))
146
+ .map(e => ({ e, r: e.getBoundingClientRect(), size: parseFloat(getComputedStyle(e).fontSize) }))
147
+ .filter(({ r, size }) => r.width >= 2 && r.height >= 2 && r.right > 0 && r.left < innerWidth && size > 0 && Math.min(16 / size, max) >= 1.1);
148
+ const name = e => (e.labels?.[0]?.innerText || e.getAttribute("aria-label") || e.placeholder || e.name || e.type).replace(/\\s+/g, " ").trim().slice(0, 40);
149
+ return { count: small.length, examples: small.slice(0, 3).map(x => \`“\${name(x.e)}” \${Math.round(x.size * 10) / 10} px\`) };
150
+ })()`;
151
+ // Installed before the page's scripts. Blocking time is each long task's part over 50 ms, as in Lighthouse's TBT.
152
+ // Layout shifts without recent input are kept as [time, score] for clsOf.
153
+ const OBSERVE = `window.__seoLab = { lcp: 0, shifts: [], tbt: 0 }; try {
154
+ new PerformanceObserver(l => { for (const e of l.getEntries()) __seoLab.lcp = e.startTime; }).observe({ type: "largest-contentful-paint", buffered: true });
155
+ new PerformanceObserver(l => { for (const e of l.getEntries()) if (!e.hadRecentInput) __seoLab.shifts.push([e.startTime, e.value]); }).observe({ type: "layout-shift", buffered: true });
156
+ new PerformanceObserver(l => { for (const e of l.getEntries()) __seoLab.tbt += Math.max(0, e.duration - 50); }).observe({ type: "longtask", buffered: true });
157
+ } catch {}`;
158
+ /** The largest session window (shifts under 1 s apart, 5 s at most), not the sum of every shift. Runs in the page too.
159
+ * https://web.dev/articles/cls
160
+ * @param {[number, number][]} shifts [time in ms, score], in time order */
161
+ export function clsOf(shifts) {
162
+ let best = 0,
163
+ sum = 0,
164
+ first = 0,
165
+ last = -Infinity;
166
+ for (const [t, v] of shifts) {
167
+ if (t - last < 1000 && t - first < 5000) sum += v;
168
+ else {
169
+ sum = v;
170
+ first = t;
171
+ }
172
+ last = t;
173
+ best = Math.max(best, sum);
174
+ }
175
+ return best;
176
+ }
177
+
178
+ // A phone H1 with at least half the desktop H1's words is the same heading (a desktop-only word or two is fine).
179
+ const seg = new Intl.Segmenter(undefined, { granularity: "word" });
180
+ const wordsOf = s => [...seg.segment(s)].filter(w => w.isWordLike).map(w => w.segment);
181
+ const sameHeading = (desktop, phone) => {
182
+ const have = new Set(wordsOf(phone)),
183
+ want = wordsOf(desktop);
184
+ return want.filter(w => have.has(w)).length >= want.length / 2;
185
+ };
186
+
187
+ async function evaluate(page, expression) {
188
+ const r = await page.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
189
+ if (r.exceptionDetails)
190
+ throw new Error(r.exceptionDetails.exception?.description?.split("\n")[0] || r.exceptionDetails.text);
191
+ return r.result.value;
192
+ }
193
+
194
+ // A fresh tab per load, so emulation and throttling never leak into the next. After the load event the page settles
195
+ // until Chrome's networkIdle (500 ms of quiet) or settleMs, whichever comes first.
196
+ async function visit(chrome, url, { device, userAgent, lab = false, settleMs, deadline, checkAddress }, read) {
197
+ const page = await chrome.newPage();
198
+ page.on("Page.javascriptDialogOpening", () =>
199
+ page.send("Page.handleJavaScriptDialog", { accept: true }).catch(() => {}),
200
+ ); // alert() would stall the page
201
+ // Chrome sends the events again for the blank tab when they're switched on, so only this load's (its loaderId) count.
202
+ const idle = new Set();
203
+ let quiet = () => {};
204
+ page.on("Page.lifecycleEvent", p => {
205
+ if (p.name === "networkIdle") {
206
+ idle.add(p.loaderId);
207
+ quiet();
208
+ }
209
+ });
210
+ const load = async () => {
211
+ await guardTab(page, checkAddress);
212
+ await page.send("Page.enable");
213
+ await page.send("Page.setLifecycleEventsEnabled", { enabled: true });
214
+ await page.send("Page.bringToFront"); // a background tab gets no animation frames
215
+ await page.send("Emulation.setDeviceMetricsOverride", device);
216
+ await page.send("Emulation.setUserAgentOverride", { userAgent });
217
+ if (device.mobile) await page.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 });
218
+ if (lab) {
219
+ await page.send("Network.enable");
220
+ await page.send("Network.setCacheDisabled", { cacheDisabled: true }); // the earlier loads filled the shared cache
221
+ await page.send("Network.emulateNetworkConditions", SLOW_4G);
222
+ await page.send("Emulation.setCPUThrottlingRate", { rate: 4 });
223
+ await page.send("Page.addScriptToEvaluateOnNewDocument", { source: OBSERVE });
224
+ }
225
+ const nav = await page.send("Page.navigate", { url });
226
+ if (nav.errorText) throw new Error(nav.errorText);
227
+ await evaluate(page, LOADED).catch(() => sleep(1000)); // a script redirect replaces the document mid-wait
228
+ await new Promise(ok => {
229
+ const t = setTimeout(ok, settleMs);
230
+ quiet = () => {
231
+ if (idle.has(nav.loaderId)) {
232
+ clearTimeout(t);
233
+ ok(undefined);
234
+ }
235
+ };
236
+ quiet();
237
+ });
238
+ return await read(page);
239
+ };
240
+ let timer;
241
+ const late = new Promise((_, fail) => {
242
+ timer = setTimeout(
243
+ fail,
244
+ Math.max(0, deadline - Date.now()),
245
+ new Error("the page was still busy when its time ran out"),
246
+ );
247
+ });
248
+ try {
249
+ return await Promise.race([load(), late]);
250
+ } finally {
251
+ clearTimeout(timer);
252
+ await page.close().catch(() => {});
253
+ }
254
+ }
255
+
256
+ // Chrome's own back/forward cache test, as DevTools runs it: from the loaded page go on to `next`, then press Back.
257
+ // Resolves to Chrome's reasons for not restoring the page ([] when it did), or null when Chrome didn't say in time.
258
+ async function goBack(page, next) {
259
+ const told = new Promise(ok => {
260
+ page.on("Page.backForwardCacheNotUsed", p => ok(p.notRestoredExplanations || []));
261
+ page.on("Page.frameNavigated", p => {
262
+ if (p.type === "BackForwardCacheRestore" && !p.frame.parentId) ok([]);
263
+ });
264
+ setTimeout(ok, 10000, null).unref();
265
+ });
266
+ const nav = await page.send("Page.navigate", { url: next });
267
+ if (nav.errorText) throw new Error(nav.errorText);
268
+ await evaluate(page, LOADED).catch(() => sleep(1000));
269
+ const { currentIndex, entries } = await page.send("Page.getNavigationHistory");
270
+ await page.send("Page.navigateToHistoryEntry", { entryId: entries[currentIndex - 1].id });
271
+ return told;
272
+ }
273
+ // Plain words for the common reasons, Chrome's names for the rest; "Circumstantial" ones aren't the page's fault.
274
+ /** @type {[RegExp, string][]} */
275
+ const REASONS = [
276
+ [/^UnloadHandler.*SubFrame/, "an unload handler in an embedded frame"],
277
+ [/^UnloadHandler/, "an unload handler"],
278
+ [/NoStore.*Cookie/i, "Cache-Control: no-store on a page whose cookies changed"],
279
+ [/NoStore/i, "Cache-Control: no-store"],
280
+ [/^WebSocket/, "an open WebSocket connection"],
281
+ ];
282
+ const blockersOf = explanations => [
283
+ ...new Set(
284
+ explanations
285
+ .filter(e => e.type !== "Circumstantial")
286
+ .map(e => REASONS.find(([re]) => re.test(e.reason))?.[1] ?? e.reason),
287
+ ),
288
+ ];
289
+
290
+ const slugOf = (url, used) => {
291
+ const base =
292
+ new URL(url).pathname
293
+ .toLowerCase()
294
+ .replace(/[^a-z0-9]+/g, "-")
295
+ .replace(/^-+|-+$/g, "")
296
+ .slice(0, 60) || "home";
297
+ let slug = base;
298
+ for (let i = 2; used.has(slug); i++) slug = `${base}-${i}`;
299
+ used.add(slug);
300
+ return slug;
301
+ };
302
+
303
+ /** @typedef {(id: string, url: string, evidence: string) => void} AddFinding */
304
+ /** The phone and desktop checks alone. pageBudgetMs covers all of a page's loads, so a page that hangs (a busy loop,
305
+ * a dialog) can't stall the run. bfTested counts the pages Chrome's back/forward test actually ran on.
306
+ * @param {string} browser
307
+ * @param {string[]} urls
308
+ * @param {{ add?: AddFinding, screenshotDir?: string, pageBudgetMs?: number, session?: Session | null }} [options]
309
+ * @returns {Promise<{ checked: number, lab: any[], notes: string[], bfTested: number }>} */
310
+ export async function checkVisual(browser, urls, { pageBudgetMs = 50000, ...options } = {}) {
311
+ return (await checkPages(browser, urls, { ...options, pageBudgetMs, more: false })).visual;
312
+ }
313
+
314
+ // ---------- more from the render sample ----------
315
+ // The render checks share the phone checks' loads, and every load goes through visit() and its guard. --render-page
316
+ // renders one chosen page after its steps, which only scroll, click and wait: nothing is ever typed into a page.
317
+
318
+ export const MORE_CHECKS = {
319
+ "render-adds-text": [
320
+ "REND-01",
321
+ "medium",
322
+ n => `${n} page(s) get most of their text only after JavaScript runs`,
323
+ "The HTML the server sends holds less than half of the words the page shows; JavaScript adds the rest. Crawlers that don't run JavaScript (most AI crawlers, and Google's first pass) see only the part in the HTML.",
324
+ "Render the text on the server (server rendering or static generation) and keep client JavaScript for interactivity. If a widget adds it (reviews, related items), pick one that can output HTML on the server.",
325
+ ],
326
+ "mobile-menu-closed": [
327
+ "REND-11",
328
+ "low",
329
+ n => `${n} page(s) have a phone menu button that doesn't open the menu`,
330
+ "On a phone these pages hide their menu links behind a button, and when Chrome tapped the button the links still didn't show. Visitors on phones can't reach the rest of the site from the menu.",
331
+ "Tap the button on a real phone. It needs a click handler that shows the menu (or use a `<details>` element), the menu must not open behind another layer, and `aria-expanded` should follow the menu's state.",
332
+ ],
333
+ "mobile-ad-density": [
334
+ "REND-11",
335
+ "medium",
336
+ n => `${n} page(s) are more than 30% ads on a phone`,
337
+ "Ads take more than 30% of the page's height on a phone, measured between the header and the footer. The Coalition for Better Ads lists mobile ad density over 30% among the ad experiences people find most annoying (betterads.org/mobile-ad-density-higher-than-30), and Google's page-experience questions ask whether a page avoids “an excessive amount of ads that distract from or interfere with the main content”.",
338
+ "Show fewer ad slots on phones: drop some in-content units and sticky stacks, and keep ads under 30% of the height between the header and the footer.",
339
+ ],
340
+ };
341
+
342
+ // Local lines: twice the HTML's words and at least 200 more, since a consent banner or small widget adds less.
343
+ export const addsText = (html, rendered) => html != null && rendered >= 2 * html && rendered - html >= 200;
344
+
345
+ // Mobile ad density as the Better Ads Standard measures it: ad heights, overlaps counted once, over the height between
346
+ // header and footer. https://www.betterads.org/mobile-ad-density-higher-than-30/
347
+ export function adShare(ads, [top, bottom]) {
348
+ if (!ads.length || bottom - top < 1) return null;
349
+ let sum = 0,
350
+ end = -Infinity;
351
+ for (const [a, b] of ads
352
+ .map(([a, b]) => [Math.max(a, top), Math.min(b, bottom)])
353
+ .filter(([a, b]) => b > a)
354
+ .sort((x, y) => x[0] - y[0]))
355
+ if (b > end) {
356
+ sum += b - Math.max(a, end);
357
+ end = b;
358
+ }
359
+ return Math.round((sum / (bottom - top)) * 100) / 100;
360
+ }
361
+
362
+ // Local lines: under 3 hidden links needs no button, and a menu opens when it shows at least half of them.
363
+ export function menuVerdict({ hidden = 0, toggle, covered, revealed = 0 }) {
364
+ return hidden < 3
365
+ ? "none-needed"
366
+ : !toggle
367
+ ? "no-button"
368
+ : covered
369
+ ? "covered"
370
+ : revealed >= hidden / 2
371
+ ? "opens"
372
+ : "closed";
373
+ }
374
+
375
+ // --render-steps: "scroll; click <CSS selector>; wait <ms>", by semicolons or lines, 20 steps and 10 s a wait at most.
376
+ export function parseSteps(text = "") {
377
+ return String(text)
378
+ .split(/[;\n]/)
379
+ .map(s => s.trim())
380
+ .filter(Boolean)
381
+ .slice(0, 20)
382
+ .map(s => {
383
+ const [, verb, rest] = s.match(/^(\w+)\s*(.*)$/) || [];
384
+ if (verb === "scroll" && !rest) return { do: "scroll" };
385
+ if (verb === "click" && rest) return { do: "click", selector: rest };
386
+ if (verb === "wait" && /^\d+$/.test(rest)) return { do: "wait", ms: Math.min(Number(rest), 10000) };
387
+ throw new Error(`can't read the step “${s}”: use scroll, click <CSS selector> or wait <milliseconds>`);
388
+ });
389
+ }
390
+
391
+ // A request the guard blocked (ERR_BLOCKED_BY_CLIENT) isn't the page's error, nor is the /favicon.ico the browser asks
392
+ // for on its own (META-10 covers favicons).
393
+ export function errorOf(method, p) {
394
+ const line = s =>
395
+ String(s ?? "")
396
+ .split("\n")[0]
397
+ .trim()
398
+ .slice(0, 200);
399
+ const at = (url, n) =>
400
+ url ? ` (${url.split(/[?#]/)[0].split("/").pop() || url}${n != null ? `:${n + 1}` : ""})` : "";
401
+ if (method === "Runtime.exceptionThrown") {
402
+ const d = p.exceptionDetails || {},
403
+ x = d.exception || {};
404
+ return line(x.description || (x.value !== undefined ? `${d.text} ${x.value}` : d.text)) + at(d.url, d.lineNumber);
405
+ }
406
+ if (method === "Runtime.consoleAPICalled")
407
+ return p.type === "error"
408
+ ? line(`console.error: ${(p.args || []).map(a => a.value ?? a.description ?? "").join(" ")}`)
409
+ : null;
410
+ if (method === "Log.entryAdded") {
411
+ const e = p.entry || {};
412
+ return e.level === "error" && !/ERR_BLOCKED_BY_CLIENT/.test(e.text) && !/\/favicon\.ico$/.test(e.url || "")
413
+ ? line(e.text) + at(e.url)
414
+ : null;
415
+ }
416
+ return null;
417
+ }
418
+
419
+ // For the type checker only, which has Node's types and no DOM. The functions below run in the page as source text,
420
+ // as `(${fn})(args)`, so each is self-contained and uses the page's own globals.
421
+ const {
422
+ document,
423
+ getComputedStyle,
424
+ NodeFilter,
425
+ DOMParser,
426
+ location,
427
+ innerWidth,
428
+ innerHeight,
429
+ scrollY,
430
+ scrollBy,
431
+ scrollTo,
432
+ } = /** @type {any} */ ({});
433
+ // Words are counted as the crawler counts them, without consent and chat widgets. Hidden text leaves out accordions,
434
+ // tabs, menus and dialogs, which Google's spam policies don't count as hidden. raw is HTML to count the same way.
435
+ // https://developers.google.com/search/docs/essentials/spam-policies#hidden-text-and-links
436
+ function pageMore(withHtml, raw) {
437
+ const css = e => getComputedStyle(e),
438
+ shown = e => e.checkVisibility({ opacityProperty: true, visibilityProperty: true });
439
+ const cls = e => `${e.id} ${e.getAttribute("class") || ""}`;
440
+ const memo = f => {
441
+ const m = new Map(),
442
+ g = e => {
443
+ if (!m.has(e)) m.set(e, f(e, g));
444
+ return m.get(e);
445
+ };
446
+ return g;
447
+ };
448
+ const JUNK =
449
+ /onetrust|cookiebot|cybot|didomi|usercentrics|quantcast|qc-cmp|\bcmp\b|consent|cookie|intercom|drift|crisp|zendesk|hubspot-messages|tawk|livechat|tidio|freshchat|olark|chat/i;
450
+ const junk = memo((e, self) => !!e && e.tagName !== "BODY" && (JUNK.test(cls(e)) || self(e.parentElement)));
451
+ const SEG = new Intl.Segmenter(undefined, { granularity: "word" }),
452
+ NOSPACE = /[\p{scx=Han}\p{scx=Hira}\p{scx=Kana}\p{scx=Thai}\p{scx=Laoo}\p{scx=Khmr}\p{scx=Mymr}]/u;
453
+ const count = t =>
454
+ NOSPACE.test(t)
455
+ ? [...SEG.segment(t)].filter(s => s.isWordLike).length
456
+ : t.split(/\s+/).filter(w => /[\p{L}\p{N}]/u.test(w)).length;
457
+ const textsOf = d => {
458
+ const out = [];
459
+ if (d.body)
460
+ for (const w = d.createTreeWalker(d.body, NodeFilter.SHOW_TEXT); w.nextNode();) {
461
+ const p = w.currentNode.parentElement;
462
+ if (p && w.currentNode.data.trim() && !p.closest("script, style, noscript, template, svg, title"))
463
+ out.push([w.currentNode.data, p]);
464
+ }
465
+ return out;
466
+ };
467
+ const wordsIn = d =>
468
+ count(
469
+ textsOf(d)
470
+ .filter(([, p]) => !junk(p))
471
+ .map(([t]) => t)
472
+ .join(" "),
473
+ );
474
+ const vw = innerWidth,
475
+ vh = innerHeight,
476
+ texts = textsOf(document);
477
+ const box = e => e.getBoundingClientRect(),
478
+ across = e => {
479
+ const r = box(e);
480
+ return shown(e) && r.width > 0 && r.height > 0 && r.right > 0 && r.left < vw;
481
+ };
482
+ const first = e => across(e) && box(e).top < vh && box(e).bottom > 0;
483
+ const label = e => (e.innerText || e.value || e.getAttribute("aria-label") || "").replace(/\s+/g, " ").trim();
484
+ const h1 = [...document.querySelectorAll("h1")].find(shown);
485
+ const cta = [
486
+ ...document.querySelectorAll('button, [role="button"], input[type="submit" i], input[type="button" i], a[href]'),
487
+ ].find(e => {
488
+ if (
489
+ e.closest('nav, [role="navigation"], footer, form[role="search"]') ||
490
+ e.matches("[aria-expanded], [aria-controls], [aria-haspopup]") ||
491
+ junk(e) ||
492
+ !first(e)
493
+ )
494
+ return false;
495
+ const t = label(e);
496
+ if (t.length < 2 || t.length > 40 || !/\p{L}/u.test(t)) return false;
497
+ return (
498
+ !e.matches("a") ||
499
+ /\b(btn|button|cta)\b/i.test(cls(e)) ||
500
+ !/^(rgba\(0, 0, 0, 0\)|transparent)$/.test(css(e).backgroundColor)
501
+ );
502
+ });
503
+ const here = location.href.split("#")[0],
504
+ frag = a => {
505
+ try {
506
+ return decodeURIComponent(a.hash.slice(1));
507
+ } catch {
508
+ return a.hash.slice(1);
509
+ }
510
+ };
511
+ const broken = [
512
+ ...new Set(
513
+ [...document.querySelectorAll('a[href*="#"]')]
514
+ .filter(
515
+ a =>
516
+ a.href.split("#")[0] === here &&
517
+ a.hash.length > 1 &&
518
+ !/^#([!\/:]|top$)/i.test(a.hash) &&
519
+ !a.matches('[role="button"], [role="tab"], [aria-controls], [data-toggle], [data-bs-toggle]'),
520
+ )
521
+ .map(frag)
522
+ .filter(id => !document.getElementById(id) && !document.getElementsByName(id).length),
523
+ ),
524
+ ].slice(0, 10);
525
+ const target =
526
+ [...document.querySelectorAll("h2[id], h3[id], section[id]")].find(
527
+ e => shown(e) && box(e).top + scrollY >= 1.5 * vh,
528
+ )?.id || null;
529
+ const AD =
530
+ 'ins.adsbygoogle, [id^="div-gpt-ad"], [id^="google_ads_iframe"], iframe[src*="doubleclick.net"], iframe[src*="googlesyndication.com"], iframe[src*="amazon-adsystem.com"], iframe[src*="adnxs.com"], [data-ad-slot], [data-ad-unit-path], amp-ad, .advertisement, .ad-slot, .ad-unit, .ad-container';
531
+ const ads = [...document.querySelectorAll(AD)]
532
+ .filter(shown)
533
+ .map(box)
534
+ .filter(r => r.height >= 20 && r.width >= 50)
535
+ .map(r => [r.top + scrollY, r.bottom + scrollY]);
536
+ const outside = e => !e.closest("main, article") && shown(e);
537
+ const hdr = [...document.querySelectorAll('header, [role="banner"]')].find(outside),
538
+ ftr = [...document.querySelectorAll('footer, [role="contentinfo"]')].filter(outside).pop();
539
+ const controlled = new Set(
540
+ [...document.querySelectorAll("[aria-controls]")]
541
+ .flatMap(e => e.getAttribute("aria-controls").split(/\s+/))
542
+ .filter(Boolean),
543
+ );
544
+ const SKIP =
545
+ 'details, dialog, nav, [role="navigation"], [role="menu"], [role="menubar"], [role="tabpanel"], [role="dialog"], [role="tooltip"], [aria-modal="true"], [hidden="until-found"], select, datalist, button, [role="button"], label';
546
+ const TOGGLED =
547
+ /accordion|collaps|tab-?pane|tabpanel|tab-content|dropdown|sub-?menu|mega-?menu|modal|popup|popover|tooltip|offcanvas|drawer|slide|carousel|swiper|faq|menu/i;
548
+ const SR =
549
+ /\b(sr-only|visually-?hidden|screen-reader-text|screen-reader-only|a11y-hidden|assistive-text|element-invisible|u-hidden-visually)\b/i;
550
+ const hideOf = memo((e, self) => {
551
+ if (!e || e.tagName === "BODY") return null;
552
+ const up = self(e.parentElement);
553
+ if (up === "skip" || e.matches(SKIP) || TOGGLED.test(cls(e)) || controlled.has(e.id) || junk(e)) return "skip";
554
+ if (up) return up;
555
+ const s = css(e);
556
+ const how = e.hidden
557
+ ? "hidden attribute"
558
+ : s.display === "none"
559
+ ? "display:none"
560
+ : e.getAttribute("aria-hidden") === "true"
561
+ ? "aria-hidden"
562
+ : SR.test(cls(e)) ||
563
+ (s.position === "absolute" &&
564
+ e.offsetWidth <= 1 &&
565
+ e.offsetHeight <= 1 &&
566
+ (s.overflow === "hidden" || s.clip !== "auto"))
567
+ ? "screen-reader only"
568
+ : null;
569
+ return how ? { how, block: e } : null;
570
+ });
571
+ const blocks = new Map(),
572
+ by = {};
573
+ let hiddenWords = 0;
574
+ for (const [t, p] of texts) {
575
+ const h = hideOf(p),
576
+ n = h && h !== "skip" ? count(t) : 0;
577
+ if (!n) continue;
578
+ hiddenWords += n;
579
+ by[h.how] = (by[h.how] || 0) + n;
580
+ const b = blocks.get(h.block) || blocks.set(h.block, { how: h.how, words: 0, text: "" }).get(h.block);
581
+ b.words += n;
582
+ if (b.text.length < 80) b.text += " " + t.trim();
583
+ }
584
+ return {
585
+ words: wordsIn(document),
586
+ ...(raw != null ? { rawWords: wordsIn(new DOMParser().parseFromString(raw, "text/html")) } : {}),
587
+ h1: h1 ? first(h1) : null,
588
+ cta: cta ? label(cta) : null,
589
+ nav: [
590
+ ...new Set(
591
+ [...document.querySelectorAll('nav a[href], [role="navigation"] a[href]')].filter(across).map(a => a.href),
592
+ ),
593
+ ].slice(0, 60),
594
+ broken,
595
+ target,
596
+ ads,
597
+ region: [hdr ? box(hdr).bottom + scrollY : 0, ftr ? box(ftr).top + scrollY : document.documentElement.scrollHeight],
598
+ hidden: {
599
+ words: hiddenWords,
600
+ by,
601
+ examples: [...blocks.values()]
602
+ .sort((a, b) => b.words - a.words)
603
+ .slice(0, 3)
604
+ .map(b => ({ how: b.how, words: b.words, text: b.text.replace(/\s+/g, " ").trim().slice(0, 80) })),
605
+ },
606
+ ...(withHtml ? { html: document.documentElement.outerHTML } : {}),
607
+ };
608
+ }
609
+ // The desktop nav links (`nav`) a phone hides everywhere on the page, and the button that should show them, by its name.
610
+ function menuFind(nav) {
611
+ const shown = e => e.checkVisibility({ opacityProperty: true, visibilityProperty: true });
612
+ const reach = e => {
613
+ const r = e.getBoundingClientRect();
614
+ return shown(e) && r.width > 0 && r.height > 0 && r.right > 0 && r.left < innerWidth;
615
+ };
616
+ const links = [...document.querySelectorAll("a[href]")],
617
+ hrefs = nav.filter(h => !links.some(a => a.href === h && reach(a)));
618
+ if (hrefs.length < 3) return { hidden: hrefs.length };
619
+ const here = location.href.split("#")[0];
620
+ const name = e =>
621
+ `${e.getAttribute("aria-label") || ""} ${e.innerText || ""} ${e.title || ""} ${e.id} ${e.getAttribute("class") || ""} ${e.getAttribute("aria-controls") || ""}`;
622
+ const toggle = [
623
+ ...document.querySelectorAll(
624
+ 'button, [role="button"], a[href], label[for], summary, [aria-controls], [aria-expanded]',
625
+ ),
626
+ ].find(
627
+ e =>
628
+ reach(e) &&
629
+ e.getBoundingClientRect().top < innerHeight &&
630
+ !(e.matches("a[href]") && e.href.split("#")[0] !== here) &&
631
+ /menu|navigation|\bnav\b|hamburger|burger|navbar-toggle|nav-toggle|toggle-nav/i.test(name(e)),
632
+ );
633
+ if (!toggle) return { hidden: hrefs.length, toggle: null };
634
+ const r = toggle.getBoundingClientRect(),
635
+ x = r.left + r.width / 2,
636
+ y = r.top + r.height / 2,
637
+ top = document.elementFromPoint(x, y);
638
+ return {
639
+ hidden: hrefs.length,
640
+ hrefs,
641
+ x,
642
+ y,
643
+ covered: !(top && (top === toggle || toggle.contains(top) || top.contains(toggle))),
644
+ toggle:
645
+ (toggle.getAttribute("aria-label") || toggle.innerText || toggle.title || "")
646
+ .replace(/\s+/g, " ")
647
+ .trim()
648
+ .slice(0, 40) || "the menu button",
649
+ };
650
+ }
651
+ // After the tap, the menu links shown: as soon as half of them show (menuVerdict's line for a menu that opens), else
652
+ // what shows after `ms` (menus slide in).
653
+ function menuReached(hrefs, ms) {
654
+ const reach = e => {
655
+ const r = e.getBoundingClientRect();
656
+ return (
657
+ e.checkVisibility({ opacityProperty: true, visibilityProperty: true }) &&
658
+ r.width > 0 &&
659
+ r.height > 0 &&
660
+ r.right > 0 &&
661
+ r.left < innerWidth
662
+ );
663
+ };
664
+ const count = () => {
665
+ const links = [...document.querySelectorAll("a[href]")];
666
+ return hrefs.filter(h => links.some(a => a.href === h && reach(a))).length;
667
+ };
668
+ const end = Date.now() + ms;
669
+ return new Promise(ok => {
670
+ const tick = () => {
671
+ const n = count();
672
+ if (n >= hrefs.length / 2 || Date.now() >= end) ok(n);
673
+ else setTimeout(tick, 50);
674
+ };
675
+ tick();
676
+ });
677
+ }
678
+ // After a load at #id: still at the target, and the #id still in the address? (Google's "Read more" deep links.)
679
+ function landed(id) {
680
+ const t = document.getElementById(id);
681
+ if (!t) return null;
682
+ const r = t.getBoundingClientRect(),
683
+ inView = r.bottom > 0 && r.top < innerHeight,
684
+ kept = location.hash.slice(1) === id || location.hash.slice(1) === encodeURIComponent(id);
685
+ return inView && kept ? "ok" : inView ? "hash-removed" : kept ? "scrolled-away" : "both";
686
+ }
687
+ // Down the page a screen at a time so lazy images and infinite lists load (40 screens at most), then back to the top.
688
+ async function scrollAll() {
689
+ const wait = ms => new Promise(ok => setTimeout(ok, ms)),
690
+ root = document.scrollingElement || document.documentElement;
691
+ for (let i = 0; i < 40 && scrollY + innerHeight < root.scrollHeight - 1; i++) {
692
+ const y = scrollY;
693
+ scrollBy(0, Math.max(200, innerHeight * 0.8));
694
+ await wait(150);
695
+ if (scrollY === y) break;
696
+ }
697
+ await wait(300);
698
+ scrollTo(0, 0);
699
+ await Promise.race([Promise.all([...document.images].map(i => i.decode().catch(() => {}))), wait(3000)]);
700
+ }
701
+ // Hides cookie bars and chat widgets (fixed or sticky layers named so, or inside one) for a clean screenshot; false
702
+ // shows them again.
703
+ function hideJunk(on) {
704
+ const JUNK =
705
+ /onetrust|cookiebot|cybot|didomi|usercentrics|quantcast|qc-cmp|\bcmp\b|consent|cookie|intercom|drift|crisp|zendesk|hubspot-messages|tawk|livechat|tidio|freshchat|olark|chat/i;
706
+ document.getElementById("seo-supervisor-hide")?.remove();
707
+ if (!on) return 0;
708
+ let n = 0;
709
+ for (const e of document.querySelectorAll("body *")) {
710
+ if (!/^(fixed|sticky)$/.test(getComputedStyle(e).position)) continue;
711
+ let hit = false;
712
+ for (let a = e; a && a !== document.body && !hit; a = a.parentElement)
713
+ hit = JUNK.test(
714
+ `${a.id} ${a.getAttribute("class") || ""} ${a.tagName === "IFRAME" ? `${a.src} ${a.title}` : ""}`,
715
+ );
716
+ if (hit) {
717
+ e.setAttribute("data-seo-supervisor-hide", "");
718
+ n++;
719
+ }
720
+ }
721
+ const style = document.createElement("style");
722
+ style.id = "seo-supervisor-hide";
723
+ style.textContent = "[data-seo-supervisor-hide]{display:none!important}";
724
+ document.head.append(style);
725
+ return n;
726
+ }
727
+ function clickOn(selector) {
728
+ const e = document.querySelector(selector);
729
+ if (!e) return false;
730
+ e.scrollIntoView({ block: "center" });
731
+ e.click();
732
+ return true;
733
+ }
734
+
735
+ // Local cap, in CSS px: Chrome can't draw much past 16,384 px.
736
+ const FULL_MAX = 12000;
737
+ // Resized in the desktop load, not loaded again, so a page that lays itself out only on load keeps its 1366 px layout.
738
+ const SIZES = [
739
+ ["desktop-1920", { width: 1920, height: 1080, deviceScaleFactor: 1, mobile: false }],
740
+ ["tablet", { width: 768, height: 1024, deviceScaleFactor: 1, mobile: false }],
741
+ ];
742
+ const shoot = async (page, file, opts = { format: "png" }) =>
743
+ writeFileSync(file, Buffer.from((await page.send("Page.captureScreenshot", opts)).data, "base64"));
744
+ // The whole page after scrolling through it, at CSS-pixel size, as JPEG to keep the files small.
745
+ async function fullPage(page, file, device) {
746
+ await evaluate(page, `(${scrollAll})()`);
747
+ const { cssContentSize: c } = await page.send("Page.getLayoutMetrics");
748
+ await shoot(page, file, {
749
+ format: "jpeg",
750
+ quality: 70,
751
+ captureBeyondViewport: true,
752
+ clip: {
753
+ x: 0,
754
+ y: 0,
755
+ width: Math.ceil(c.width),
756
+ height: Math.min(Math.ceil(c.height), FULL_MAX),
757
+ scale: 1 / device.deviceScaleFactor,
758
+ },
759
+ });
760
+ }
761
+ async function cleanShot(page, file) {
762
+ if (await evaluate(page, `(${hideJunk})(true)`)) await shoot(page, file);
763
+ await evaluate(page, `(${hideJunk})(false)`);
764
+ }
765
+ // The tab's browser errors go into `errors` from before the page loads: visit() opens its tab with chrome.newPage().
766
+ const watch = (chrome, errors) => ({
767
+ ...chrome,
768
+ async newPage() {
769
+ const page = await chrome.newPage();
770
+ for (const m of ["Runtime.exceptionThrown", "Runtime.consoleAPICalled", "Log.entryAdded"])
771
+ page.on(m, p => {
772
+ const e = errorOf(m, p);
773
+ if (e) errors.add(e);
774
+ });
775
+ await page.send("Runtime.enable");
776
+ await page.send("Log.enable");
777
+ return page;
778
+ },
779
+ });
780
+ async function userAgents(chrome) {
781
+ const { userAgent: ua } = await chrome.send("Browser.getVersion");
782
+ return {
783
+ desktop: ua.replace("HeadlessChrome/", "Chrome/"),
784
+ phone: `Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${ua.match(/Chrome\/(\d+)/)?.[1] || "130"}.0.0.0 Mobile Safari/537.36`,
785
+ };
786
+ }
787
+
788
+ /** The render checks alone. rawWords is the crawler's word count per URL; clean adds screenshots without cookie bars
789
+ * and chat widgets; chosen is rendered at phone size after its steps.
790
+ * @param {string} browser
791
+ * @param {string[]} urls
792
+ * @param {{ add?: AddFinding, screenshotDir?: string, rawWords?: Map<string, number>, clean?: boolean, chosen?: Chosen | null, pageBudgetMs?: number, session?: Session | null }} [options]
793
+ * @returns {Promise<{ checked: number, pages: any[], chosen: any, notes: string[] }>} */
794
+ export async function checkMore(browser, urls, { pageBudgetMs = 60000, ...options } = {}) {
795
+ return (await checkPages(browser, urls, { ...options, pageBudgetMs, visual: false })).more;
796
+ }
797
+
798
+ /** @typedef {{ url: string, steps?: string, raw?: string | null }} Chosen */
799
+ /** @typedef {Awaited<ReturnType<typeof openSession>>} Session */
800
+ /** checkVisual and checkMore in one browser, sharing each page's desktop and phone loads, up to 10 pages one at a
801
+ * time. The default pageBudgetMs is their two budgets added. visual or more set to false skips that side.
802
+ * @param {string} browser
803
+ * @param {string[]} urls
804
+ * @param {{ add?: AddFinding, screenshotDir?: string, rawWords?: Map<string, number>, clean?: boolean, chosen?: Chosen | null, pageBudgetMs?: number, session?: Session | null, visual?: boolean, more?: boolean }} [options] */
805
+ export async function checkPages(
806
+ browser,
807
+ urls,
808
+ {
809
+ add = () => {},
810
+ screenshotDir,
811
+ rawWords = new Map(),
812
+ clean = false,
813
+ chosen = null,
814
+ pageBudgetMs = 110000,
815
+ session = null,
816
+ visual = true,
817
+ more = true,
818
+ } = {},
819
+ ) {
820
+ const V = { checked: 0, lab: [], notes: [], bfTested: 0 },
821
+ M = { checked: 0, pages: [], chosen: null, notes: [] };
822
+ const list = urls.slice(0, 10),
823
+ used = new Set(),
824
+ smallText = [],
825
+ gates = [],
826
+ noButton = [],
827
+ why = e => redact(String(e.message).split("\n")[0]).slice(0, 120);
828
+ let steps = [];
829
+ if (!more) chosen = null;
830
+ if (chosen)
831
+ try {
832
+ steps = parseSteps(chosen.steps);
833
+ } catch (e) {
834
+ M.notes.push(`--render-steps: ${e.message}. The page you chose wasn't rendered.`);
835
+ chosen = null;
836
+ }
837
+ if (!list.length && !chosen) return { visual: V, more: M };
838
+ if (screenshotDir) mkdirSync(screenshotDir, { recursive: true });
839
+ // The guard: every request is checked against the site's own addresses, and the browser's proxy covers
840
+ // other-site frames and WebSockets.
841
+ const chrome = session || (await openSession(browser, list[0] ?? chosen.url));
842
+ const checkAddress = chrome.checkAddress || (await addressCheck(list[0] ?? chosen.url));
843
+ try {
844
+ const ua = await userAgents(chrome);
845
+ for (const [i, url] of list.entries()) {
846
+ const slug = slugOf(url, used),
847
+ deadline = Date.now() + pageBudgetMs,
848
+ errors = new Set(),
849
+ tab = more ? watch(chrome, errors) : chrome,
850
+ at = { deadline, checkAddress };
851
+ const png = (p, name) => screenshotDir && shoot(p, join(screenshotDir, `${slug}-${name}.png`));
852
+ const shots = async (page, kind) => {
853
+ if (!screenshotDir) return;
854
+ const to = name => join(screenshotDir, `${slug}-${kind}-${name}`);
855
+ await fullPage(page, to("full.jpg"), kind === "desktop" ? DESKTOP : PHONE);
856
+ if (clean) await cleanShot(page, to("clean.png"));
857
+ if (kind === "desktop")
858
+ for (const [name, size] of SIZES) {
859
+ await page.send("Emulation.setDeviceMetricsOverride", size);
860
+ await evaluate(page, DRAWN);
861
+ await png(page, name);
862
+ }
863
+ };
864
+ // One load at a time, so the lab load has the CPU to itself. Popups get a second after load to appear. The plain
865
+ // screenshot and the phone checks' reads come first, before the render checks scroll, hide layers or tap.
866
+ let d, m;
867
+ try {
868
+ d = await visit(
869
+ tab,
870
+ url,
871
+ { device: DESKTOP, userAgent: ua.desktop, settleMs: more ? 500 : 200, ...at },
872
+ async p => {
873
+ const x = {};
874
+ if (visual) {
875
+ await png(p, "desktop");
876
+ x.v = await evaluate(p, MEASURE);
877
+ }
878
+ if (more) {
879
+ x.m = await evaluate(p, `(${pageMore})(true)`);
880
+ x.m.gate = gateOf(x.m.html);
881
+ delete x.m.html;
882
+ if (!x.m.gate) await shots(p, "desktop");
883
+ }
884
+ return x;
885
+ },
886
+ );
887
+ } catch (e) {
888
+ if (visual) V.notes.push(`Couldn't load ${url} for the phone checks (${why(e)}).`);
889
+ if (more) M.notes.push(`Couldn't load ${url} for the render checks (${why(e)}).`);
890
+ continue;
891
+ }
892
+ const gate = more && d.m.gate; // a login screen or paywall isn't measured for the render checks
893
+ if (gate) {
894
+ gates.push(`${new URL(url).pathname} (${gate})`);
895
+ M.pages.push({ url, gate, errors: [...errors].slice(0, 10) });
896
+ if (!visual) continue;
897
+ }
898
+ try {
899
+ m = await visit(tab, url, { device: PHONE, userAgent: ua.phone, settleMs: 1000, ...at }, async p => {
900
+ const x = {};
901
+ if (visual) {
902
+ await png(p, "mobile");
903
+ x.v = { ...(await evaluate(p, MEASURE)), taps: await evaluate(p, TAPS), fields: await evaluate(p, FIELDS) };
904
+ }
905
+ if (more && !gate) {
906
+ x.m = await evaluate(p, `(${pageMore})(false)`);
907
+ await shots(p, "mobile");
908
+ await evaluate(p, `(${hideJunk})(true)`); // a cookie bar or chat bubble mustn't take the tap
909
+ x.m.menu = await evaluate(p, `(${menuFind})(${JSON.stringify(d.m.nav)})`);
910
+ if (x.m.menu.toggle && !x.m.menu.covered) {
911
+ for (const type of ["mousePressed", "mouseReleased"])
912
+ await p.send("Input.dispatchMouseEvent", {
913
+ type,
914
+ x: x.m.menu.x,
915
+ y: x.m.menu.y,
916
+ button: "left",
917
+ clickCount: 1,
918
+ });
919
+ x.m.menu.revealed = await evaluate(p, `(${menuReached})(${JSON.stringify(x.m.menu.hrefs)}, 700)`);
920
+ }
921
+ }
922
+ return x;
923
+ });
924
+ } catch (e) {
925
+ if (visual) V.notes.push(`Couldn't load ${url} for the phone checks (${why(e)}).`);
926
+ if (more && !gate) M.notes.push(`Couldn't load ${url} for the render checks (${why(e)}).`);
927
+ continue;
928
+ }
929
+ if (visual) {
930
+ const dv = d.v,
931
+ mv = m.v;
932
+ V.checked++;
933
+ // Word counts below 30 are too small to compare. A real diff of the text would also catch swapped content.
934
+ const fewer = dv.words >= 30 && mv.words < 0.7 * dv.words,
935
+ lostH1 = dv.h1[0] && !mv.h1.some(h => sameHeading(dv.h1[0], h));
936
+ if (fewer || lostH1)
937
+ add(
938
+ "mobile-content-missing",
939
+ url,
940
+ [
941
+ fewer && `${mv.words} words on a phone vs ${dv.words} on desktop`,
942
+ lostH1 && `the H1 “${dv.h1[0]}” isn't shown on a phone`,
943
+ ]
944
+ .filter(Boolean)
945
+ .join("; "),
946
+ );
947
+ // Without a mobile viewport the page is laid out 980 px wide and zoomed out; the crawler's doc-basics reports that.
948
+ // Overflow that html or body clips can't be scrolled to.
949
+ if (mv.viewport && !mv.clipped && mv.scrollWidth > PHONE.width + 2)
950
+ add("mobile-overflow", url, `${mv.scrollWidth} px wide on a ${PHONE.width} px screen`);
951
+ if (mv.viewport && mv.fontSize < 12) add("mobile-small-text", url, `main text ${mv.fontSize} px`);
952
+ else if (mv.viewport && mv.fontSize < 16)
953
+ smallText.push(`${new URL(url).pathname} (${Math.round(mv.fontSize * 10) / 10} px)`);
954
+ if (mv.viewport && mv.taps.count)
955
+ add(
956
+ "tap-targets-small",
957
+ url,
958
+ `${mv.taps.count} ${mv.taps.count === 1 ? "link or button" : "links or buttons"} under 24×24 px with too little space around them, for example ${mv.taps.examples.join(", ")}`,
959
+ );
960
+ if (mv.viewport && mv.fields.count)
961
+ add(
962
+ "input-zoom",
963
+ url,
964
+ `${mv.fields.count} form field${mv.fields.count === 1 ? "" : "s"} with text under 16 px, for example ${mv.fields.examples.join(", ")}`,
965
+ );
966
+ if (mv.popup.cover)
967
+ add(
968
+ "mobile-interstitial",
969
+ url,
970
+ `${mv.popup.by} covers ${Math.round(mv.popup.cover * 100)}% of the screen on arrival`,
971
+ );
972
+ // Consent and other legally required notices are exempt from Google's intrusive-interstitial guidance.
973
+ // https://developers.google.com/search/docs/appearance/avoid-intrusive-interstitials
974
+ if (mv.consent.cover)
975
+ V.notes.push(
976
+ `On a phone, ${url} opens with a consent popup (${mv.consent.by}) over ${Math.round(mv.consent.cover * 100)}% of the screen. Legally required notices are exempt from Google's intrusive-interstitial guidance, so it isn't a finding; a bottom banner keeps the page readable.`,
977
+ );
978
+ }
979
+ if (more && !gate) {
980
+ const dm = d.m,
981
+ mm = m.m;
982
+ M.checked++;
983
+ const rec = {
984
+ url,
985
+ h1: { desktop: dm.h1, phone: mm.h1 },
986
+ cta: { desktop: dm.cta, phone: mm.cta },
987
+ words: { html: rawWords.get(url) ?? null, rendered: dm.words },
988
+ menu: menuVerdict(mm.menu),
989
+ ads: adShare(mm.ads, mm.region),
990
+ };
991
+ if (dm.hidden.words) rec.hidden = dm.hidden;
992
+ if (dm.broken.length || dm.target) rec.jumpLinks = { broken: dm.broken, deepLink: null, target: dm.target };
993
+ if (dm.target)
994
+ try {
995
+ rec.jumpLinks.deepLink = await visit(
996
+ tab,
997
+ `${url.split("#")[0]}#${encodeURIComponent(dm.target)}`,
998
+ { device: DESKTOP, userAgent: ua.desktop, settleMs: 1500, ...at },
999
+ p => evaluate(p, `(${landed})(${JSON.stringify(dm.target)})`),
1000
+ );
1001
+ } catch (e) {
1002
+ M.notes.push(`Couldn't test a jump to ${quote(`#${dm.target}`)} on ${url} (${why(e)}).`);
1003
+ } // the jump link is page text
1004
+ rec.errors = [...errors].slice(0, 10);
1005
+ M.pages.push(rec);
1006
+ if (addsText(rec.words.html, rec.words.rendered))
1007
+ add(
1008
+ "render-adds-text",
1009
+ url,
1010
+ `${rec.words.html} words in the HTML, ${rec.words.rendered} after JavaScript runs`,
1011
+ );
1012
+ if (rec.menu === "closed")
1013
+ add(
1014
+ "mobile-menu-closed",
1015
+ url,
1016
+ `the menu button “${mm.menu.toggle}” showed ${mm.menu.revealed} of the ${mm.menu.hidden} menu links desktop shows`,
1017
+ );
1018
+ if (rec.menu === "no-button") noButton.push(new URL(url).pathname);
1019
+ if (rec.ads > 0.3)
1020
+ add(
1021
+ "mobile-ad-density",
1022
+ url,
1023
+ `ads take ${Math.round(rec.ads * 100)}% of the page's height on a phone, between the header and the footer`,
1024
+ );
1025
+ }
1026
+ if (!visual) continue;
1027
+ try {
1028
+ const v = await visit(chrome, url, { device: PHONE, userAgent: ua.phone, lab: true, settleMs: 500, ...at }, p =>
1029
+ evaluate(p, `({ ...__seoLab, cls: (${clsOf})(__seoLab.shifts), shifts: null })`),
1030
+ );
1031
+ V.lab.push({
1032
+ url,
1033
+ lcp: v.lcp ? Math.round(v.lcp) : null,
1034
+ cls: Math.round(v.cls * 1000) / 1000,
1035
+ tbt: Math.round(v.tbt),
1036
+ });
1037
+ } catch (e) {
1038
+ V.notes.push(`Couldn't measure lab speed for ${url} (${why(e)}).`);
1039
+ }
1040
+ if (list.length > 1 && i < BF_PAGES)
1041
+ try {
1042
+ // Back needs a page to come back from: the next one in the sample
1043
+ const reasons = await visit(
1044
+ chrome,
1045
+ url,
1046
+ { device: DESKTOP, userAgent: ua.desktop, settleMs: 200, ...at },
1047
+ p => goBack(p, list[(i + 1) % list.length]),
1048
+ );
1049
+ if (reasons) {
1050
+ V.bfTested++;
1051
+ const blockers = blockersOf(reasons);
1052
+ if (blockers.length) add("bfcache-blocked", url, `Chrome names: ${blockers.join("; ")}`);
1053
+ } else V.notes.push(`Chrome didn't report the back/forward cache test on ${url} within 10 s.`);
1054
+ } catch (e) {
1055
+ V.notes.push(`Couldn't run the back/forward cache test on ${url} (${why(e)}).`);
1056
+ }
1057
+ }
1058
+ const { notes } = M;
1059
+ if (chosen) {
1060
+ const errors = new Set();
1061
+ try {
1062
+ const x = await visit(
1063
+ watch(chrome, errors),
1064
+ chosen.url,
1065
+ { device: PHONE, userAgent: ua.phone, settleMs: 1000, deadline: Date.now() + 120000, checkAddress },
1066
+ async p => {
1067
+ for (const s of steps) {
1068
+ if (s.do === "scroll") await evaluate(p, `(${scrollAll})()`);
1069
+ else if (s.do === "wait") await sleep(s.ms);
1070
+ else if (await evaluate(p, `(${clickOn})(${JSON.stringify(s.selector)})`)) await sleep(500);
1071
+ else
1072
+ notes.push(
1073
+ `--render-steps: nothing on the page you chose matched “${s.selector}”, so that click was skipped.`,
1074
+ );
1075
+ }
1076
+ const r = await evaluate(p, `(${pageMore})(true, ${JSON.stringify(chosen.raw ?? null)})`);
1077
+ if (screenshotDir) {
1078
+ await shoot(p, join(screenshotDir, "chosen-mobile.png"));
1079
+ await fullPage(p, join(screenshotDir, "chosen-mobile-full.jpg"), PHONE);
1080
+ }
1081
+ return r;
1082
+ },
1083
+ );
1084
+ M.chosen = {
1085
+ url: chosen.url,
1086
+ steps: steps.length ? chosen.steps.trim() : null,
1087
+ words: { html: x.rawWords ?? null, rendered: x.words },
1088
+ changes: chosen.raw ? compareRendered(chosen.raw, x.html) : [],
1089
+ gate: gateOf(x.html),
1090
+ errors: [...errors].slice(0, 10),
1091
+ };
1092
+ notes.push(
1093
+ `Rendered the page you chose, ${chosen.url}, at phone size${steps.length ? " after your steps" : ""}${screenshotDir ? ", with screenshots (chosen-mobile.png and chosen-mobile-full.jpg)" : ""}. Information only.`,
1094
+ );
1095
+ } catch (e) {
1096
+ notes.push(`Couldn't render the page you chose, ${chosen.url} (${why(e)}).`);
1097
+ }
1098
+ }
1099
+ } finally {
1100
+ if (!session) await chrome.close();
1101
+ }
1102
+ const { checked, bfTested } = V;
1103
+ if (checked)
1104
+ V.notes.push(
1105
+ `Loaded ${checked} sample page(s) at desktop (1366×768) and phone (390×844) size${screenshotDir ? ", with screenshots" : ""}${bfTested ? `, and ran Chrome's back/forward cache test on ${bfTested} of them` : ""}. Lab speed comes from one phone load with 4× CPU slowdown on slow 4G: indicative only, it won't match Lighthouse.`,
1106
+ );
1107
+ if (smallText.length)
1108
+ V.notes.push(
1109
+ `On a phone, the main text is under 16 px on ${smallText.length} page${smallText.length === 1 ? "" : "s"}: ${smallText.join(", ")}. Information only: 16 px is the browsers' default text size, and main text under 12 px is a finding (mobile-small-text).`,
1110
+ );
1111
+ if (checked && containerArgs().length)
1112
+ V.notes.push(
1113
+ "Chrome ran without its security sandbox (--no-sandbox), because this runs as root on Linux or inside a container, where the sandbox can't start. The sample pages' scripts ran with fewer protections than in a normal browser; to keep the sandbox, run the audit as an ordinary user outside a container.",
1114
+ );
1115
+ if (M.checked)
1116
+ M.notes.push(
1117
+ `${visual ? "Read the same" : "Loaded"} ${M.checked} sample page(s) ${visual ? "" : "again "}at desktop and phone size for browser errors, the first screen, the phone menu, ads, hidden text and jump links${screenshotDir ? `, with whole-page, 1920×1080 and 768×1024 (tablet) screenshots${clean ? " and copies without cookie bars and chat widgets" : ""}` : ""}.`,
1118
+ );
1119
+ if (M.checked && screenshotDir)
1120
+ M.notes.push(
1121
+ `The screenshots are in ${screenshotDir}. Look through them for text that overlaps or is cut off, images that are stretched, squashed or blurry, and layouts that break at one of the sizes, and report what you find with the file name.`,
1122
+ );
1123
+ if (gates.length)
1124
+ M.notes.push(
1125
+ `Chrome got a login screen or a paywall instead of the page on ${gates.join(", ")}. Reported only: nothing was typed in, and these weren't measured as the page.`,
1126
+ );
1127
+ if (noButton.length)
1128
+ M.notes.push(
1129
+ `On a phone, ${noButton.join(", ")} ${noButton.length === 1 ? "hides" : "hide"} the menu links desktop shows, and no menu button was found to open them. Check the menu by hand on a phone.`,
1130
+ );
1131
+ return { visual: V, more: M };
1132
+ }