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}
55
56impl SiteConfig {
57 pub fn load(src: &Path) -> Option<SiteConfig> {
60 let text = std::fs::read_to_string(src.join("site.toml")).ok()?;
61 let mut base_url = None;
62 let mut site_title = String::from("Documentation");
63 let mut author = String::new();
64 let mut ai_crawlers = String::from("allow");
65 let mut stylesheet = None;
66 let mut island_shim = None;
67 let mut search_island = None;
68 for line in text.lines() {
69 let line = line.trim();
70 if line.is_empty() || line.starts_with('#') {
71 continue;
72 }
73 let Some((key, value)) = line.split_once('=') else {
74 continue;
75 };
76 let value = value.trim().trim_matches('"').to_string();
77 match key.trim() {
78 "base_url" => base_url = Some(value.trim_end_matches('/').to_string()),
79 "site_title" => site_title = value,
80 "author" => author = value,
81 "ai_crawlers" => ai_crawlers = value,
82 "stylesheet" => stylesheet = Some(value),
83 "island_shim" => island_shim = Some(value),
84 "search_island" => search_island = Some(value),
85 _ => {}
86 }
87 }
88 Some(SiteConfig {
89 base_url: base_url.map(|u| u.trim_end_matches('/').to_string())?,
90 site_title,
91 author,
92 ai_crawlers,
93 stylesheet,
94 island_shim,
95 search_island,
96 })
97 }
98}
99
100#[derive(Debug, Clone, Default, PartialEq)]
104pub struct PageMeta {
105 pub title: Option<String>,
107 pub description: Option<String>,
109 pub slug: Option<String>,
111 pub date: Option<String>,
113}
114
115#[must_use]
118pub fn split_front_matter(markdown: &str) -> (PageMeta, String) {
119 let mut meta = PageMeta::default();
120 let Some(rest) = markdown.strip_prefix("---\n") else {
121 return (meta, markdown.to_string());
122 };
123 let Some(close) = rest.find("\n---") else {
124 return (meta, markdown.to_string());
125 };
126 let block = &rest[..close];
127 for line in block.lines() {
128 let Some((key, value)) = line.split_once(':') else {
129 continue;
130 };
131 let value = value.trim().to_string();
132 match key.trim() {
133 "title" => meta.title = Some(value),
134 "description" => meta.description = Some(value),
135 "slug" => meta.slug = Some(value),
136 "date" => meta.date = Some(value),
137 _ => {}
138 }
139 }
140 let after = &rest[close + 4..];
143 (meta, after.trim_start_matches('\n').to_string())
144}
145
146#[must_use]
148pub fn first_h1(body: &str) -> Option<String> {
149 let start = body.find("<h1>")? + 4;
150 let end = body[start..].find("</h1>")? + start;
151 let text = strip_tags(&body[start..end]);
152 if text.is_empty() {
153 None
154 } else {
155 Some(text)
156 }
157}
158
159#[must_use]
162pub fn first_paragraph(body: &str) -> Option<String> {
163 let start = body.find("<p>")? + 3;
164 let end = body[start..].find("</p>")? + start;
165 let text = strip_tags(&body[start..end]);
166 if text.is_empty() {
167 return None;
168 }
169 Some(truncate_words(&text, 155))
170}
171
172#[must_use]
175pub fn plain_text(body: &str) -> String {
176 let text = strip_tags(body);
177 text.split_whitespace().collect::<Vec<_>>().join(" ")
178}
179
180fn strip_tags(html: &str) -> String {
181 let mut out = String::with_capacity(html.len());
182 let mut in_tag = false;
183 for c in html.chars() {
184 match c {
185 '<' => in_tag = true,
186 '>' => in_tag = false,
187 c if !in_tag => out.push(c),
188 _ => {}
189 }
190 }
191 out.trim().to_string()
192}
193
194fn truncate_words(text: &str, max: usize) -> String {
195 if text.len() <= max {
196 return text.to_string();
197 }
198 match text[..max].rfind(' ') {
199 Some(pos) => format!("{}...", &text[..pos]),
200 None => format!("{}...", &text[..max]),
201 }
202}
203
204fn escape_attr(text: &str) -> String {
207 html_escape(text).replace('"', """)
208}
209
210#[must_use]
216pub fn document(
217 body: &str,
218 meta: &PageMeta,
219 title: &str,
220 description: &str,
221 route: &str,
222 config: Option<&SiteConfig>,
223) -> String {
224 let canonical = config
225 .map(|c| format!("{}/{}", c.base_url, route))
226 .unwrap_or_default();
227 let canonical_tags = if canonical.is_empty() {
228 String::new()
229 } else {
230 format!(
231 "<link rel=\"canonical\" href=\"{u}\"><meta property=\"og:url\" content=\"{u}\">",
232 u = escape_attr(&canonical)
233 )
234 };
235 let json_ld_tag = config
236 .map(|c| {
237 let mut article = serde_json::json!({
238 "@context": "https://schema.org",
239 "@type": "TechArticle",
240 "headline": title,
241 "description": description,
242 "isPartOf": { "@type": "WebSite", "name": c.site_title, "url": c.base_url },
243 });
244 if let Some(obj) = article.as_object_mut() {
245 if !canonical.is_empty() {
246 obj.insert("url".into(), serde_json::json!(canonical));
247 }
248 if !c.author.is_empty() {
249 obj.insert(
250 "author".into(),
251 serde_json::json!({ "@type": "Person", "name": c.author }),
252 );
253 }
254 if let Some(date) = &meta.date {
255 obj.insert("datePublished".into(), serde_json::json!(date));
256 }
257 }
258 format!("<script type=\"application/ld+json\">{article}</script>")
259 })
260 .unwrap_or_default();
261 let site_name_tag = config
262 .map(|c| {
263 format!(
264 "<meta property=\"og:site_name\" content=\"{}\">",
265 escape_attr(&c.site_title)
266 )
267 })
268 .unwrap_or_default();
269 let head_extra = config
272 .map(|c| {
273 let mut extra = String::new();
274 if let Some(css) = &c.stylesheet {
275 extra.push_str(&format!(
276 "<link rel=\"stylesheet\" href=\"{}\">",
277 escape_attr(css)
278 ));
279 }
280 if let Some(shim) = &c.island_shim {
281 extra.push_str(&format!(
282 "<script type=\"module\" src=\"{}\"></script>",
283 escape_attr(shim)
284 ));
285 }
286 extra
287 })
288 .unwrap_or_default();
289 format!(
290 "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
291<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
292<title>{t}</title>\
293<meta name=\"description\" content=\"{d}\">{canonical_tags}\
294<meta property=\"og:type\" content=\"article\">\
295<meta property=\"og:title\" content=\"{t}\">\
296<meta property=\"og:description\" content=\"{d}\">{site_name_tag}\
297<meta name=\"twitter:card\" content=\"summary\">\
298<meta name=\"twitter:title\" content=\"{t}\">\
299<meta name=\"twitter:description\" content=\"{d}\">\
300{head_extra}{json_ld_tag}</head><body>{body}</body></html>",
301 t = escape_attr(title),
302 d = escape_attr(description)
303 )
304}
305
306#[must_use]
309pub fn llms_txt(config: &SiteConfig, pages: &[SeoPage]) -> String {
310 let mut out = format!("# {}\n\n", config.site_title);
311 if !config.author.is_empty() {
312 out.push_str(&format!("By {}.\n\n", config.author));
313 }
314 for page in pages {
315 out.push_str(&format!(
316 "- [{t}]({u}/{r}): {d}\n",
317 t = page.title,
318 u = config.base_url,
319 r = page.route,
320 d = page.description
321 ));
322 }
323 out
324}
325
326#[must_use]
330pub fn sitemap_xml(config: &SiteConfig, pages: &[SeoPage]) -> String {
331 let mut out = String::from(
332 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n",
333 );
334 let mut sorted: Vec<&SeoPage> = pages.iter().collect();
335 sorted.sort_by(|a, b| a.route.cmp(&b.route));
336 for page in sorted {
337 let lastmod = page
338 .date
339 .as_ref()
340 .map(|d| format!("<lastmod>{d}</lastmod>"))
341 .unwrap_or_default();
342 out.push_str(&format!(
343 "<url><loc>{}/{}</loc>{lastmod}</url>\n",
344 config.base_url, page.route
345 ));
346 }
347 out.push_str("</urlset>\n");
348 out
349}
350
351#[must_use]
353pub fn robots_txt(config: &SiteConfig) -> String {
354 let policy = config.ai_crawlers.as_str();
355 let mut out =
356 format!("# AI-crawler policy: {policy} (recorded decision; site.toml: ai_crawlers)\n");
357 match policy {
358 "block-all" => {
359 out.push_str("User-agent: *\nDisallow: /\n");
360 }
361 "block-training" => {
362 for bot in ["GPTBot", "CCBot", "anthropic-ai"] {
363 out.push_str(&format!("User-agent: {bot}\nDisallow: /\n"));
364 }
365 out.push_str("User-agent: *\nAllow: /\n");
366 }
367 _ => {
368 out.push_str("User-agent: *\nAllow: /\n");
369 }
370 }
371 out.push_str(&format!("Sitemap: {}/sitemap.xml\n", config.base_url));
372 out
373}