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 pub search_island: Option<String>,
54 pub base_path: String,
57 pub og_image: Option<String>,
59}
60
61impl SiteConfig {
62 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#[derive(Debug, Clone, Default, PartialEq)]
115pub struct PageMeta {
116 pub title: Option<String>,
118 pub description: Option<String>,
120 pub slug: Option<String>,
122 pub date: Option<String>,
124}
125
126#[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 let after = &rest[close + 4..];
154 (meta, after.trim_start_matches('\n').to_string())
155}
156
157#[must_use]
159pub fn first_h1(body: &str) -> Option<String> {
160 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#[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#[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 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
230fn escape_attr(text: &str) -> String {
233 html_escape(text).replace('"', """)
234}
235
236#[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 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#[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#[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#[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#[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}