Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

SEO Audit v0.2.2 · claude-code

Archive SHA-256 ebbd8d46148768959e990b4461e3c295be450a4b06b9f39a5d4bd745798f27fe · 45.6 KB · built Nov 27, 2026

src/audit.js

// On-page SEO checks for seo-audit. Heuristic hygiene checks only: they make no claim about rankings.
import { tokenize } from "./html.js";

export const DEFAULT_THRESHOLDS = { title_min: 30, title_max: 60, description_min: 70, description_max: 160, min_words: 300 };
export const DISCLAIMER = "These are on-page hygiene checks based on common published guidelines. They do not measure, predict or guarantee search rankings or traffic.";

const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr", "param", "keygen"]);
const HIDDEN_CONTEXT = new Set(["head", "template", "svg", "noscript", "textarea", "select", "math"]);
const WORD = /[\p{L}\p{N}]+(?:['’-][\p{L}\p{N}]+)*/gu;

const clean = (s) => s.replace(/[\s\u00A0]+/g, " ").trim();
const chars = (s) => [...s].length;
const stripWww = (h) => h.replace(/^www\./, "");

export function extract(html) {
  const tokens = tokenize(html);
  const m = {
    titles: [],
    descriptions: [],
    robots: [],
    canonicals: [],
    og: {},
    headings: [],
    images: [],
    links: [],
    lang: null,
    viewport: false,
    base: null,
    textParts: [],
    tagCount: 0,
  };
  const hidden = {}; // open hidden-context element counts
  let hiddenDepth = 0;
  let inTitle = false;
  let titleText = "";
  let heading = null;
  let link = null; // the <a href> being read, to collect its anchor text
  for (const t of tokens) {
    if (t.type === "start") {
      m.tagCount++;
      const a = t.attrs;
      if (t.name === "body") { hiddenDepth -= hidden.head ?? 0; hidden.head = 0; }
      if (t.name === "html" && a.lang !== undefined) m.lang = a.lang.trim() || null;
      if (t.name === "title" && !(hidden.svg > 0)) { inTitle = true; titleText = ""; }
      if (t.name === "meta") {
        const name = (a.name ?? "").toLowerCase().trim();
        const prop = (a.property ?? "").toLowerCase().trim();
        if (name === "description") m.descriptions.push(clean(a.content ?? ""));
        if (name === "robots" || name === "googlebot") m.robots.push((a.content ?? "").toLowerCase());
        if (name === "viewport") m.viewport = true;
        if (prop.startsWith("og:") && !(prop in m.og)) m.og[prop.slice(3)] = clean(a.content ?? "");
      }
      if (t.name === "link" && (a.rel ?? "").toLowerCase().split(/\s+/).includes("canonical")) m.canonicals.push((a.href ?? "").trim());
      if (t.name === "base" && a.href && !m.base) m.base = a.href.trim();
      if (/^h[1-6]$/.test(t.name) && !hiddenDepth) {
        if (heading) m.headings.push({ level: heading.level, text: clean(heading.text) });
        heading = { level: Number(t.name[1]), text: "" };
      }
      if (t.name === "img") {
        const decorative = (a.role ?? "").toLowerCase() === "presentation" || (a.role ?? "").toLowerCase() === "none" || (a["aria-hidden"] ?? "").toLowerCase() === "true";
        m.images.push({ src: a.src ?? "", hasAlt: "alt" in a, alt: (a.alt ?? "").trim(), decorative });
        if (heading && a.alt) heading.text += ` ${a.alt}`;
        if (link && a.alt) link.text += ` ${a.alt}`;
      }
      if (t.name === "a") link = null; // <a> cannot nest; a new one closes the previous
      if (t.name === "a" && "href" in a) {
        link = { href: a.href.trim(), rel: (a.rel ?? "").toLowerCase(), text: "", label: clean(a["aria-label"] ?? a.title ?? "") };
        m.links.push(link);
      }
      if (HIDDEN_CONTEXT.has(t.name) && !VOID.has(t.name) && !t.selfClosing) { hidden[t.name] = (hidden[t.name] ?? 0) + 1; hiddenDepth++; }
    } else if (t.type === "end") {
      if (t.name === "title" && inTitle) { inTitle = false; m.titles.push(clean(titleText)); }
      if (t.name === "a") link = null;
      if (heading && t.name === `h${heading.level}`) { m.headings.push({ level: heading.level, text: clean(heading.text) }); heading = null; }
      if (HIDDEN_CONTEXT.has(t.name) && hidden[t.name] > 0) { hidden[t.name]--; hiddenDepth--; }
    } else {
      if (inTitle) { titleText += t.text; continue; }
      if (heading) heading.text += t.text;
      if (link) link.text += t.text;
      if (!hiddenDepth) m.textParts.push(t.text);
    }
  }
  if (inTitle) m.titles.push(clean(titleText));
  if (heading) m.headings.push({ level: heading.level, text: clean(heading.text) });
  m.wordCount = (m.textParts.join(" ").match(WORD) ?? []).length;
  for (const l of m.links) l.text = clean(l.text);
  return m;
}

function classifyLinks(links, pageUrl, base, siteHost) {
  const counts = { total: links.length, internal: 0, external: 0, other: 0, nofollow: 0, javascript: 0 };
  const DUMMY = "https://page.invalid/";
  let baseUrl = DUMMY;
  try { if (pageUrl) baseUrl = new URL(pageUrl).href; } catch { /* relative path: keep dummy base */ }
  try { if (base) baseUrl = new URL(base, baseUrl).href; } catch { /* invalid <base>: ignore */ }
  const site = siteHost ? stripWww(siteHost.toLowerCase()) : null;
  for (const l of links) {
    if (l.rel.split(/\s+/).includes("nofollow")) counts.nofollow++;
    const href = l.href;
    if (/^javascript:/i.test(href)) { counts.other++; counts.javascript++; continue; }
    if (!href || href.startsWith("#") || /^(mailto|tel|sms|data|ftp):/i.test(href)) { counts.other++; continue; }
    let u;
    try { u = new URL(href, baseUrl); } catch { counts.other++; continue; }
    if (u.protocol !== "http:" && u.protocol !== "https:") { counts.other++; continue; }
    const host = stripWww(u.hostname.toLowerCase());
    if (host === "page.invalid" || (site && host === site)) counts.internal++;
    else counts.external++;
  }
  return counts;
}

function absoluteHost(urlOrPath) {
  try {
    const u = new URL(urlOrPath);
    return u.protocol === "http:" || u.protocol === "https:" ? u.hostname.toLowerCase() : null;
  } catch {
    return null;
  }
}

/** The page's own URL: absolute url_or_path, or a "/path" on site_host (protocol then unknown). */
function pageLocation(urlOrPath, siteHost) {
  try {
    const u = new URL(urlOrPath);
    if (u.protocol === "http:" || u.protocol === "https:") return { url: u, protocolKnown: true };
  } catch { /* a path */ }
  if (siteHost && urlOrPath.startsWith("/") && !urlOrPath.startsWith("//")) {
    try { return { url: new URL(urlOrPath, `https://${siteHost}`), protocolKnown: false }; } catch { /* invalid path */ }
  }
  return null;
}

/** Comparable form of a URL: host without www, path without a trailing slash, query; no hash or protocol. */
const urlKey = (u) => `${stripWww(u.hostname.toLowerCase())}${u.pathname.replace(/(.)\/$/, "$1")}${u.search}`;

const GENERIC_ANCHORS = new Set(["click here", "click", "here", "read more", "more", "learn more", "find out more", "see more", "more info", "info", "details", "this link", "link", "this page", "continue", "go"]);

export function analyzePage(page, opts) {
  const th = { ...DEFAULT_THRESHOLDS, ...(opts.thresholds ?? {}) };
  const html = page.html ?? "";
  const m = extract(html);
  const issues = [];
  const add = (rule, severity, message, details) => issues.push({ rule, severity, message, ...(details ? { details } : {}) });
  const siteHost = opts.siteHost ?? absoluteHost(page.url_or_path);
  const pageUrlOrPath = page.url_or_path;

  if (!html.trim() || (m.tagCount === 0 && m.wordCount === 0)) {
    add("html-empty", "error", "No HTML content was supplied for this page.");
  }

  // Title
  const title = m.titles[0] ?? null;
  if (!m.titles.length) add("title-missing", "error", "The page has no <title> element.");
  else if (!title) add("title-empty", "error", "The <title> element is empty.");
  else {
    const n = chars(title);
    if (n < th.title_min) add("title-too-short", "warning", `Title is ${n} characters, below the ${th.title_min}-character guideline; it may not describe the page fully.`);
    if (n > th.title_max) add("title-too-long", "warning", `Title is ${n} characters, above the ${th.title_max}-character guideline; search engines may truncate long titles in result listings.`);
  }
  if (m.titles.length > 1) add("title-multiple", "warning", `Found ${m.titles.length} <title> elements; only one is expected.`);

  // Meta description
  const desc = m.descriptions[0] ?? null;
  if (!m.descriptions.length) add("meta-description-missing", "warning", 'No <meta name="description"> found; search engines will choose their own snippet text.');
  else if (!desc) add("meta-description-empty", "warning", "The meta description is empty.");
  else {
    const n = chars(desc);
    if (n < th.description_min) add("meta-description-too-short", "notice", `Meta description is ${n} characters, below the ${th.description_min}-character guideline.`);
    if (n > th.description_max) add("meta-description-too-long", "notice", `Meta description is ${n} characters, above the ${th.description_max}-character guideline; it may be truncated in result snippets.`);
  }
  if (m.descriptions.length > 1) add("meta-description-multiple", "warning", `Found ${m.descriptions.length} meta descriptions; only one is expected.`);

  // Headings
  const h1s = m.headings.filter((h) => h.level === 1);
  if (!h1s.length) add("h1-missing", "error", "The page has no <h1> heading.");
  if (h1s.length > 1) add("h1-multiple", "warning", `Found ${h1s.length} <h1> headings; a single <h1> naming the page's main topic is the common convention.`, { h1: h1s.map((h) => h.text).slice(0, 10) });
  if (h1s.some((h) => !h.text)) add("h1-empty", "warning", "An <h1> heading has no text.");
  if (m.headings.length && m.headings[0].level !== 1) add("heading-first-not-h1", "notice", `The first heading is an <h${m.headings[0].level}> ("${m.headings[0].text.slice(0, 60)}"), not an <h1>.`);
  let skips = 0;
  for (let i = 1; i < m.headings.length; i++) {
    const prev = m.headings[i - 1];
    const cur = m.headings[i];
    if (cur.level > prev.level + 1 && skips++ < 10) {
      add("heading-level-skip", "warning", `<h${prev.level}> "${prev.text.slice(0, 50)}" is followed by <h${cur.level}> "${cur.text.slice(0, 50)}", skipping level ${prev.level + 1}.`);
    }
  }

  // Images
  const missingAlt = m.images.filter((im) => !im.hasAlt && !im.decorative);
  const emptyAlt = m.images.filter((im) => im.hasAlt && !im.alt);
  if (missingAlt.length) add("img-alt-missing", "warning", `${missingAlt.length} of ${m.images.length} image(s) have no alt attribute (use alt="" for purely decorative images).`, { src: missingAlt.slice(0, 10).map((im) => im.src) });

  // Canonical
  const canonical = m.canonicals[0] ?? null;
  if (!m.canonicals.length) add("canonical-missing", "notice", 'No <link rel="canonical"> found.');
  else {
    if (m.canonicals.length > 1) add("canonical-multiple", "warning", `Found ${m.canonicals.length} canonical links; search engines may ignore conflicting canonicals.`, { href: m.canonicals.slice(0, 5) });
    let cu = null;
    try { cu = new URL(canonical); } catch { /* relative or invalid */ }
    if (!canonical) add("canonical-invalid", "warning", "The canonical link has an empty href.");
    else if (!cu) {
      if (URL.canParse(canonical, "https://page.invalid/")) add("canonical-relative", "notice", `Canonical URL "${canonical.slice(0, 100)}" is relative; an absolute URL is recommended.`);
      else add("canonical-invalid", "warning", `Canonical URL "${canonical.slice(0, 100)}" is not a valid URL.`);
    } else if (cu.protocol !== "https:" && cu.protocol !== "http:") add("canonical-invalid", "warning", `Canonical URL uses unsupported scheme ${cu.protocol}`);
    else {
      const page = pageLocation(pageUrlOrPath, siteHost);
      if (cu.protocol === "http:") {
        const known = page?.protocolKnown && page.url.protocol === "https:";
        add("canonical-not-https", known ? "warning" : "notice", known ? `Canonical URL uses http:// although this page is served over https; point it to the https URL.` : `Canonical URL uses http://; if the site is served over https, point it to the https URL.`, { href: canonical.slice(0, 300) });
      }
      if (siteHost && stripWww(cu.hostname.toLowerCase()) !== stripWww(siteHost)) add("canonical-cross-host", "notice", `Canonical points to another host (${cu.hostname}); confirm this is intended.`);
      else if (page && urlKey(cu) !== urlKey(page.url)) add("canonical-other-url", "notice", `Canonical points to a different URL (${cu.pathname}${cu.search}); search engines will usually index that URL instead of this one. Expected for duplicates and variants, otherwise point it at this page.`, { href: canonical.slice(0, 300) });
    }
  }

  // Robots (meta tags plus an X-Robots-Tag header when the page was fetched)
  const robots = [...m.robots, ...(page.x_robots_tag ? [page.x_robots_tag.toLowerCase()] : [])].join(", ");
  const directives = robots.split(/[\s,]+/).filter(Boolean);
  if (directives.includes("noindex") || directives.includes("none")) add("robots-noindex", "warning", `Robots directives ask search engines not to index this page (${robots}); confirm this is intended.`);
  if (directives.includes("nofollow") || directives.includes("none")) add("robots-nofollow", "notice", `Robots directives ask search engines not to follow links on this page (${robots}).`);

  // Open Graph basics (the four required OGP properties plus description)
  const ogKeys = ["title", "type", "image", "url", "description"];
  const ogMissing = ogKeys.filter((k) => !m.og[k]);
  if (ogMissing.length === ogKeys.length) add("og-missing", "notice", "No Open Graph tags (og:title, og:type, og:image, og:url, og:description); link previews in social apps will be generic.");
  else if (ogMissing.length) add("og-incomplete", "notice", `Missing Open Graph properties: ${ogMissing.map((k) => `og:${k}`).join(", ")}.`, { missing: ogMissing.map((k) => `og:${k}`) });

  if (!m.lang) add("lang-missing", "notice", "The <html> element has no lang attribute.");
  if (!m.viewport) add("viewport-missing", "notice", 'No <meta name="viewport"> found; the page may not scale on mobile devices.');
  if (html.trim() && m.wordCount < th.min_words) add("word-count-low", "notice", `The page has ${m.wordCount} words of visible text (guideline: ${th.min_words}); check that it covers its topic for visitors.`);

  const links = classifyLinks(m.links, page.url_or_path, m.base, siteHost);
  if (links.javascript) add("link-javascript", "notice", `${links.javascript} link(s) use javascript: URLs, which crawlers cannot follow.`);
  const navigable = m.links.filter((l) => l.href && !l.href.startsWith("#") && !/^(javascript|mailto|tel|sms|data):/i.test(l.href));
  const noText = navigable.filter((l) => !l.text && !l.label);
  if (noText.length) add("link-no-text", "notice", `${noText.length} link(s) have no anchor text (no words, image alt text or aria-label), so search engines and screen readers get no description of the target.`, { href: noText.slice(0, 10).map((l) => l.href.slice(0, 300)) });
  const generic = navigable.filter((l) => GENERIC_ANCHORS.has(l.text.toLowerCase().replace(/[\s.:!»›→>…-]+$/u, "")));
  if (generic.length) add("link-generic-text", "notice", `${generic.length} link(s) use generic anchor text such as "${generic[0].text.slice(0, 40)}"; descriptive text tells visitors and search engines what the target page is about.`, { links: generic.slice(0, 10).map((l) => ({ text: l.text.slice(0, 80), href: l.href.slice(0, 300) })) });
  if (html.trim() && links.internal === 0) add("links-internal-none", "notice", "The page has no internal links to other pages of the site.");

  const metrics = {
    title,
    title_length: title ? chars(title) : 0,
    meta_description: desc,
    meta_description_length: desc ? chars(desc) : 0,
    h1_count: h1s.length,
    headings: m.headings.slice(0, 100),
    word_count: m.wordCount,
    images: m.images.length,
    images_missing_alt: missingAlt.length,
    images_empty_alt: emptyAlt.length,
    links: { total: links.total, internal: links.internal, external: links.external, other: links.other, nofollow: links.nofollow },
    canonical,
    robots: robots || null,
    open_graph: Object.fromEntries(ogKeys.map((k) => [k, m.og[k] || null])),
    lang: m.lang,
    viewport: m.viewport,
    site_host: siteHost,
  };
  return { url_or_path: page.url_or_path, issues, metrics };
}

const SEVERITY_RANK = { error: 0, warning: 1, notice: 2 };

export function auditPages(pages, opts = {}) {
  const results = pages.map((p) => analyzePage(p, { thresholds: opts.thresholds, siteHost: opts.siteHost ?? null }));
  const siteIssues = [];
  const dup = (field, rule, severity, label) => {
    const groups = new Map();
    for (const r of results) {
      const v = r.metrics[field];
      if (!v) continue;
      const key = v.toLowerCase();
      if (!groups.has(key)) groups.set(key, []);
      groups.get(key).push(r);
    }
    for (const [, rs] of groups) {
      if (rs.length < 2) continue;
      const paths = rs.map((r) => r.url_or_path);
      siteIssues.push({ rule, severity, message: `${rs.length} pages share the same ${label}: "${rs[0].metrics[field].slice(0, 80)}"`, pages: paths });
      for (const r of rs) {
        const others = paths.filter((p) => p !== r.url_or_path);
        r.issues.push({ rule, severity, message: `The ${label} is the same as on ${others.length} other page(s): ${others.slice(0, 5).join(", ")}${others.length > 5 ? ", …" : ""}.` });
      }
    }
  };
  dup("title", "title-duplicate", "warning", "title");
  dup("meta_description", "meta-description-duplicate", "notice", "meta description");
  const summary = { pages: results.length, errors: 0, warnings: 0, notices: 0, by_rule: {} };
  for (const r of results) {
    r.issues.sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]);
    for (const i of r.issues) {
      summary[`${i.severity}s`]++;
      summary.by_rule[i.rule] = (summary.by_rule[i.rule] ?? 0) + 1;
    }
  }
  return { pages: results, site_issues: siteIssues, summary, disclaimer: DISCLAIMER };
}

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).