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