Skip to main content

docs_compiler/
seo.rs

1//! SEO emission (Wave 2c): full HTML documents with the estate-seo
2//! floor's technical artifacts - title, meta description, canonical,
3//! Open Graph, JSON-LD per page; `llms.txt`, `sitemap.xml`, and
4//! `robots.txt` per site (with `base_url` in `site.toml`).
5//!
6//! Policy decisions, recorded (estate-seo: never block AI crawlers
7//! silently): `site.toml` carries `ai_crawlers = "allow"` (default) /
8//! `"block-training"` / `"block-all"`, and the emitted robots.txt states
9//! the decision in a comment next to the rules.
10//!
11//! Inputs are deliberately tiny: front-matter is `key: value` scalars
12//! under a leading `---` fence; `site.toml` is `key = "value"` lines.
13//! No YAML/TOML dependency; anything richer belongs to a real pipeline.
14
15use std::path::Path;
16
17use crate::directives::html_escape;
18
19/// One indexable page, as the SEO emitters see it.
20#[derive(Debug, Clone, PartialEq)]
21pub struct SeoPage {
22    /// Site-relative HTML route (`index.html`, `guides/x.html`).
23    pub route: String,
24    /// Page title (front-matter, first h1, or file stem).
25    pub title: String,
26    /// Meta description (front-matter or first paragraph).
27    pub description: String,
28    /// Declared publication date (ISO), for sitemap lastmod + JSON-LD.
29    pub date: Option<String>,
30}
31
32/// Site-wide settings, from `site.toml` in the source root.
33#[derive(Debug, Clone, PartialEq)]
34pub struct SiteConfig {
35    /// Absolute origin for canonical URLs, sitemap, and llms.txt
36    /// (`https://docs.example.com`, no trailing slash).
37    pub base_url: String,
38    /// Site title (llms.txt heading, JSON-LD `isPartOf`).
39    pub site_title: String,
40    /// Named author (E-E-A-T: real names beat anonymous).
41    pub author: String,
42    /// AI-crawler policy, recorded in robots.txt: `"allow"` (default),
43    /// `"block-training"`, `"block-all"`.
44    pub ai_crawlers: String,
45    /// Stylesheet URL emitted as a `<link rel="stylesheet">` in every
46    /// page head (e.g. the islands' Tailwind build).
47    pub stylesheet: Option<String>,
48    /// The island shim module URL, emitted as a deferred module script
49    /// in every page head (registers `<docs-island>`).
50    pub island_shim: Option<String>,
51}
52
53impl SiteConfig {
54    /// Parse `site.toml` if present: `key = "value"` scalar lines only.
55    /// `base_url` is the one required key; the rest have defaults.
56    pub fn load(src: &Path) -> Option<SiteConfig> {
57        let text = std::fs::read_to_string(src.join("site.toml")).ok()?;
58        let mut base_url = None;
59        let mut site_title = String::from("Documentation");
60        let mut author = String::new();
61        let mut ai_crawlers = String::from("allow");
62        let mut stylesheet = None;
63        let mut island_shim = None;
64        for line in text.lines() {
65            let line = line.trim();
66            if line.is_empty() || line.starts_with('#') {
67                continue;
68            }
69            let Some((key, value)) = line.split_once('=') else {
70                continue;
71            };
72            let value = value.trim().trim_matches('"').to_string();
73            match key.trim() {
74                "base_url" => base_url = Some(value.trim_end_matches('/').to_string()),
75                "site_title" => site_title = value,
76                "author" => author = value,
77                "ai_crawlers" => ai_crawlers = value,
78                "stylesheet" => stylesheet = Some(value),
79                "island_shim" => island_shim = Some(value),
80                _ => {}
81            }
82        }
83        Some(SiteConfig {
84            base_url: base_url.map(|u| u.trim_end_matches('/').to_string())?,
85            site_title,
86            author,
87            ai_crawlers,
88            stylesheet,
89            island_shim,
90        })
91    }
92}
93
94/// Per-page metadata, from the page's front-matter (`---` fenced
95/// `key: value` scalars). `title` falls back to the first `<h1>`, then
96/// the file stem; `description` falls back to the first paragraph.
97#[derive(Debug, Clone, Default, PartialEq)]
98pub struct PageMeta {
99    /// Page title.
100    pub title: Option<String>,
101    /// Meta description.
102    pub description: Option<String>,
103    /// Output file stem override (route becomes `<slug>.html`).
104    pub slug: Option<String>,
105    /// Publication date (ISO `YYYY-MM-DD`; sitemap lastmod + JSON-LD).
106    pub date: Option<String>,
107}
108
109/// Split a leading `---` front-matter block off a document: returns the
110/// parsed metadata and the remainder to compile.
111#[must_use]
112pub fn split_front_matter(markdown: &str) -> (PageMeta, String) {
113    let mut meta = PageMeta::default();
114    let Some(rest) = markdown.strip_prefix("---\n") else {
115        return (meta, markdown.to_string());
116    };
117    let Some(close) = rest.find("\n---") else {
118        return (meta, markdown.to_string());
119    };
120    let block = &rest[..close];
121    for line in block.lines() {
122        let Some((key, value)) = line.split_once(':') else {
123            continue;
124        };
125        let value = value.trim().to_string();
126        match key.trim() {
127            "title" => meta.title = Some(value),
128            "description" => meta.description = Some(value),
129            "slug" => meta.slug = Some(value),
130            "date" => meta.date = Some(value),
131            _ => {}
132        }
133    }
134    // Skip the closing fence line and any following blank lines
135    // (markdown leading whitespace is insignificant).
136    let after = &rest[close + 4..];
137    (meta, after.trim_start_matches('\n').to_string())
138}
139
140/// Derive a page title from the rendered body: the first `<h1>` text.
141#[must_use]
142pub fn first_h1(body: &str) -> Option<String> {
143    let start = body.find("<h1>")? + 4;
144    let end = body[start..].find("</h1>")? + start;
145    let text = strip_tags(&body[start..end]);
146    if text.is_empty() {
147        None
148    } else {
149        Some(text)
150    }
151}
152
153/// Derive a description from the rendered body: the first paragraph's
154/// text, tags stripped, truncated at a word boundary to 155 chars.
155#[must_use]
156pub fn first_paragraph(body: &str) -> Option<String> {
157    let start = body.find("<p>")? + 3;
158    let end = body[start..].find("</p>")? + start;
159    let text = strip_tags(&body[start..end]);
160    if text.is_empty() {
161        return None;
162    }
163    Some(truncate_words(&text, 155))
164}
165
166fn strip_tags(html: &str) -> String {
167    let mut out = String::with_capacity(html.len());
168    let mut in_tag = false;
169    for c in html.chars() {
170        match c {
171            '<' => in_tag = true,
172            '>' => in_tag = false,
173            c if !in_tag => out.push(c),
174            _ => {}
175        }
176    }
177    out.trim().to_string()
178}
179
180fn truncate_words(text: &str, max: usize) -> String {
181    if text.len() <= max {
182        return text.to_string();
183    }
184    match text[..max].rfind(' ') {
185        Some(pos) => format!("{}...", &text[..pos]),
186        None => format!("{}...", &text[..max]),
187    }
188}
189
190/// Attribute-safe escaping: text escaping plus double quotes (SEO head
191/// values live inside `content="..."` attributes).
192fn escape_attr(text: &str) -> String {
193    html_escape(text).replace('"', "&quot;")
194}
195
196/// The full-document wrapper: doctype, head (charset, viewport, title,
197/// description, canonical, Open Graph, Twitter card, JSON-LD), body.
198/// `route` is the page's site-relative HTML path (`index.html`,
199/// `guides/x.html`). Length guidance (title <=60, description <=155)
200/// surfaces as warnings in the report, not build failures.
201#[must_use]
202pub fn document(
203    body: &str,
204    meta: &PageMeta,
205    title: &str,
206    description: &str,
207    route: &str,
208    config: Option<&SiteConfig>,
209) -> String {
210    let canonical = config
211        .map(|c| format!("{}/{}", c.base_url, route))
212        .unwrap_or_default();
213    let canonical_tags = if canonical.is_empty() {
214        String::new()
215    } else {
216        format!(
217            "<link rel=\"canonical\" href=\"{u}\"><meta property=\"og:url\" content=\"{u}\">",
218            u = escape_attr(&canonical)
219        )
220    };
221    let json_ld_tag = config
222        .map(|c| {
223            let mut article = serde_json::json!({
224                "@context": "https://schema.org",
225                "@type": "TechArticle",
226                "headline": title,
227                "description": description,
228                "isPartOf": { "@type": "WebSite", "name": c.site_title, "url": c.base_url },
229            });
230            if let Some(obj) = article.as_object_mut() {
231                if !canonical.is_empty() {
232                    obj.insert("url".into(), serde_json::json!(canonical));
233                }
234                if !c.author.is_empty() {
235                    obj.insert(
236                        "author".into(),
237                        serde_json::json!({ "@type": "Person", "name": c.author }),
238                    );
239                }
240                if let Some(date) = &meta.date {
241                    obj.insert("datePublished".into(), serde_json::json!(date));
242                }
243            }
244            format!("<script type=\"application/ld+json\">{article}</script>")
245        })
246        .unwrap_or_default();
247    let site_name_tag = config
248        .map(|c| {
249            format!(
250                "<meta property=\"og:site_name\" content=\"{}\">",
251                escape_attr(&c.site_title)
252            )
253        })
254        .unwrap_or_default();
255    // Site-level head wiring (Wave 2c.5): the islands' stylesheet and
256    // the shim module that registers <docs-island>.
257    let head_extra = config
258        .map(|c| {
259            let mut extra = String::new();
260            if let Some(css) = &c.stylesheet {
261                extra.push_str(&format!(
262                    "<link rel=\"stylesheet\" href=\"{}\">",
263                    escape_attr(css)
264                ));
265            }
266            if let Some(shim) = &c.island_shim {
267                extra.push_str(&format!(
268                    "<script type=\"module\" src=\"{}\"></script>",
269                    escape_attr(shim)
270                ));
271            }
272            extra
273        })
274        .unwrap_or_default();
275    format!(
276        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
277<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
278<title>{t}</title>\
279<meta name=\"description\" content=\"{d}\">{canonical_tags}\
280<meta property=\"og:type\" content=\"article\">\
281<meta property=\"og:title\" content=\"{t}\">\
282<meta property=\"og:description\" content=\"{d}\">{site_name_tag}\
283<meta name=\"twitter:card\" content=\"summary\">\
284<meta name=\"twitter:title\" content=\"{t}\">\
285<meta name=\"twitter:description\" content=\"{d}\">\
286{head_extra}{json_ld_tag}</head><body>{body}</body></html>",
287        t = escape_attr(title),
288        d = escape_attr(description)
289    )
290}
291
292/// `llms.txt` (GEO floor): the site heading plus one curated link per
293/// page with its description.
294#[must_use]
295pub fn llms_txt(config: &SiteConfig, pages: &[SeoPage]) -> String {
296    let mut out = format!("# {}\n\n", config.site_title);
297    if !config.author.is_empty() {
298        out.push_str(&format!("By {}.\n\n", config.author));
299    }
300    for page in pages {
301        out.push_str(&format!(
302            "- [{t}]({u}/{r}): {d}\n",
303            t = page.title,
304            u = config.base_url,
305            r = page.route,
306            d = page.description
307        ));
308    }
309    out
310}
311
312/// `sitemap.xml`: one `<url>` per page, sorted by route; `lastmod` only
313/// when the page declares a date (deterministic builds do not lie about
314/// modification times).
315#[must_use]
316pub fn sitemap_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
317    let mut out = String::from(
318        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n",
319    );
320    let mut sorted: Vec<&SeoPage> = pages.iter().collect();
321    sorted.sort_by(|a, b| a.route.cmp(&b.route));
322    for page in sorted {
323        let lastmod = page
324            .date
325            .as_ref()
326            .map(|d| format!("<lastmod>{d}</lastmod>"))
327            .unwrap_or_default();
328        out.push_str(&format!(
329            "<url><loc>{}/{}</loc>{lastmod}</url>\n",
330            config.base_url, page.route
331        ));
332    }
333    out.push_str("</urlset>\n");
334    out
335}
336
337/// `robots.txt` with the AI-crawler policy as a recorded decision.
338#[must_use]
339pub fn robots_txt(config: &SiteConfig) -> String {
340    let policy = config.ai_crawlers.as_str();
341    let mut out =
342        format!("# AI-crawler policy: {policy} (recorded decision; site.toml: ai_crawlers)\n");
343    match policy {
344        "block-all" => {
345            out.push_str("User-agent: *\nDisallow: /\n");
346        }
347        "block-training" => {
348            for bot in ["GPTBot", "CCBot", "anthropic-ai"] {
349                out.push_str(&format!("User-agent: {bot}\nDisallow: /\n"));
350            }
351            out.push_str("User-agent: *\nAllow: /\n");
352        }
353        _ => {
354            out.push_str("User-agent: *\nAllow: /\n");
355        }
356    }
357    out.push_str(&format!("Sitemap: {}/sitemap.xml\n", config.base_url));
358    out
359}