1use std::path::Path;
16
17use crate::directives::html_escape;
18
19#[derive(Debug, Clone, PartialEq)]
21pub struct SeoPage {
22 pub route: String,
24 pub title: String,
26 pub description: String,
28 pub date: Option<String>,
30}
31
32#[derive(Debug, Clone, PartialEq)]
34pub struct SiteConfig {
35 pub base_url: String,
38 pub site_title: String,
40 pub author: String,
42 pub ai_crawlers: String,
45 pub stylesheet: Option<String>,
48 pub island_shim: Option<String>,
51}
52
53impl SiteConfig {
54 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#[derive(Debug, Clone, Default, PartialEq)]
98pub struct PageMeta {
99 pub title: Option<String>,
101 pub description: Option<String>,
103 pub slug: Option<String>,
105 pub date: Option<String>,
107}
108
109#[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 let after = &rest[close + 4..];
137 (meta, after.trim_start_matches('\n').to_string())
138}
139
140#[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#[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
190fn escape_attr(text: &str) -> String {
193 html_escape(text).replace('"', """)
194}
195
196#[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 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#[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#[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#[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}