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
193/// Prefix a site-relative URL with the configured base path. Values
194/// starting with a scheme (https://, http://) pass through verbatim
195/// (external URLs, CDN assets).
196fn site_url(base_path: &str, value: &str) -> String {
197    if value.starts_with("https://") || value.starts_with("http://") || base_path.is_empty() {
198        value.to_string()
199    } else if value.starts_with('/') {
200        format!("{base_path}{value}")
201    } else {
202        format!("{base_path}/{value}")
203    }
204}
205
206fn strip_tags(html: &str) -> String {
207    let mut out = String::with_capacity(html.len());
208    let mut in_tag = false;
209    for c in html.chars() {
210        match c {
211            '<' => in_tag = true,
212            '>' => in_tag = false,
213            c if !in_tag => out.push(c),
214            _ => {}
215        }
216    }
217    out.trim().to_string()
218}
219
220fn truncate_words(text: &str, max: usize) -> String {
221    if text.len() <= max {
222        return text.to_string();
223    }
224    match text[..max].rfind(' ') {
225        Some(pos) => format!("{}...", &text[..pos]),
226        None => format!("{}...", &text[..max]),
227    }
228}
229
230/// Attribute-safe escaping: text escaping plus double quotes (SEO head
231/// values live inside `content="..."` attributes).
232fn escape_attr(text: &str) -> String {
233    html_escape(text).replace('"', "&quot;")
234}
235
236/// The full-document wrapper: doctype, head (charset, viewport, title,
237/// description, canonical, Open Graph, Twitter card, JSON-LD), body.
238/// `route` is the page's site-relative HTML path (`index.html`,
239/// `guides/x.html`). Length guidance (title <=60, description <=155)
240/// surfaces as warnings in the report, not build failures.
241#[must_use]
242pub fn document(
243    body: &str,
244    meta: &PageMeta,
245    title: &str,
246    description: &str,
247    route: &str,
248    config: Option<&SiteConfig>,
249    breadcrumbs: &[(String, Option<String>)],
250) -> String {
251    let canonical = config
252        .map(|c| format!("{}/{}", c.base_url, route))
253        .unwrap_or_default();
254    let canonical_tags = if canonical.is_empty() {
255        String::new()
256    } else {
257        format!(
258            "<link rel=\"canonical\" href=\"{u}\"><meta property=\"og:url\" content=\"{u}\">",
259            u = escape_attr(&canonical)
260        )
261    };
262    let json_ld_tag = config
263        .map(|c| {
264            let mut article = serde_json::json!({
265                "@context": "https://schema.org",
266                "@type": "TechArticle",
267                "headline": title,
268                "description": description,
269                "isPartOf": { "@type": "WebSite", "name": c.site_title, "url": c.base_url },
270            });
271            if let Some(obj) = article.as_object_mut() {
272                if !canonical.is_empty() {
273                    obj.insert("url".into(), serde_json::json!(canonical));
274                }
275                if !c.author.is_empty() {
276                    obj.insert(
277                        "author".into(),
278                        serde_json::json!({ "@type": "Person", "name": c.author }),
279                    );
280                }
281                if let Some(date) = &meta.date {
282                    obj.insert("datePublished".into(), serde_json::json!(date));
283                }
284            }
285            format!("<script type=\"application/ld+json\">{article}</script>")
286        })
287        .unwrap_or_default();
288    let site_name_tag = config
289        .map(|c| {
290            format!(
291                "<meta property=\"og:site_name\" content=\"{}\">",
292                escape_attr(&c.site_title)
293            )
294        })
295        .unwrap_or_default();
296    let og_image_tag = config
297        .and_then(|c| c.og_image.clone())
298        .map(|img| {
299            format!(
300                "<meta property=\"og:image\" content=\"{i}\"><meta name=\"twitter:image\" content=\"{i}\">",
301                i = escape_attr(&img)
302            )
303        })
304        .unwrap_or_default();
305    let _ = &og_image_tag;
306    let feed_link = config
307        .map(|c| {
308            format!(
309                "<link rel=\"alternate\" type=\"application/atom+xml\" href=\"{u}/atom.xml\">",
310                u = c.base_url
311            )
312        })
313        .unwrap_or_default();
314    let breadcrumb_markup = if breadcrumbs.is_empty() {
315        String::new()
316    } else {
317        let mut parts: Vec<String> = vec!["<a href=\"/\">Home</a>".into()];
318        for (label, href) in breadcrumbs {
319            parts.push(match href {
320                Some(h) => format!("<a href=\"{}\">{}</a>", escape_attr(h), html_escape(label)),
321                None => html_escape(label),
322            });
323        }
324        format!(
325            "<nav class=\"breadcrumbs\">{}</nav>",
326            parts.join(" <span class=\"crumb-sep\">/</span> ")
327        )
328    };
329    // Site-level head wiring (Wave 2c.5): the islands' stylesheet and
330    // the shim module that registers <docs-island>.
331    let head_extra = config
332        .map(|c| {
333            let mut extra = String::new();
334            if let Some(css) = &c.stylesheet {
335                extra.push_str(&format!(
336                    "<link rel=\"stylesheet\" href=\"{}\">",
337                    escape_attr(&site_url(&c.base_path, css))
338                ));
339            }
340            if let Some(shim) = &c.island_shim {
341                extra.push_str(&format!(
342                    "<script type=\"module\" src=\"{}\"></script>",
343                    escape_attr(&site_url(&c.base_path, shim))
344                ));
345            }
346            extra
347        })
348        .unwrap_or_default();
349    format!(
350        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
351<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
352<title>{t}</title>\
353<meta name=\"description\" content=\"{d}\">{canonical_tags}\
354<meta property=\"og:type\" content=\"article\">\
355<meta property=\"og:title\" content=\"{t}\">\
356<meta property=\"og:description\" content=\"{d}\">{site_name_tag}\
357<meta name=\"twitter:card\" content=\"summary\">\
358<meta name=\"twitter:title\" content=\"{t}\">\
359<meta name=\"twitter:description\" content=\"{d}\">\
360{head_extra}{og_image_tag}{feed_link}{json_ld_tag}</head><body>{breadcrumb_markup}{body}</body></html>",
361        t = escape_attr(title),
362        d = escape_attr(description),
363        breadcrumb_markup = breadcrumb_markup
364    )
365}
366
367/// `llms.txt` (GEO floor): the site heading plus one curated link per
368/// page with its description.
369#[must_use]
370pub fn llms_txt(config: &SiteConfig, pages: &[SeoPage]) -> String {
371    let mut out = format!("# {}\n\n", config.site_title);
372    if !config.author.is_empty() {
373        out.push_str(&format!("By {}.\n\n", config.author));
374    }
375    for page in pages {
376        out.push_str(&format!(
377            "- [{t}]({u}/{r}): {d}\n",
378            t = page.title,
379            u = config.base_url,
380            r = page.route,
381            d = page.description
382        ));
383    }
384    out
385}
386
387/// `sitemap.xml`: one `<url>` per page, sorted by route; `lastmod` only
388/// when the page declares a date (deterministic builds do not lie about
389/// modification times).
390#[must_use]
391pub fn sitemap_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
392    let mut out = String::from(
393        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n",
394    );
395    let mut sorted: Vec<&SeoPage> = pages.iter().collect();
396    sorted.sort_by(|a, b| a.route.cmp(&b.route));
397    for page in sorted {
398        let lastmod = page
399            .date
400            .as_ref()
401            .map(|d| format!("<lastmod>{d}</lastmod>"))
402            .unwrap_or_default();
403        out.push_str(&format!(
404            "<url><loc>{}/{}</loc>{lastmod}</url>\n",
405            config.base_url, page.route
406        ));
407    }
408    out.push_str("</urlset>\n");
409    out
410}
411
412/// `robots.txt` with the AI-crawler policy as a recorded decision.
413#[must_use]
414pub fn robots_txt(config: &SiteConfig) -> String {
415    let policy = config.ai_crawlers.as_str();
416    let mut out =
417        format!("# AI-crawler policy: {policy} (recorded decision; site.toml: ai_crawlers)\n");
418    match policy {
419        "block-all" => {
420            out.push_str("User-agent: *\nDisallow: /\n");
421        }
422        "block-training" => {
423            for bot in ["GPTBot", "CCBot", "anthropic-ai"] {
424                out.push_str(&format!("User-agent: {bot}\nDisallow: /\n"));
425            }
426            out.push_str("User-agent: *\nAllow: /\n");
427        }
428        _ => {
429            out.push_str("User-agent: *\nAllow: /\n");
430        }
431    }
432    out.push_str(&format!("Sitemap: {}/sitemap.xml\n", config.base_url));
433    out
434}
435
436/// `atom.xml`: one entry per dated page, newest first. Pages without a
437/// front-matter date stay out of the feed (deterministic builds do not
438/// invent timestamps).
439#[must_use]
440pub fn atom_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
441    let mut dated: Vec<&SeoPage> = pages.iter().filter(|p| p.date.is_some()).collect();
442    dated.sort_by(|a, b| b.date.as_deref().cmp(&a.date.as_deref()));
443    let mut out = String::from(
444        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\">\n",
445    );
446    out.push_str(&format!(
447        "<title>{}</title>\n",
448        html_escape(&config.site_title)
449    ));
450    if !config.author.is_empty() {
451        out.push_str(&format!(
452            "<author><name>{}</name></author>\n",
453            html_escape(&config.author)
454        ));
455    }
456    let self_url = format!("{}/atom.xml", config.base_url);
457    out.push_str(&format!(
458        "<link rel=\"self\" href=\"{}\"/>\n<link rel=\"alternate\" href=\"{}\"/>\n<id>{}/</id>\n",
459        html_escape(&self_url),
460        config.base_url,
461        config.base_url,
462    ));
463    if let Some(newest) = dated.first() {
464        if let Some(date) = &newest.date {
465            out.push_str(&format!("<updated>{date}T00:00:00Z</updated>\n"));
466        }
467    }
468    for page in dated {
469        let url = format!("{}/{}", config.base_url, page.route);
470        out.push_str(&format!(
471            "<entry><title>{t}</title><link rel=\"alternate\" href=\"{u}\"/><id>{u}</id><published>{d}</published><summary>{s}</summary></entry>\n",
472            t = html_escape(&page.title),
473            u = html_escape(&url),
474            d = page.date.as_deref().unwrap_or(""),
475            s = html_escape(&page.description),
476        ));
477    }
478    out.push_str("</feed>\n");
479    out
480}