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    /// The search island chunk URL, emitted as a search trigger in the
52    /// header (props point at `/search.json`).
53    pub search_island: Option<String>,
54    /// URL path prefix for all site-relative links (subpath hosting,
55    /// e.g. `/solid-fx/preview`). Empty string = served at root.
56    pub base_path: String,
57    /// Open Graph image URL, emitted as `og:image` + `twitter:image`.
58    pub og_image: Option<String>,
59}
60
61impl SiteConfig {
62    /// Parse `site.toml` if present: `key = "value"` scalar lines only.
63    /// `base_url` is the one required key; the rest have defaults.
64    pub fn load(src: &Path) -> Option<SiteConfig> {
65        let text = std::fs::read_to_string(src.join("site.toml")).ok()?;
66        let mut base_url = None;
67        let mut site_title = String::from("Documentation");
68        let mut author = String::new();
69        let mut ai_crawlers = String::from("allow");
70        let mut stylesheet = None;
71        let mut island_shim = None;
72        let mut search_island = None;
73        let mut base_path = String::new();
74        let mut og_image = None;
75        for line in text.lines() {
76            let line = line.trim();
77            if line.is_empty() || line.starts_with('#') {
78                continue;
79            }
80            let Some((key, value)) = line.split_once('=') else {
81                continue;
82            };
83            let value = value.trim().trim_matches('"').to_string();
84            match key.trim() {
85                "base_url" => base_url = Some(value.trim_end_matches('/').to_string()),
86                "site_title" => site_title = value,
87                "author" => author = value,
88                "ai_crawlers" => ai_crawlers = value,
89                "stylesheet" => stylesheet = Some(value),
90                "island_shim" => island_shim = Some(value),
91                "search_island" => search_island = Some(value),
92                "base_path" => base_path = value.trim_end_matches('/').to_string(),
93                "og_image" => og_image = Some(value),
94                _ => {}
95            }
96        }
97        Some(SiteConfig {
98            base_url: base_url.map(|u| u.trim_end_matches('/').to_string())?,
99            site_title,
100            author,
101            ai_crawlers,
102            stylesheet,
103            island_shim,
104            search_island,
105            base_path,
106            og_image,
107        })
108    }
109}
110
111/// Per-page metadata, from the page's front-matter (`---` fenced
112/// `key: value` scalars). `title` falls back to the first `<h1>`, then
113/// the file stem; `description` falls back to the first paragraph.
114#[derive(Debug, Clone, Default, PartialEq)]
115pub struct PageMeta {
116    /// Page title.
117    pub title: Option<String>,
118    /// Meta description.
119    pub description: Option<String>,
120    /// Output file stem override (route becomes `<slug>.html`).
121    pub slug: Option<String>,
122    /// Publication date (ISO `YYYY-MM-DD`; sitemap lastmod + JSON-LD).
123    pub date: Option<String>,
124}
125
126/// Split a leading `---` front-matter block off a document: returns the
127/// parsed metadata and the remainder to compile.
128#[must_use]
129pub fn split_front_matter(markdown: &str) -> (PageMeta, String) {
130    let mut meta = PageMeta::default();
131    let Some(rest) = markdown.strip_prefix("---\n") else {
132        return (meta, markdown.to_string());
133    };
134    let Some(close) = rest.find("\n---") else {
135        return (meta, markdown.to_string());
136    };
137    let block = &rest[..close];
138    for line in block.lines() {
139        let Some((key, value)) = line.split_once(':') else {
140            continue;
141        };
142        let value = value.trim().to_string();
143        match key.trim() {
144            "title" => meta.title = Some(value),
145            "description" => meta.description = Some(value),
146            "slug" => meta.slug = Some(value),
147            "date" => meta.date = Some(value),
148            _ => {}
149        }
150    }
151    // Skip the closing fence line and any following blank lines
152    // (markdown leading whitespace is insignificant).
153    let after = &rest[close + 4..];
154    (meta, after.trim_start_matches('\n').to_string())
155}
156
157/// Derive a page title from the rendered body: the first `<h1>` text.
158#[must_use]
159pub fn first_h1(body: &str) -> Option<String> {
160    // Matches both `<h1>` and `<h1 id="...">` (anchored headings, 0.3.0+).
161    let tag_pos = body.find("<h1")?;
162    let gt = body[tag_pos..].find('>')? + tag_pos + 1;
163    let end = body[gt..].find("</h1>")? + gt;
164    let text = strip_tags(&body[gt..end]);
165    if text.is_empty() {
166        None
167    } else {
168        Some(text)
169    }
170}
171
172/// Derive a description from the rendered body: the first paragraph's
173/// text, tags stripped, truncated at a word boundary to 155 chars.
174#[must_use]
175pub fn first_paragraph(body: &str) -> Option<String> {
176    let start = body.find("<p>")? + 3;
177    let end = body[start..].find("</p>")? + start;
178    let text = strip_tags(&body[start..end]);
179    if text.is_empty() {
180        return None;
181    }
182    Some(truncate_words(&text, 155))
183}
184
185/// Strip all tags from rendered HTML and collapse whitespace: the
186/// plain-text view used for search corpora.
187#[must_use]
188pub fn plain_text(body: &str) -> String {
189    let text = strip_tags(body);
190    text.split_whitespace().collect::<Vec<_>>().join(" ")
191}
192
193fn strip_tags(html: &str) -> String {
194    let mut out = String::with_capacity(html.len());
195    let mut in_tag = false;
196    for c in html.chars() {
197        match c {
198            '<' => in_tag = true,
199            '>' => in_tag = false,
200            c if !in_tag => out.push(c),
201            _ => {}
202        }
203    }
204    out.trim().to_string()
205}
206
207fn truncate_words(text: &str, max: usize) -> String {
208    if text.len() <= max {
209        return text.to_string();
210    }
211    match text[..max].rfind(' ') {
212        Some(pos) => format!("{}...", &text[..pos]),
213        None => format!("{}...", &text[..max]),
214    }
215}
216
217/// Attribute-safe escaping: text escaping plus double quotes (SEO head
218/// values live inside `content="..."` attributes).
219fn escape_attr(text: &str) -> String {
220    html_escape(text).replace('"', "&quot;")
221}
222
223/// The full-document wrapper: doctype, head (charset, viewport, title,
224/// description, canonical, Open Graph, Twitter card, JSON-LD), body.
225/// `route` is the page's site-relative HTML path (`index.html`,
226/// `guides/x.html`). Length guidance (title <=60, description <=155)
227/// surfaces as warnings in the report, not build failures.
228#[must_use]
229pub fn document(
230    body: &str,
231    meta: &PageMeta,
232    title: &str,
233    description: &str,
234    route: &str,
235    config: Option<&SiteConfig>,
236    breadcrumbs: &[(String, Option<String>)],
237) -> String {
238    let canonical = config
239        .map(|c| format!("{}/{}", c.base_url, route))
240        .unwrap_or_default();
241    let canonical_tags = if canonical.is_empty() {
242        String::new()
243    } else {
244        format!(
245            "<link rel=\"canonical\" href=\"{u}\"><meta property=\"og:url\" content=\"{u}\">",
246            u = escape_attr(&canonical)
247        )
248    };
249    let json_ld_tag = config
250        .map(|c| {
251            let mut article = serde_json::json!({
252                "@context": "https://schema.org",
253                "@type": "TechArticle",
254                "headline": title,
255                "description": description,
256                "isPartOf": { "@type": "WebSite", "name": c.site_title, "url": c.base_url },
257            });
258            if let Some(obj) = article.as_object_mut() {
259                if !canonical.is_empty() {
260                    obj.insert("url".into(), serde_json::json!(canonical));
261                }
262                if !c.author.is_empty() {
263                    obj.insert(
264                        "author".into(),
265                        serde_json::json!({ "@type": "Person", "name": c.author }),
266                    );
267                }
268                if let Some(date) = &meta.date {
269                    obj.insert("datePublished".into(), serde_json::json!(date));
270                }
271            }
272            format!("<script type=\"application/ld+json\">{article}</script>")
273        })
274        .unwrap_or_default();
275    let site_name_tag = config
276        .map(|c| {
277            format!(
278                "<meta property=\"og:site_name\" content=\"{}\">",
279                escape_attr(&c.site_title)
280            )
281        })
282        .unwrap_or_default();
283    let og_image_tag = config
284        .and_then(|c| c.og_image.clone())
285        .map(|img| {
286            format!(
287                "<meta property=\"og:image\" content=\"{i}\"><meta name=\"twitter:image\" content=\"{i}\">",
288                i = escape_attr(&img)
289            )
290        })
291        .unwrap_or_default();
292    let feed_link = config
293        .map(|c| {
294            format!(
295                "<link rel=\"alternate\" type=\"application/atom+xml\" href=\"{u}/atom.xml\">",
296                u = c.base_url
297            )
298        })
299        .unwrap_or_default();
300    let breadcrumb_markup = if breadcrumbs.is_empty() {
301        String::new()
302    } else {
303        let mut parts: Vec<String> = vec!["<a href=\"/\">Home</a>".into()];
304        for (label, href) in breadcrumbs {
305            parts.push(match href {
306                Some(h) => format!("<a href=\"{}\">{}</a>", escape_attr(h), html_escape(label)),
307                None => html_escape(label),
308            });
309        }
310        format!(
311            "<nav class=\"breadcrumbs\">{}</nav>",
312            parts.join(" <span class=\"crumb-sep\">/</span> ")
313        )
314    };
315    // Site-level head wiring (Wave 2c.5): the islands' stylesheet and
316    // the shim module that registers <docs-island>.
317    let head_extra = config
318        .map(|c| {
319            let mut extra = String::new();
320            if let Some(css) = &c.stylesheet {
321                extra.push_str(&format!(
322                    "<link rel=\"stylesheet\" href=\"{}\">",
323                    escape_attr(css)
324                ));
325            }
326            if let Some(shim) = &c.island_shim {
327                extra.push_str(&format!(
328                    "<script type=\"module\" src=\"{}\"></script>",
329                    escape_attr(shim)
330                ));
331            }
332            extra
333        })
334        .unwrap_or_default();
335    format!(
336        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
337<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
338<title>{t}</title>\
339<meta name=\"description\" content=\"{d}\">{canonical_tags}\
340<meta property=\"og:type\" content=\"article\">\
341<meta property=\"og:title\" content=\"{t}\">\
342<meta property=\"og:description\" content=\"{d}\">{site_name_tag}\
343<meta name=\"twitter:card\" content=\"summary\">\
344<meta name=\"twitter:title\" content=\"{t}\">\
345<meta name=\"twitter:description\" content=\"{d}\">\
346{head_extra}{og_image_tag}{feed_link}{json_ld_tag}</head><body>{breadcrumb_markup}{body}</body></html>",
347        t = escape_attr(title),
348        d = escape_attr(description),
349        breadcrumb_markup = breadcrumb_markup
350    )
351}
352
353/// `llms.txt` (GEO floor): the site heading plus one curated link per
354/// page with its description.
355#[must_use]
356pub fn llms_txt(config: &SiteConfig, pages: &[SeoPage]) -> String {
357    let mut out = format!("# {}\n\n", config.site_title);
358    if !config.author.is_empty() {
359        out.push_str(&format!("By {}.\n\n", config.author));
360    }
361    for page in pages {
362        out.push_str(&format!(
363            "- [{t}]({u}/{r}): {d}\n",
364            t = page.title,
365            u = config.base_url,
366            r = page.route,
367            d = page.description
368        ));
369    }
370    out
371}
372
373/// `sitemap.xml`: one `<url>` per page, sorted by route; `lastmod` only
374/// when the page declares a date (deterministic builds do not lie about
375/// modification times).
376#[must_use]
377pub fn sitemap_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
378    let mut out = String::from(
379        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n",
380    );
381    let mut sorted: Vec<&SeoPage> = pages.iter().collect();
382    sorted.sort_by(|a, b| a.route.cmp(&b.route));
383    for page in sorted {
384        let lastmod = page
385            .date
386            .as_ref()
387            .map(|d| format!("<lastmod>{d}</lastmod>"))
388            .unwrap_or_default();
389        out.push_str(&format!(
390            "<url><loc>{}/{}</loc>{lastmod}</url>\n",
391            config.base_url, page.route
392        ));
393    }
394    out.push_str("</urlset>\n");
395    out
396}
397
398/// `robots.txt` with the AI-crawler policy as a recorded decision.
399#[must_use]
400pub fn robots_txt(config: &SiteConfig) -> String {
401    let policy = config.ai_crawlers.as_str();
402    let mut out =
403        format!("# AI-crawler policy: {policy} (recorded decision; site.toml: ai_crawlers)\n");
404    match policy {
405        "block-all" => {
406            out.push_str("User-agent: *\nDisallow: /\n");
407        }
408        "block-training" => {
409            for bot in ["GPTBot", "CCBot", "anthropic-ai"] {
410                out.push_str(&format!("User-agent: {bot}\nDisallow: /\n"));
411            }
412            out.push_str("User-agent: *\nAllow: /\n");
413        }
414        _ => {
415            out.push_str("User-agent: *\nAllow: /\n");
416        }
417    }
418    out.push_str(&format!("Sitemap: {}/sitemap.xml\n", config.base_url));
419    out
420}
421
422/// `atom.xml`: one entry per dated page, newest first. Pages without a
423/// front-matter date stay out of the feed (deterministic builds do not
424/// invent timestamps).
425#[must_use]
426pub fn atom_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
427    let mut dated: Vec<&SeoPage> = pages.iter().filter(|p| p.date.is_some()).collect();
428    dated.sort_by(|a, b| b.date.as_deref().cmp(&a.date.as_deref()));
429    let mut out = String::from(
430        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\n",
431    );
432    out.push_str(&format!(
433        "<title>{}</title>\n",
434        html_escape(&config.site_title)
435    ));
436    if !config.author.is_empty() {
437        out.push_str(&format!(
438            "<author><name>{}</name></author>\n",
439            html_escape(&config.author)
440        ));
441    }
442    let self_url = format!("{}/atom.xml", config.base_url);
443    out.push_str(&format!(
444        "<link rel=\"self\" href=\"{}\"/>\n<link rel=\"alternate\" href=\"{}\"/>\n<id>{}/</id>\n",
445        html_escape(&self_url),
446        config.base_url,
447        config.base_url,
448    ));
449    if let Some(newest) = dated.first() {
450        if let Some(date) = &newest.date {
451            out.push_str(&format!("<updated>{date}T00:00:00Z</updated>\n"));
452        }
453    }
454    for page in dated {
455        let url = format!("{}/{}", config.base_url, page.route);
456        out.push_str(&format!(
457            "<entry><title>{t}</title><link rel=\"alternate\" href=\"{u}\"/><id>{u}</id><published>{d}</published><summary>{s}</summary></entry>\n",
458            t = html_escape(&page.title),
459            u = html_escape(&url),
460            d = page.date.as_deref().unwrap_or(""),
461            s = html_escape(&page.description),
462        ));
463    }
464    out.push_str("</feed>\n");
465    out
466}