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