astro-seo-check 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+
5
+ - First release: 24 rules covering titles, descriptions, canonicals, broken internal links, headings, alt text, JSON-LD, lang, Open Graph, thin content, sitemap and robots. Astro integration with failOn, JSON report and rule overrides; CLI for any static folder. Tested with Astro 7.
6
+ - Re-check (4 Dec 2026), checked against Google Search Central documentation: 24 rules became 46.
7
+ - Canonical: several different canonicals, relative URLs, targets missing from the build, targets that are `noindex`, and non-canonical pages listed in the sitemap.
8
+ - hreflang: invalid codes, one-way links, broken targets and missing self-reference. `lang` values are validated.
9
+ - robots.txt is now parsed per RFC 9309 (groups, longest match, `*` and `$`) instead of one pattern: blocked pages, blocked CSS/JS, `noindex` pages hidden behind a block, missing `Sitemap:` line.
10
+ - Sitemaps: URLs not in the build, redirect pages; any `sitemap*.xml` is recognised.
11
+ - JSON-LD: Google's Product requirements, missing `@context`, `@graph` support, and types that no longer get rich results (FAQ since 7 May 2026, How-to, Claim Review, Special Announcement, practice problems, Dataset).
12
+ - Also: `noindex` from `<meta name="googlebot">`, missing viewport, links with no text, orphan pages.
13
+ - 3,000-page sites check in under a second.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ahmad Zia (https://www.ahmadzia.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,155 @@
1
- # Temporary Holding Version
1
+ # astro-seo-check
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <!-- badges -->
4
+ [![npm](https://img.shields.io/npm/v/astro-seo-check?color=3a7a4e&label=npm)](https://www.npmjs.com/package/astro-seo-check) [![CI](https://github.com/MuhammadAhmadZia/astro-seo-check/actions/workflows/ci.yml/badge.svg)](https://github.com/MuhammadAhmadZia/astro-seo-check/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-0d2018)](LICENSE) [![Agent skill](https://img.shields.io/badge/agent%20skill-static--seo--check-c5dfc9)](skills/static-seo-check/SKILL.md) [![Guide](https://img.shields.io/badge/guide-ahmadzia.com-3a7a4e)](https://www.ahmadzia.com/tools/astro-seo-check)
5
+
6
+ **Catch SEO mistakes before they go live.** An Astro integration that checks every built page at the end of `astro build`, and fails the build if something is badly broken. Also works as a CLI on any static site.
7
+
8
+ ```bash
9
+ npx astro add astro-seo-check
10
+ ```
11
+
12
+ ```js
13
+ // astro.config.mjs
14
+ import { defineConfig } from 'astro/config';
15
+ import seoCheck from 'astro-seo-check';
16
+
17
+ export default defineConfig({
18
+ site: 'https://www.your-site.com',
19
+ integrations: [seoCheck()],
20
+ });
21
+ ```
22
+
23
+ ```
24
+ [astro-seo-check] SEO check: 48 pages, 1 error(s), 3 warning(s), 12 info
25
+ ERROR /blog/old-post/ 1 broken internal link(s): /services/audit/ [broken-link]
26
+ WARNING /tools/ Title "Free tools" is used on 2 pages: /tools/, /tools/archive/ [title-duplicate]
27
+ WARNING /research/gbdt/ 2 image(s) without alt: /img/fig1.png, /img/fig2.png [img-alt]
28
+ WARNING (site) No sitemap in the build (add @astrojs/sitemap) [sitemap-missing]
29
+ (12 info note(s) hidden. Use verbose: true or --verbose to see them.)
30
+ ```
31
+
32
+ (Illustrative output.)
33
+
34
+ Zero dependencies. Checks run on the final HTML, so they catch problems from layouts, content collections and components alike.
35
+
36
+ ## What it checks
37
+
38
+ | Rule | Default level | Checks |
39
+ |---|---|---|
40
+ | `title-missing` | error | Page has no `<title>` |
41
+ | `title-length` | warning | Title over 60 or under 10 characters |
42
+ | `title-duplicate` | warning | Same title on several indexable pages |
43
+ | `description-missing` | warning | No meta description |
44
+ | `description-length` | info | Description over 160 or under 50 characters |
45
+ | `description-duplicate` | warning | Same description on several pages |
46
+ | `canonical-missing` | warning | No canonical link |
47
+ | `canonical-host` | error | Canonical uses another host (for example non-www when your site is www) |
48
+ | `canonical-invalid` | error | Canonical is not a valid URL |
49
+ | `canonical-other` | info | Canonical points to a different page |
50
+ | `canonical-multiple` | error | Several different canonical links on one page (Google may ignore all of them) |
51
+ | `canonical-relative` | info | Canonical is a relative URL (Google recommends absolute) |
52
+ | `canonical-broken` | warning | Canonical points to a page that is not in the build |
53
+ | `canonical-to-noindex` | warning | Canonical points to a `noindex` page |
54
+ | `hreflang-invalid` | error | `hreflang` value is not a valid language or language-region code |
55
+ | `hreflang-no-return` | warning | Language version does not link back (Google ignores one-way hreflang) |
56
+ | `hreflang-broken` | warning | `hreflang` points to a page that is not in the build |
57
+ | `hreflang-self-missing` | info | `hreflang` set does not include the page itself |
58
+ | `broken-link` | error | Internal link to a page or file that is not in the build |
59
+ | `trailing-slash` | info | Internal links mix `/page` and `/page/` |
60
+ | `h1-missing` | warning | No H1 |
61
+ | `h1-multiple` | info | More than one H1 |
62
+ | `img-alt` | warning | Images without an `alt` attribute (`alt=""` is fine for decorative images) |
63
+ | `jsonld-invalid` | error | JSON-LD that does not parse |
64
+ | `lang-missing` | warning | `<html>` without `lang` |
65
+ | `lang-invalid` | warning | `lang` is not a valid language code (for example `english` instead of `en`) |
66
+ | `viewport-missing` | warning | No viewport meta tag (Google indexes the mobile version) |
67
+ | `link-text-empty` | info | Links with no text, `aria-label` or image `alt` |
68
+ | `orphan-page` | info | Indexable page that no other page links to |
69
+ | `jsonld-context` | warning | JSON-LD without `@context` |
70
+ | `jsonld-product` | warning | `Product` missing what Google requires: `name`; one of `offers`, `review` or `aggregateRating`; `offers.price` and `priceCurrency`; `image` for merchant listings |
71
+ | `jsonld-retired` | info | Types that no longer produce Google rich results: `FAQPage` (since 7 May 2026), `HowTo`, `ClaimReview`, `SpecialAnnouncement`, `Quiz` (practice problems), `Dataset` (Dataset Search only) |
72
+ | `og-image-missing` | info | No `og:image` |
73
+ | `thin-content` | info | Fewer than 100 words of main content |
74
+ | `noindex-in-sitemap` | error | A `noindex` page is listed in the sitemap |
75
+ | `sitemap-non-canonical` | warning | Sitemap lists a page whose canonical points elsewhere (sitemaps should list canonical URLs only) |
76
+ | `sitemap-broken` | warning | Sitemap lists URLs that are not in the build |
77
+ | `sitemap-redirect` | warning | Sitemap lists a redirect page |
78
+ | `sitemap-missing` | warning | No sitemap file in the build |
79
+ | `robots-blocks-all` | error | robots.txt blocks Googlebot from the home page |
80
+ | `robots-blocks-pages` | warning | robots.txt blocks indexable pages |
81
+ | `robots-blocks-assets` | warning | robots.txt blocks CSS or JS files Google needs to render the page |
82
+ | `noindex-blocked` | warning | A `noindex` page is also blocked in robots.txt, so Google never sees the `noindex` |
83
+ | `robots-no-sitemap` | info | robots.txt has no `Sitemap:` line |
84
+ | `robots-missing` | info | No robots.txt in the build |
85
+ | `404-missing` | info | No custom 404 page |
86
+
87
+ ## Options
88
+
89
+ ```js
90
+ seoCheck({
91
+ failOn: 'error', // 'error' (default), 'warning', or false to never fail the build
92
+ report: 'seo-report.json', // write the full results to a JSON file in the project root
93
+ verbose: false, // also print info notes
94
+ ignore: ['/drafts/', /^\/tags\//], // pages to skip (404 and 500 are skipped already)
95
+ ignoreLinks: ['/api/', '/admin'], // link targets served at runtime, not in the static build
96
+ titleMax: 60, descMax: 160, minWords: 100,
97
+ rules: { 'og-image-missing': 'off', 'canonical-missing': 'error' }, // change any rule level
98
+ });
99
+ ```
100
+
101
+ If your site uses server-rendered routes, add them to `ignoreLinks` so links to them are not reported as broken.
102
+
103
+ robots.txt is read the way Google reads it (RFC 9309): the most specific `User-agent` group applies, the longest matching rule wins, `Allow` wins a tie, and `*` and `$` work. `noindex` is read from both `<meta name="robots">` and `<meta name="googlebot">`.
104
+
105
+ Checked against Google Search Central documentation in December 2026 (canonicalisation, hreflang, robots.txt, sitemaps, Product structured data, and the 2025 and 2026 rich result retirements).
106
+
107
+ ## Not using Astro?
108
+
109
+ Point the CLI at any build folder (Hugo, Eleventy, Next.js static export, Vite SSG, Jekyll):
110
+
111
+ ```bash
112
+ npx astro-seo-check ./dist --site https://www.your-site.com
113
+ npx astro-seo-check ./public --fail-on warning --json seo-report.json --verbose
114
+ ```
115
+
116
+ Exit code is 1 when issues reach the `--fail-on` level, so it works in CI.
117
+
118
+ ## Sustainable Development Goals
119
+
120
+ This tool supports **SDG target 8.3** (growth of micro, small and medium-sized enterprises). Technical SEO problems such as broken canonicals, one-way hreflang or a robots.txt that blocks CSS quietly cost small sites their search traffic, and an agency audit is out of reach for most. A free check that runs on every build gives them the same safety net. It also supports **target 9.c** (access to information and communications technology) indirectly: correct `lang` and hreflang tags help search engines show Urdu, Arabic and other-language pages to the people who read those languages.
121
+
122
+ ## Related
123
+
124
+ - [astro-ai-ready](https://www.npmjs.com/package/astro-ai-ready) writes `llms.txt` for AI agents from the same build.
125
+ - [ai-ready-audit](https://www.npmjs.com/package/ai-ready-audit) checks the live site for AI crawler access and schema.
126
+ - The **static-seo-check** agent skill lets Claude, ChatGPT, Codex or Cursor run these checks and fix the issues in your source:
127
+
128
+ ```bash
129
+ npx skills add MuhammadAhmadZia/astro-seo-check --skill static-seo-check
130
+ ```
131
+
132
+ ## About
133
+
134
+ Built by [Ahmad Zia](https://www.ahmadzia.com), who builds fast, search-friendly sites for e-commerce brands with Astro. MIT licensed.
135
+
136
+ <!-- ahmadzia-links -->
137
+ ## Guide, help and author
138
+
139
+ - **Full guide with examples and FAQs:** [www.ahmadzia.com/tools/astro-seo-check](https://www.ahmadzia.com/tools/astro-seo-check)
140
+ - **Background reading:** [AI visibility for online stores: what gets you cited](https://www.ahmadzia.com/blog/ai-visibility-llms-txt-ai-crawlers)
141
+ - **All 30 free tools and agent skills:** [ahmadzia.com/tools](https://www.ahmadzia.com/tools) · [ahmadzia.com/skills](https://www.ahmadzia.com/skills)
142
+ - **Want it set up, fixed or tuned for your store?** [Book a free call](https://www.ahmadzia.com/contact)
143
+
144
+ Built by **[Ahmad Zia](https://www.ahmadzia.com)** (Muhammad Ahmad Zia), an AI consultant for ecommerce since 2020 and green AI researcher at the University of Lahore. [Research](https://www.ahmadzia.com/research) · [Google Scholar](https://scholar.google.com/citations?user=sqjdX2EAAAAJ&hl=en) · [ORCID](https://orcid.org/0000-0002-3208-6246) · [LinkedIn](https://www.linkedin.com/in/muhammad-ahmadzia/) · [GitHub](https://github.com/MuhammadAhmadZia)
145
+ <!-- /ahmadzia-links -->
146
+
147
+ ## More AI search and agent readiness tools
148
+
149
+ - [ai-ready-audit](https://github.com/MuhammadAhmadZia/ai-ready-audit): Check whether ChatGPT, Claude, Perplexity and Google AI can find and cite your site
150
+ - [ai-traffic-insights](https://github.com/MuhammadAhmadZia/ai-traffic-insights): See what ChatGPT, Claude and Perplexity actually do on your site, from your own logs
151
+ - [agentic-commerce-readiness](https://github.com/MuhammadAhmadZia/agentic-commerce-readiness): Get your store ready for ChatGPT shopping and AI shopping agents
152
+ - [webmcp-store-tools](https://github.com/MuhammadAhmadZia/webmcp-store-tools): WebMCP tools for WooCommerce and headless stores, plus a checker for any WebMCP site
153
+ - [astro-ai-ready](https://github.com/MuhammadAhmadZia/astro-ai-ready): Generate llms.txt and llms-full.txt for any Astro site on every build
154
+
155
+ All 30 tools and agent skills: [github.com/MuhammadAhmadZia](https://github.com/MuhammadAhmadZia) · [ahmadzia.com/tools](https://www.ahmadzia.com/tools)
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { checkSite, format } from '../src/index.js';
4
+
5
+ const args = process.argv.slice(2);
6
+ if (!args.length || args.includes('-h') || args.includes('--help')) {
7
+ console.log(`astro-seo-check - SEO checks for a built static site (Astro, Hugo, Eleventy, Next export...)
8
+
9
+ Usage:
10
+ npx astro-seo-check <build-folder> [--site https://example.com] [--fail-on error|warning|none] [--json report.json] [--verbose]`);
11
+ process.exit(args.length ? 0 : 1);
12
+ }
13
+ const val = (f) => { const i = args.indexOf(f); return i >= 0 ? args[i + 1] : undefined; };
14
+ const result = await checkSite({ outDir: args[0], site: val('--site') });
15
+ console.log(format(result, { verbose: args.includes('--verbose') }));
16
+ if (val('--json')) await writeFile(val('--json'), JSON.stringify(result, null, 2));
17
+ const failOn = val('--fail-on') || 'error';
18
+ const errors = result.issues.some((i) => i.severity === 'error');
19
+ const warnings = result.issues.some((i) => i.severity === 'warning');
20
+ process.exitCode = (failOn === 'error' && errors) || (failOn === 'warning' && (errors || warnings)) ? 1 : 0;
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "astro-seo-check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Build-time SEO checks for Astro and any static site: missing or duplicate titles and descriptions, broken internal links, canonical mistakes, H1 problems, images without alt text, invalid JSON-LD, noindex pages in the sitemap, and more. Fails the build when you want it to.",
5
+ "type": "module",
6
+ "bin": {
7
+ "astro-seo-check": "bin/astro-seo-check.js"
8
+ },
9
+ "main": "src/index.js",
10
+ "exports": {
11
+ ".": "./src/index.js"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "src",
16
+ "README.md",
17
+ "LICENSE",
18
+ "CHANGELOG.md"
19
+ ],
20
+ "scripts": {
21
+ "test": "node --test test/*.test.js"
22
+ },
23
+ "engines": {
24
+ "node": ">=18.17"
25
+ },
26
+ "peerDependencies": {
27
+ "astro": ">=4.0.0"
28
+ },
29
+ "peerDependenciesMeta": {
30
+ "astro": {
31
+ "optional": true
32
+ }
33
+ },
34
+ "keywords": [
35
+ "astro",
36
+ "astro-integration",
37
+ "withastro",
38
+ "seo",
39
+ "seo-audit",
40
+ "broken-links",
41
+ "static-site",
42
+ "lint",
43
+ "meta-tags",
44
+ "canonical",
45
+ "json-ld",
46
+ "ci"
47
+ ],
48
+ "author": {
49
+ "name": "Ahmad Zia (Muhammad Ahmad Zia)",
50
+ "url": "https://www.ahmadzia.com"
51
+ },
52
+ "license": "MIT",
53
+ "homepage": "https://www.ahmadzia.com/tools/astro-seo-check",
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "git+https://github.com/MuhammadAhmadZia/astro-seo-check.git"
57
+ },
58
+ "bugs": {
59
+ "url": "https://github.com/MuhammadAhmadZia/astro-seo-check/issues"
60
+ }
61
+ }
package/src/check.js ADDED
@@ -0,0 +1,378 @@
1
+ import { readdir, readFile, access } from 'node:fs/promises';
2
+ import { join, relative, sep } from 'node:path';
3
+
4
+ const decode = (s) => s.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;|&apos;/g, "'").replace(/&nbsp;/g, ' ');
5
+ const attr = (tag, name) => {
6
+ const m = new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag);
7
+ return m ? decode(m[1] ?? m[2] ?? m[3] ?? '') : null;
8
+ };
9
+
10
+ async function exists(p) {
11
+ try { await access(p); return true; } catch { return false; }
12
+ }
13
+
14
+ async function* walk(dir) {
15
+ for (const e of await readdir(dir, { withFileTypes: true })) {
16
+ const full = join(dir, e.name);
17
+ if (e.isDirectory()) yield* walk(full);
18
+ else if (e.isFile()) yield full;
19
+ }
20
+ }
21
+
22
+ export function routeOf(outDir, file) {
23
+ const rel = '/' + relative(outDir, file).split(sep).join('/');
24
+ return rel.replace(/index\.html$/, '').replace(/\.html$/, '') || '/';
25
+ }
26
+
27
+ /** Extract SEO-relevant facts from one HTML document. */
28
+ export function parsePage(html) {
29
+ const title = (/<title[^>]*>([\s\S]*?)<\/title>/i.exec(html) || [])[1];
30
+ const meta = {};
31
+ for (const tag of html.match(/<meta\b[^>]*>/gi) || []) {
32
+ const k = (attr(tag, 'name') || attr(tag, 'property') || '').toLowerCase();
33
+ if (k && !(k in meta)) meta[k] = attr(tag, 'content') ?? '';
34
+ }
35
+ const links = (html.match(/<link\b[^>]*>/gi) || []).map((t) => ({ rel: (attr(t, 'rel') || '').toLowerCase(), href: attr(t, 'href') }));
36
+ const canonicals = links.filter((l) => l.rel.split(/\s+/).includes('canonical')).map((l) => l.href);
37
+ const canonical = canonicals[0] ?? null;
38
+ const hreflang = (html.match(/<link\b[^>]*>/gi) || [])
39
+ .filter((t) => (attr(t, 'rel') || '').toLowerCase().split(/\s+/).includes('alternate') && attr(t, 'hreflang'))
40
+ .map((t) => ({ lang: attr(t, 'hreflang'), href: attr(t, 'href') }));
41
+ const htmlTag = (/<html\b[^>]*>/i.exec(html) || [''])[0];
42
+ const h1 = (html.match(/<h1\b/gi) || []).length;
43
+ const imgs = html.match(/<img\b[^>]*>/gi) || [];
44
+ const imgsNoAlt = imgs.filter((t) => attr(t, 'alt') === null && !/\baria-hidden\s*=\s*["']true/i.test(t) && !/\brole\s*=\s*["']presentation/i.test(t)).map((t) => attr(t, 'src') || '(no src)');
45
+ const anchors = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')[^>]*>/gi)].map((m) => decode(m[1] ?? m[2] ?? ''));
46
+ // Links a crawler sees no text for: no words, no aria-label/title, no image alt.
47
+ let emptyLinks = 0;
48
+ for (const m of html.matchAll(/<a\b([^>]*)>([\s\S]{0,2000}?)<\/a>/gi)) {
49
+ if (!/\bhref\s*=/.test(m[1]) || attr(m[1], 'aria-label') || attr(m[1], 'title')) continue;
50
+ const inner = m[2];
51
+ const text = decode(inner.replace(/<[^>]+>/g, ' ')).trim();
52
+ const alts = [...inner.matchAll(/<img\b[^>]*>/gi)].map((t) => attr(t[0], 'alt')).filter((a) => a && a.trim());
53
+ const svgTitle = /<title\b[^>]*>\s*\S/i.test(inner) || /aria-label\s*=\s*["'][^"']+/i.test(inner);
54
+ if (!text && !alts.length && !svgTitle) emptyLinks++;
55
+ }
56
+ const jsonLdErrors = [];
57
+ const jsonLd = [];
58
+ let i = 0;
59
+ for (const m of html.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi)) {
60
+ i++;
61
+ try { jsonLd.push(JSON.parse(m[1])); } catch (e) { jsonLdErrors.push(`block ${i}: ${e.message}`); }
62
+ }
63
+ const main = (/<main\b[^>]*>([\s\S]*?)<\/main>/i.exec(html) || /<body\b[^>]*>([\s\S]*?)<\/body>/i.exec(html) || [null, html])[1];
64
+ const words = decode(main.replace(/<(script|style|svg|noscript|nav|footer|header)\b[\s\S]*?<\/\1>/gi, ' ').replace(/<[^>]+>/g, ' ')).split(/\s+/).filter(Boolean).length;
65
+ return {
66
+ title: title ? decode(title).trim() : null,
67
+ description: meta.description ?? null,
68
+ robots: [meta.robots, meta.googlebot].filter(Boolean).join(', ').toLowerCase(),
69
+ ogImage: meta['og:image'] ?? null,
70
+ viewport: meta.viewport ?? null,
71
+ canonical,
72
+ canonicals,
73
+ hreflang,
74
+ emptyLinks,
75
+ jsonLd,
76
+ lang: attr(htmlTag, 'lang'),
77
+ h1,
78
+ imgsNoAlt,
79
+ anchors,
80
+ jsonLdErrors,
81
+ words,
82
+ redirect: /<meta\b[^>]*http-equiv\s*=\s*["']refresh["']/i.test(html),
83
+ };
84
+ }
85
+
86
+ const isNoindex = (robots) => /\b(noindex|none)\b/.test(robots || '');
87
+
88
+ // BCP 47 language tag as Google accepts it for hreflang and lang: language (ISO 639-1/2), optional script, optional region.
89
+ const LANG_RE = /^[a-z]{2,3}(-[a-z]{4})?(-([a-z]{2}|\d{3}))?$/i;
90
+
91
+ /** All JSON-LD nodes in a parsed document, flattening @graph and arrays. */
92
+ function nodes(doc, out = []) {
93
+ if (Array.isArray(doc)) { for (const d of doc) nodes(d, out); return out; }
94
+ if (!doc || typeof doc !== 'object') return out;
95
+ if (Array.isArray(doc['@graph'])) nodes(doc['@graph'], out);
96
+ if (doc['@type']) out.push(doc);
97
+ return out;
98
+ }
99
+ const types = (n) => [].concat(n['@type'] || []).map(String);
100
+
101
+ // Types that no longer produce a rich result in Google Search (checked December 2026). The markup is harmless,
102
+ // and other consumers (AI agents, other engines) may still read it.
103
+ export const RETIRED_RICH_RESULTS = {
104
+ FAQPage: 'FAQ rich results stopped appearing in Google Search on 7 May 2026',
105
+ HowTo: 'How-to rich results were removed from Google Search in 2023',
106
+ ClaimReview: 'Claim Review rich results were phased out in 2025',
107
+ SpecialAnnouncement: 'Special Announcement rich results were phased out in 2025',
108
+ Quiz: 'Practice problem rich results were phased out from January 2026',
109
+ Dataset: 'Dataset markup is used only by Google Dataset Search, not Google Search',
110
+ };
111
+
112
+ /** Minimal robots.txt reader (RFC 9309): the rules for a user agent, and whether a path is allowed. */
113
+ export function parseRobots(text) {
114
+ const groups = [];
115
+ let current = null;
116
+ let lastWasAgent = false;
117
+ const sitemaps = [];
118
+ for (const raw of String(text).split(/\r?\n/)) {
119
+ const line = raw.replace(/#.*/, '').trim();
120
+ const m = /^([a-z-]+)\s*:\s*(.*)$/i.exec(line);
121
+ if (!m) continue;
122
+ const key = m[1].toLowerCase();
123
+ const value = m[2].trim();
124
+ if (key === 'user-agent') {
125
+ if (!lastWasAgent) { current = { agents: [], rules: [] }; groups.push(current); }
126
+ current.agents.push(value.toLowerCase());
127
+ lastWasAgent = true;
128
+ } else {
129
+ lastWasAgent = false;
130
+ if (key === 'sitemap') sitemaps.push(value);
131
+ else if ((key === 'allow' || key === 'disallow') && current) current.rules.push({ allow: key === 'allow', path: value });
132
+ }
133
+ }
134
+ const rulesFor = (agent = '*') => {
135
+ const a = agent.toLowerCase();
136
+ const named = groups.filter((g) => g.agents.some((x) => x !== '*' && a.includes(x)));
137
+ return (named.length ? named : groups.filter((g) => g.agents.includes('*'))).flatMap((g) => g.rules);
138
+ };
139
+ const toRe = (p) => new RegExp('^' + p.replace(/[.+?^{}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\\\$$/, '$'));
140
+ const allowed = (path, agent) => {
141
+ let best = null;
142
+ for (const r of rulesFor(agent)) {
143
+ if (!r.path) continue; // empty Disallow allows everything
144
+ if (!toRe(r.path).test(path)) continue;
145
+ if (!best || r.path.length > best.path.length || (r.path.length === best.path.length && r.allow)) best = r;
146
+ }
147
+ return !best || best.allow;
148
+ };
149
+ return { groups, sitemaps, allowed };
150
+ }
151
+
152
+ const DEFAULTS = {
153
+ titleMin: 10, titleMax: 60, descMin: 50, descMax: 160, minWords: 100,
154
+ ignore: ['/404', '/500'],
155
+ };
156
+
157
+ /**
158
+ * Check a built site folder.
159
+ * @param {{outDir:string, site?:string, ignore?:(string|RegExp)[], ignoreLinks?:(string|RegExp)[], titleMax?:number, descMax?:number, minWords?:number, rules?:Record<string,'off'|'error'|'warning'|'info'>}} opts
160
+ */
161
+ export async function checkSite(opts) {
162
+ const o = { ...DEFAULTS, ...opts, ignore: [...DEFAULTS.ignore, ...(opts.ignore || [])] };
163
+ const outDir = o.outDir;
164
+ const siteUrl = o.site ? new URL(o.site) : null;
165
+ const issues = [];
166
+ const add = (rule, severity, page, message) => {
167
+ const override = o.rules?.[rule];
168
+ if (override === 'off') return;
169
+ issues.push({ rule, severity: override || severity, page, message });
170
+ };
171
+
172
+ const files = new Set();
173
+ const pages = [];
174
+ for await (const f of walk(outDir)) {
175
+ const rel = '/' + relative(outDir, f).split(sep).join('/');
176
+ files.add(rel);
177
+ if (rel.endsWith('.html')) pages.push(f);
178
+ }
179
+ const routes = new Map();
180
+ for (const f of pages) {
181
+ const route = routeOf(outDir, f);
182
+ if (o.ignore.some((p) => (p instanceof RegExp ? p.test(route) : route === p || route.startsWith(p.endsWith('/') ? p : p + '/')))) continue;
183
+ routes.set(route, parsePage(await readFile(f, 'utf8')));
184
+ }
185
+
186
+ const resolves = (path) => {
187
+ let p = decodeURIComponent(path.split('#')[0].split('?')[0]);
188
+ if (!p) return true;
189
+ if (files.has(p)) return true;
190
+ if (p.endsWith('/')) return files.has(p + 'index.html');
191
+ return files.has(p + '.html') || files.has(p + '/index.html');
192
+ };
193
+
194
+ const canonicalTargets = [];
195
+ const hreflangPages = new Map();
196
+ const inbound = new Map();
197
+ const normRoute = (x) => decodeURIComponent(x).replace(/index\.html$/, '').replace(/\.html$/, '').replace(/\/$/, '') || '/';
198
+ const titles = new Map();
199
+ const descs = new Map();
200
+ let slashStyles = { with: 0, without: 0 };
201
+
202
+ for (const [route, p] of routes) {
203
+ if (p.redirect) continue;
204
+ const noindex = isNoindex(p.robots);
205
+ if (!p.title) add('title-missing', 'error', route, 'Missing <title>');
206
+ else {
207
+ if (p.title.length > o.titleMax) add('title-length', 'warning', route, `Title is ${p.title.length} characters (over ${o.titleMax}): "${p.title}"`);
208
+ if (p.title.length < o.titleMin) add('title-length', 'warning', route, `Title is very short: "${p.title}"`);
209
+ if (!noindex) titles.set(p.title, [...(titles.get(p.title) || []), route]);
210
+ }
211
+ if (p.description === null || !p.description.trim()) add('description-missing', 'warning', route, 'Missing meta description');
212
+ else {
213
+ const len = p.description.trim().length;
214
+ if (len > o.descMax) add('description-length', 'info', route, `Meta description is ${len} characters (over ${o.descMax})`);
215
+ if (len < o.descMin) add('description-length', 'info', route, `Meta description is short (${len} characters)`);
216
+ if (!noindex) descs.set(p.description.trim(), [...(descs.get(p.description.trim()) || []), route]);
217
+ }
218
+ const distinctCanon = [...new Set(p.canonicals)];
219
+ if (distinctCanon.length > 1) add('canonical-multiple', 'error', route, `${distinctCanon.length} different canonical links (${distinctCanon.slice(0, 3).join(', ')}). Google may ignore all of them.`);
220
+ if (p.canonical && !/^https?:\/\//i.test(p.canonical)) add('canonical-relative', 'info', route, `Canonical is a relative URL (${p.canonical}). Google recommends an absolute URL.`);
221
+ if (p.canonical) {
222
+ try {
223
+ const c = new URL(p.canonical, siteUrl || 'http://x');
224
+ if ((!siteUrl || c.host === siteUrl.host) && c.pathname.replace(/\/$/, '') !== route.replace(/\/$/, '')) canonicalTargets.push({ route, target: c.pathname });
225
+ } catch { /* reported below */ }
226
+ }
227
+ if (!p.canonical) add('canonical-missing', 'warning', route, 'No canonical link');
228
+ else if (siteUrl) {
229
+ try {
230
+ const c = new URL(p.canonical, siteUrl);
231
+ if (c.host !== siteUrl.host) add('canonical-host', 'error', route, `Canonical points to ${c.host}, but site is ${siteUrl.host}`);
232
+ else if (c.pathname.replace(/\/$/, '') !== route.replace(/\/$/, '') && !noindex) add('canonical-other', 'info', route, `Canonical points to a different page: ${c.pathname}`);
233
+ } catch { add('canonical-invalid', 'error', route, `Invalid canonical URL: ${p.canonical}`); }
234
+ }
235
+ if (p.h1 === 0) add('h1-missing', 'warning', route, 'No <h1>');
236
+ if (p.h1 > 1) add('h1-multiple', 'info', route, `${p.h1} <h1> elements`);
237
+ if (!p.lang) add('lang-missing', 'warning', route, '<html> has no lang attribute');
238
+ else if (!LANG_RE.test(p.lang)) add('lang-invalid', 'warning', route, `<html lang="${p.lang}"> is not a valid language code (use for example en, ur, en-PK)`);
239
+ if (!p.viewport) add('viewport-missing', 'warning', route, 'No viewport meta tag. Google indexes the mobile version of pages.');
240
+ if (p.emptyLinks) add('link-text-empty', 'info', route, `${p.emptyLinks} link(s) with no text, aria-label or image alt. Search engines use link text to understand the target page.`);
241
+ if (p.hreflang.length) hreflangPages.set(route, p.hreflang);
242
+ for (const n of p.jsonLd.flatMap((d) => nodes(d))) {
243
+ for (const t of types(n)) {
244
+ if (RETIRED_RICH_RESULTS[t]) add('jsonld-retired', 'info', route, `${t}: ${RETIRED_RICH_RESULTS[t]}. The markup does no harm, but expect no rich result.`);
245
+ }
246
+ if (types(n).some((t) => t === 'Product' || t === 'ProductGroup')) {
247
+ const missing = [];
248
+ if (!n.name) missing.push('name');
249
+ if (!n.offers && !n.review && !n.aggregateRating && !n.hasVariant) missing.push('offers, review or aggregateRating (one is required)');
250
+ for (const o of [].concat(n.offers || [])) {
251
+ if (o && typeof o === 'object' && (o['@type'] === 'Offer' || !o['@type'])) {
252
+ if (o.price === undefined && !o.priceSpecification) missing.push('offers.price');
253
+ if (!o.priceCurrency && !o.priceSpecification) missing.push('offers.priceCurrency');
254
+ }
255
+ }
256
+ if (!n.image) missing.push('image (required for merchant listings)');
257
+ if (missing.length) add('jsonld-product', 'warning', route, `Product "${n.name || '?'}" is missing ${[...new Set(missing)].join(', ')}`);
258
+ }
259
+ if (!n['@context'] && p.jsonLd.every((d) => !d['@context'])) add('jsonld-context', 'warning', route, `JSON-LD ${types(n)[0] || ''} has no @context ("https://schema.org")`);
260
+ }
261
+ if (!p.ogImage) add('og-image-missing', 'info', route, 'No og:image (link previews will be plain)');
262
+ if (p.imgsNoAlt.length) add('img-alt', 'warning', route, `${p.imgsNoAlt.length} image(s) without alt: ${p.imgsNoAlt.slice(0, 3).join(', ')}`);
263
+ for (const e of p.jsonLdErrors) add('jsonld-invalid', 'error', route, `Invalid JSON-LD ${e}`);
264
+ if (!noindex && p.words < o.minWords && route !== '/') add('thin-content', 'info', route, `Only ${p.words} words of main content`);
265
+
266
+ const broken = new Set();
267
+ for (const href of p.anchors) {
268
+ if (!href || /^(#|mailto:|tel:|javascript:|data:|sms:|whatsapp:)/i.test(href)) continue;
269
+ let path;
270
+ if (/^https?:\/\//i.test(href) || href.startsWith('//')) {
271
+ if (!siteUrl) continue;
272
+ const u = new URL(href, siteUrl);
273
+ if (u.host !== siteUrl.host) continue;
274
+ path = u.pathname;
275
+ } else {
276
+ path = new URL(href, `http://x${route}`).pathname;
277
+ }
278
+ if ((o.ignoreLinks || []).some((x) => (x instanceof RegExp ? x.test(path) : path.startsWith(x)))) continue;
279
+ if (!resolves(path)) broken.add(path);
280
+ else if (path !== route) inbound.set(normRoute(path), (inbound.get(normRoute(path)) || 0) + 1);
281
+ if (!/\.[a-z0-9]+$/i.test(path) && path !== '/') path.endsWith('/') ? slashStyles.with++ : slashStyles.without++;
282
+ }
283
+ if (broken.size) add('broken-link', 'error', route, `${broken.size} broken internal link(s): ${[...broken].slice(0, 5).join(', ')}`);
284
+ }
285
+
286
+ const routeByNorm = new Map([...routes].map(([r, p]) => [normRoute(r), p]));
287
+ for (const { route, target } of canonicalTargets) {
288
+ const t = routeByNorm.get(normRoute(target));
289
+ if (!resolves(target)) add('canonical-broken', 'warning', route, `Canonical points to ${target}, which is not in the build`);
290
+ else if (t && isNoindex(t.robots)) add('canonical-to-noindex', 'warning', route, `Canonical points to ${target}, which is noindex. Mixed signals: Google may index neither.`);
291
+ }
292
+
293
+ // hreflang (Google: each language version must list itself and every other version, and the links must go both ways)
294
+ const hreflangByNorm = new Map([...hreflangPages].map(([r, a]) => [normRoute(r), a]));
295
+ for (const [route, alts] of hreflangPages) {
296
+ for (const a of alts) {
297
+ if (a.lang.toLowerCase() !== 'x-default' && !LANG_RE.test(a.lang)) add('hreflang-invalid', 'error', route, `hreflang="${a.lang}" is not a valid language or language-region code`);
298
+ }
299
+ let selfListed = false;
300
+ for (const a of alts) {
301
+ let target;
302
+ try { target = new URL(a.href, siteUrl || 'http://x'); } catch { add('hreflang-invalid', 'error', route, `hreflang link has an invalid URL: ${a.href}`); continue; }
303
+ if (siteUrl && target.host !== siteUrl.host) continue;
304
+ if (normRoute(target.pathname) === normRoute(route)) { selfListed = true; continue; }
305
+ const back = hreflangByNorm.get(normRoute(target.pathname));
306
+ if (!back) { if (resolves(target.pathname)) add('hreflang-no-return', 'warning', route, `${target.pathname} (${a.lang}) does not link back with hreflang. Google ignores one-way hreflang.`); else add('hreflang-broken', 'warning', route, `hreflang ${a.lang} points to ${target.pathname}, which is not in the build`); continue; }
307
+ if (!back.some((b) => { try { return normRoute(new URL(b.href, siteUrl || 'http://x').pathname) === normRoute(route); } catch { return false; } })) add('hreflang-no-return', 'warning', route, `${target.pathname} (${a.lang}) does not link back to this page. Google ignores one-way hreflang.`);
308
+ }
309
+ if (!selfListed) add('hreflang-self-missing', 'info', route, 'hreflang links do not include this page itself');
310
+ }
311
+
312
+ // Orphans: indexable pages no other page links to.
313
+ if (routes.size > 2) {
314
+ for (const [route, p] of routes) {
315
+ if (route === '/' || p.redirect || isNoindex(p.robots)) continue;
316
+ if (!inbound.get(normRoute(route))) add('orphan-page', 'info', route, 'No internal links point to this page. Link to it from a related page or a hub.');
317
+ }
318
+ }
319
+
320
+ for (const [t, list] of titles) if (list.length > 1) add('title-duplicate', 'warning', list[0], `Title "${t}" is used on ${list.length} pages: ${list.slice(0, 4).join(', ')}`);
321
+ for (const [d, list] of descs) if (list.length > 1) add('description-duplicate', 'warning', list[0], `Same meta description on ${list.length} pages: ${list.slice(0, 4).join(', ')}`);
322
+ if (slashStyles.with && slashStyles.without) {
323
+ add('trailing-slash', 'info', '(site)', `Internal links mix trailing slashes (${slashStyles.with} with, ${slashStyles.without} without). Pick one style to avoid redirect hops and duplicate URLs.`);
324
+ }
325
+
326
+ // site level
327
+ const sitemapFile = ['/sitemap-index.xml', '/sitemap.xml', '/sitemap_index.xml'].find((f) => files.has(f)) || [...files].find((f) => /^\/sitemap[^/]*\.xml$/.test(f));
328
+ if (!sitemapFile) add('sitemap-missing', 'warning', '(site)', 'No sitemap in the build (add @astrojs/sitemap)');
329
+ else {
330
+ // noindex pages listed in sitemap
331
+ const xmls = [...files].filter((f) => /sitemap.*\.xml$/.test(f));
332
+ const listed = new Set();
333
+ for (const x of xmls) {
334
+ const text = await readFile(join(outDir, ...x.split('/').filter(Boolean)), 'utf8').catch(() => '');
335
+ for (const m of text.matchAll(/<loc>([^<]+)<\/loc>/g)) {
336
+ try { listed.add(new URL(m[1]).pathname); } catch { /* ignore */ }
337
+ }
338
+ }
339
+ for (const [route, p] of routes) {
340
+ if (isNoindex(p.robots) && (listed.has(route) || listed.has(route + '/'))) add('noindex-in-sitemap', 'error', route, 'Page is noindex but listed in the sitemap');
341
+ if (p.redirect && (listed.has(route) || listed.has(route + '/'))) add('sitemap-redirect', 'warning', route, 'Redirect page is listed in the sitemap. List the final URL instead.');
342
+ }
343
+ const brokenInSitemap = [...listed].filter((pth) => !(o.ignoreLinks || []).some((x) => (x instanceof RegExp ? x.test(pth) : pth.startsWith(x))) && !resolves(pth));
344
+ if (brokenInSitemap.length) add('sitemap-broken', 'warning', '(site)', `${brokenInSitemap.length} sitemap URL(s) not in the build: ${brokenInSitemap.slice(0, 5).join(', ')}`);
345
+ for (const { route } of canonicalTargets) {
346
+ if (listed.has(route) || listed.has(route + '/')) add('sitemap-non-canonical', 'warning', route, 'Listed in the sitemap but its canonical points to another page. Sitemaps should list only canonical URLs.');
347
+ }
348
+ }
349
+ const robotsTxt = files.has('/robots.txt') ? await readFile(join(outDir, 'robots.txt'), 'utf8') : null;
350
+ if (robotsTxt === null) add('robots-missing', 'info', '(site)', 'No robots.txt in the build (it may be served by your host instead)');
351
+ else {
352
+ const rb = parseRobots(robotsTxt);
353
+ if (!rb.allowed('/', 'Googlebot')) add('robots-blocks-all', 'error', '(site)', 'robots.txt blocks Googlebot from the home page');
354
+ else {
355
+ const blockedPages = [...routes.keys()].filter((r) => !isNoindex(routes.get(r).robots) && !rb.allowed(r, 'Googlebot'));
356
+ if (blockedPages.length) add('robots-blocks-pages', 'warning', '(site)', `robots.txt blocks ${blockedPages.length} indexable page(s): ${blockedPages.slice(0, 4).join(', ')}`);
357
+ const assets = [...files].filter((f) => /\.(css|js|mjs)$/.test(f) && !rb.allowed(f, 'Googlebot'));
358
+ if (assets.length) add('robots-blocks-assets', 'warning', '(site)', `robots.txt blocks ${assets.length} CSS/JS file(s) (${assets.slice(0, 2).join(', ')}). Google needs them to render pages.`);
359
+ }
360
+ const blockedNoindex = [...routes.entries()].filter(([r, p]) => isNoindex(p.robots) && !rb.allowed(r, 'Googlebot')).map(([r]) => r);
361
+ if (blockedNoindex.length) add('noindex-blocked', 'warning', '(site)', `${blockedNoindex.length} noindex page(s) are also blocked in robots.txt, so Google cannot see the noindex: ${blockedNoindex.slice(0, 4).join(', ')}`);
362
+ if (!rb.sitemaps.length && sitemapFile) add('robots-no-sitemap', 'info', '(site)', `robots.txt has no Sitemap: line. Add "Sitemap: ${siteUrl ? new URL(sitemapFile, siteUrl).href : sitemapFile}".`);
363
+ }
364
+ if (!files.has('/404.html')) add('404-missing', 'info', '(site)', 'No custom 404 page');
365
+
366
+ return { pages: routes.size, issues };
367
+ }
368
+
369
+ export function format(result, { verbose = false } = {}) {
370
+ const order = { error: 0, warning: 1, info: 2 };
371
+ const shown = verbose ? result.issues : result.issues.filter((i) => i.severity !== 'info');
372
+ const sorted = [...shown].sort((a, b) => order[a.severity] - order[b.severity] || a.page.localeCompare(b.page));
373
+ const count = (s) => result.issues.filter((i) => i.severity === s).length;
374
+ const lines = [`SEO check: ${result.pages} pages, ${count('error')} error(s), ${count('warning')} warning(s), ${count('info')} info`];
375
+ for (const i of sorted) lines.push(` ${i.severity.toUpperCase().padEnd(7)} ${i.page.padEnd(28)} ${i.message} [${i.rule}]`);
376
+ if (!verbose && count('info')) lines.push(` (${count('info')} info note(s) hidden. Use verbose: true or --verbose to see them.)`);
377
+ return lines.join('\n');
378
+ }
package/src/index.js ADDED
@@ -0,0 +1,47 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { checkSite, format, parsePage, routeOf, parseRobots, RETIRED_RICH_RESULTS } from './check.js';
4
+
5
+ export { checkSite, format, parsePage, routeOf, parseRobots, RETIRED_RICH_RESULTS };
6
+
7
+ /**
8
+ * Astro integration.
9
+ * @param {Object} [options]
10
+ * @param {'error'|'warning'|false} [options.failOn='error'] Fail the build at this level
11
+ * @param {string} [options.report] Write a JSON report to this path (relative to the project root)
12
+ * @param {(string|RegExp)[]} [options.ignore] Pages to skip
13
+ * @param {(string|RegExp)[]} [options.ignoreLinks] Link targets not in the static build (API routes, server pages)
14
+ * @param {Record<string,'off'|'error'|'warning'|'info'>} [options.rules] Change or switch off rules
15
+ * @param {boolean} [options.verbose=false] Also print info notes
16
+ */
17
+ export default function seoCheck(options = {}) {
18
+ const { failOn = 'error', report, verbose = false, ...checkOpts } = options;
19
+ let site;
20
+ let root;
21
+ return {
22
+ name: 'astro-seo-check',
23
+ hooks: {
24
+ 'astro:config:done': ({ config }) => {
25
+ site = config.site ? String(config.site) : undefined;
26
+ root = config.root;
27
+ },
28
+ 'astro:build:done': async ({ dir, logger }) => {
29
+ const outDir = dir instanceof URL ? fileURLToPath(dir) : String(dir);
30
+ const log = logger || console;
31
+ const result = await checkSite({ outDir, site, ...checkOpts });
32
+ const text = format(result, { verbose });
33
+ const errors = result.issues.filter((i) => i.severity === 'error').length;
34
+ const warnings = result.issues.filter((i) => i.severity === 'warning').length;
35
+ (errors ? log.error?.bind(log) || log.warn.bind(log) : warnings ? log.warn.bind(log) : log.info.bind(log))(text);
36
+ if (report) {
37
+ const path = root ? fileURLToPath(new URL(report, root)) : report;
38
+ await writeFile(path, JSON.stringify(result, null, 2));
39
+ log.info(`Report written to ${report}`);
40
+ }
41
+ if ((failOn === 'error' && errors) || (failOn === 'warning' && (errors || warnings))) {
42
+ throw new Error(`astro-seo-check found ${errors} error(s) and ${warnings} warning(s). Fix them or change failOn.`);
43
+ }
44
+ },
45
+ },
46
+ };
47
+ }