aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / crates / site-builder / src / oracle.rs
| 1 | //! Guards that run in `verify` mode on any generated tree, whatever built it. |
| 2 | //! |
| 3 | //! Before the Omega site generator, several gates ran only inside `build`: |
| 4 | //! the dist/registry comparison, the head checks and the validation of each |
| 5 | //! published data file. A tree built by another generator never met them. |
| 6 | //! This module holds those gates as pure checks over the files in dist, so |
| 7 | //! `site-builder verify DIR` is a complete, independent oracle. |
| 8 | //! |
| 9 | //! Independence: every expected value here comes from Rust constants and |
| 10 | //! Rust parsers ([`seo::PAGES`], [`seo::DATA_FILES`], the component |
| 11 | //! validators). Nothing is read from the generator's own registry |
| 12 | //! (`om/site/pages.json` is not an input), so a page the generator adds or |
| 13 | //! drops on its own is caught rather than trusted. |
| 14 | |
| 15 | use std::collections::BTreeSet; |
| 16 | use std::fs; |
| 17 | use std::path::Path; |
| 18 | use std::sync::LazyLock; |
| 19 | |
| 20 | use regex::Regex; |
| 21 | use serde_json::Value; |
| 22 | |
| 23 | use crate::seo::{self, attr, tag_name, DATA_FILES, HOST, PAGES}; |
| 24 | |
| 25 | /// The first opening tag at or after `from` whose class attribute holds |
| 26 | /// `token` as a whole word: (tag start, index just past its `>`, tag name). |
| 27 | pub fn find_class(html: &str, from: usize, token: &str) -> Option<(usize, usize, String)> { |
| 28 | let mut i = from; |
| 29 | while let Some(lt) = html.get(i..)?.find('<') { |
| 30 | let at = i + lt; |
| 31 | let gt = at + html[at..].find('>')?; |
| 32 | let tag = &html[at..=gt]; |
| 33 | if !tag.starts_with("</") && !tag.starts_with("<!") { |
| 34 | if let Some(class) = attr(tag, "class") { |
| 35 | if class.split_ascii_whitespace().any(|c| c == token) { |
| 36 | return Some((at, gt + 1, tag_name(tag))); |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | i = gt + 1; |
| 41 | } |
| 42 | None |
| 43 | } |
| 44 | |
| 45 | /// Index just past the close tag of the element whose opening tag ends at |
| 46 | /// `body`, counting nested elements of the same name. |
| 47 | pub fn element_end(html: &str, body: usize, name: &str) -> Option<usize> { |
| 48 | let lower = html.to_ascii_lowercase(); |
| 49 | let (start, close) = (format!("<{name}"), format!("</{name}>")); |
| 50 | let mut depth = 1usize; |
| 51 | let mut i = body; |
| 52 | while let Some(lt) = lower[i..].find('<') { |
| 53 | let at = i + lt; |
| 54 | let tail = &lower[at..]; |
| 55 | if tail.starts_with(&close) { |
| 56 | depth -= 1; |
| 57 | if depth == 0 { |
| 58 | return Some(at + close.len()); |
| 59 | } |
| 60 | } else if tail.starts_with(&start) && tail[start.len()..].starts_with(['>', ' ', '\t', '\n', '\r', '/']) { |
| 61 | depth += 1; |
| 62 | } |
| 63 | i = at + 1; |
| 64 | } |
| 65 | None |
| 66 | } |
| 67 | |
| 68 | /// Elements that have no close tag. |
| 69 | const VOID: [&str; 13] = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]; |
| 70 | |
| 71 | /// The attribute names of one opening tag, lowercased, skipping quoted |
| 72 | /// values, so `title="hidden"` or `class="visually-hidden"` is no attribute |
| 73 | /// named `hidden`. |
| 74 | pub fn attr_names(tag: &str) -> Vec<String> { |
| 75 | let b = tag.as_bytes(); |
| 76 | let ws = |c: u8| c.is_ascii_whitespace(); |
| 77 | let mut i = 1; |
| 78 | while i < b.len() && !ws(b[i]) && b[i] != b'>' && b[i] != b'/' { |
| 79 | i += 1; |
| 80 | } |
| 81 | let mut out = Vec::new(); |
| 82 | loop { |
| 83 | while i < b.len() && (ws(b[i]) || b[i] == b'/') { |
| 84 | i += 1; |
| 85 | } |
| 86 | if i >= b.len() || b[i] == b'>' { |
| 87 | break; |
| 88 | } |
| 89 | let start = i; |
| 90 | while i < b.len() && !ws(b[i]) && b[i] != b'=' && b[i] != b'>' && b[i] != b'/' { |
| 91 | i += 1; |
| 92 | } |
| 93 | if i > start { |
| 94 | out.push(tag[start..i].to_ascii_lowercase()); |
| 95 | } |
| 96 | while i < b.len() && ws(b[i]) { |
| 97 | i += 1; |
| 98 | } |
| 99 | if i < b.len() && b[i] == b'=' { |
| 100 | i += 1; |
| 101 | while i < b.len() && ws(b[i]) { |
| 102 | i += 1; |
| 103 | } |
| 104 | if i < b.len() && (b[i] == b'"' || b[i] == b'\'') { |
| 105 | let q = b[i]; |
| 106 | i += 1; |
| 107 | while i < b.len() && b[i] != q { |
| 108 | i += 1; |
| 109 | } |
| 110 | i += 1; |
| 111 | } else { |
| 112 | while i < b.len() && !ws(b[i]) && b[i] != b'>' { |
| 113 | i += 1; |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | } |
| 118 | out |
| 119 | } |
| 120 | |
| 121 | /// One pass over `html` that drops comments, the listed elements (through |
| 122 | /// their close) and, when `hidden` is set, every element whose opening tag |
| 123 | /// carries the `hidden` attribute or `aria-hidden="true"`. Anything that |
| 124 | /// never closes is dropped to the end, so malformed markup can only remove |
| 125 | /// content from the checks, never add it. |
| 126 | fn strip(html: &str, drop: &[&str], hidden: bool) -> String { |
| 127 | let mut out = String::with_capacity(html.len()); |
| 128 | let mut i = 0; |
| 129 | while let Some(lt) = html[i..].find('<') { |
| 130 | let at = i + lt; |
| 131 | out.push_str(&html[i..at]); |
| 132 | let rest = &html[at..]; |
| 133 | if rest.starts_with("<!--") { |
| 134 | i = rest.find("-->").map_or(html.len(), |e| at + e + 3); |
| 135 | out.push(' '); |
| 136 | continue; |
| 137 | } |
| 138 | let name = tag_name(rest); |
| 139 | let Some(gt) = rest.find('>').map(|g| at + g) else { |
| 140 | i = html.len(); |
| 141 | break; |
| 142 | }; |
| 143 | let tag = &html[at..=gt]; |
| 144 | let opening = !rest.starts_with("</") && !rest.starts_with("<!") && !name.is_empty(); |
| 145 | let hide = opening |
| 146 | && (drop.contains(&name.as_str()) |
| 147 | || (hidden && (attr_names(tag).iter().any(|a| a == "hidden") || attr(tag, "aria-hidden").as_deref() == Some("true")))); |
| 148 | if hide { |
| 149 | i = if VOID.contains(&name.as_str()) || tag.ends_with("/>") { |
| 150 | gt + 1 |
| 151 | } else { |
| 152 | element_end(html, gt + 1, &name).unwrap_or(html.len()) |
| 153 | }; |
| 154 | out.push(' '); |
| 155 | continue; |
| 156 | } |
| 157 | out.push_str(tag); |
| 158 | i = gt + 1; |
| 159 | } |
| 160 | out.push_str(&html[i.min(html.len())..]); |
| 161 | out |
| 162 | } |
| 163 | |
| 164 | /// The real markup of a page: comments, scripts, styles and templates |
| 165 | /// removed, so an id or link written inside them is not an element. |
| 166 | pub fn markup(html: &str) -> String { |
| 167 | strip(html, &["script", "style", "template"], false) |
| 168 | } |
| 169 | |
| 170 | /// The part of a page a reader reaches with the page as served: the real |
| 171 | /// markup, minus `<noscript>` fallbacks and elements marked `hidden` or |
| 172 | /// `aria-hidden="true"`. |
| 173 | pub fn reachable(html: &str) -> String { |
| 174 | strip(html, &["script", "style", "template", "noscript"], true) |
| 175 | } |
| 176 | |
| 177 | /// The contents of every `<noscript>` element in the real markup outside |
| 178 | /// hidden elements: what a reader without scripts gets instead. |
| 179 | pub fn noscript(html: &str) -> Vec<String> { |
| 180 | let m = strip(html, &["script", "style", "template"], true); |
| 181 | let lower = m.to_ascii_lowercase(); |
| 182 | let mut out = Vec::new(); |
| 183 | for (at, _) in lower.match_indices("<noscript") { |
| 184 | if !lower[at + 9..].starts_with(['>', ' ', '\t', '\n', '\r']) { |
| 185 | continue; |
| 186 | } |
| 187 | let Some(body) = m[at..].find('>').map(|g| at + g + 1) else { continue }; |
| 188 | let end = element_end(&m, body, "noscript").map_or(m.len(), |e| e - "</noscript>".len()); |
| 189 | out.push(m[body..end].to_string()); |
| 190 | } |
| 191 | out |
| 192 | } |
| 193 | |
| 194 | /// Whether the real markup has an element with exactly this id. |
| 195 | pub fn has_id(html: &str, id: &str) -> bool { |
| 196 | let m = markup(html); |
| 197 | let mut i = 0; |
| 198 | while let Some(lt) = m[i..].find('<') { |
| 199 | let at = i + lt; |
| 200 | let Some(gt) = m[at..].find('>').map(|g| at + g) else { break }; |
| 201 | if !m[at..].starts_with("</") && attr(&m[at..=gt], "id").as_deref() == Some(id) { |
| 202 | return true; |
| 203 | } |
| 204 | i = gt + 1; |
| 205 | } |
| 206 | false |
| 207 | } |
| 208 | |
| 209 | /// Text a reader sees: hidden elements and every tag removed, the common |
| 210 | /// entities decoded, whitespace squashed. |
| 211 | pub fn reader_text(fragment: &str) -> String { |
| 212 | let s = strip(fragment, &["script", "style", "template"], true); |
| 213 | let mut out = String::with_capacity(s.len()); |
| 214 | let mut in_tag = false; |
| 215 | for c in s.chars() { |
| 216 | match c { |
| 217 | '<' => in_tag = true, |
| 218 | '>' if in_tag => { |
| 219 | in_tag = false; |
| 220 | out.push(' '); |
| 221 | } |
| 222 | _ if !in_tag => out.push(c), |
| 223 | _ => {} |
| 224 | } |
| 225 | } |
| 226 | let out = out.replace(" ", " ").replace(""", "\"").replace("'", "'").replace("<", "<").replace(">", ">").replace("&", "&"); |
| 227 | out.split_whitespace().collect::<Vec<_>>().join(" ") |
| 228 | } |
| 229 | |
| 230 | /// Every `<a>` in `region`, as (href, reader text). An anchor without an |
| 231 | /// href has an empty one. |
| 232 | pub fn anchors(region: &str) -> Vec<(String, String)> { |
| 233 | let lower = region.to_ascii_lowercase(); |
| 234 | let mut out = Vec::new(); |
| 235 | let mut i = 0; |
| 236 | while let Some(lt) = lower[i..].find("<a") { |
| 237 | let at = i + lt; |
| 238 | i = at + 2; |
| 239 | if !lower[i..].starts_with(['>', ' ', '\t', '\n', '\r']) { |
| 240 | continue; |
| 241 | } |
| 242 | let Some(gt) = region[at..].find('>').map(|g| at + g) else { break }; |
| 243 | let close = lower[gt..].find("</a>").map(|c| gt + c).unwrap_or(region.len()); |
| 244 | out.push((attr(®ion[at..=gt], "href").unwrap_or_default(), reader_text(®ion[gt + 1..close]))); |
| 245 | i = close; |
| 246 | } |
| 247 | out |
| 248 | } |
| 249 | |
| 250 | /// Every `index.html` under dist, as site paths (`/`, `/machine/`, |
| 251 | /// `/research/status/`), sorted. An unreadable directory is an error, never |
| 252 | /// a silently shorter list. |
| 253 | pub fn html_pages(dist: &Path) -> Result<Vec<String>, String> { |
| 254 | fn walk(dir: &Path, dist: &Path, out: &mut Vec<String>) -> Result<(), String> { |
| 255 | let rd = fs::read_dir(dir).map_err(|e| format!("read {}: {e}", dir.display()))?; |
| 256 | for entry in rd { |
| 257 | let entry = entry.map_err(|e| format!("read {}: {e}", dir.display()))?; |
| 258 | let p = entry.path(); |
| 259 | let kind = entry.file_type().map_err(|e| format!("stat {}: {e}", p.display()))?; |
| 260 | if kind.is_dir() { |
| 261 | walk(&p, dist, out)?; |
| 262 | } else if p.file_name().is_some_and(|n| n == "index.html") { |
| 263 | let rel = p.strip_prefix(dist).map_err(|e| e.to_string())?.parent().unwrap_or(Path::new("")); |
| 264 | let rel = rel.to_string_lossy().replace('\\', "/"); |
| 265 | out.push(if rel.is_empty() { "/".to_string() } else { format!("/{rel}/") }); |
| 266 | } |
| 267 | } |
| 268 | Ok(()) |
| 269 | } |
| 270 | let mut out = Vec::new(); |
| 271 | walk(dist, dist, &mut out)?; |
| 272 | out.sort(); |
| 273 | Ok(out) |
| 274 | } |
| 275 | |
| 276 | /// The site is English only: the Simplified Chinese copies are retired and |
| 277 | /// readers translate with their own tools. Fails, naming the file, when dist |
| 278 | /// holds anything under `zh-CN/`, an `hreflang` whose value starts with `zh` |
| 279 | /// (any case), an `<html lang="zh...">`, or a link (`href`, sitemap `<loc>`, |
| 280 | /// markdown target) to a `/zh-CN/` route, root-relative or on the site's |
| 281 | /// host. Rule O8 in the Omega verifier (om/site/verify-rules.tsv). A bare |
| 282 | /// mention of zh-CN in page text is not a translated copy and passes. |
| 283 | /// Returns the number of files read. |
| 284 | pub fn check_no_translations(dist: &Path) -> Result<usize, String> { |
| 285 | static HREFLANG: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?i)\bhreflang\s*=\s*["']?\s*(zh[^"'\s>]*)"#).unwrap()); |
| 286 | static HTML_LANG: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"(?i)<html\b[^>]*?\slang\s*=\s*["']?\s*(zh[^"'\s>]*)"#).unwrap()); |
| 287 | static ZH_LINK: LazyLock<Regex> = LazyLock::new(|| { |
| 288 | Regex::new(r#"(?i)(?:\bhref\s*=\s*["']?|\]\(|<loc>)\s*((?:https?:)?(?://(?:www\.)?aienos\.com)?/zh-cn)(?:[/?#"'\s>)<]|$)"#).unwrap() |
| 289 | }); |
| 290 | const TEXT: [&str; 9] = ["html", "xml", "md", "txt", "json", "tsv", "js", "css", "svg"]; |
| 291 | fn walk(dir: &Path, dist: &Path, n: &mut usize) -> Result<(), String> { |
| 292 | for entry in fs::read_dir(dir).map_err(|e| format!("read {}: {e}", dir.display()))? { |
| 293 | let entry = entry.map_err(|e| format!("read {}: {e}", dir.display()))?; |
| 294 | let p = entry.path(); |
| 295 | let rel = p.strip_prefix(dist).map_err(|e| e.to_string())?.to_string_lossy().replace('\\', "/"); |
| 296 | if entry.file_type().map_err(|e| format!("stat {}: {e}", p.display()))?.is_dir() { |
| 297 | walk(&p, dist, n)?; |
| 298 | continue; |
| 299 | } |
| 300 | if rel.to_ascii_lowercase().starts_with("zh-cn/") { |
| 301 | return Err(format!("{rel}: nothing may live under zh-CN/; the site is English only")); |
| 302 | } |
| 303 | if !p.extension().and_then(|e| e.to_str()).is_some_and(|e| TEXT.contains(&e.to_ascii_lowercase().as_str())) { |
| 304 | continue; |
| 305 | } |
| 306 | let text = fs::read_to_string(&p).map_err(|e| format!("read {}: {e}", p.display()))?; |
| 307 | *n += 1; |
| 308 | if let Some(c) = HREFLANG.captures(&text) { |
| 309 | return Err(format!("{rel}: hreflang {:?} names a Chinese alternate; the site is English only", &c[1])); |
| 310 | } |
| 311 | if let Some(c) = HTML_LANG.captures(&text) { |
| 312 | return Err(format!("{rel}: <html lang={:?}> marks a Chinese page; the site is English only", &c[1])); |
| 313 | } |
| 314 | if let Some(c) = ZH_LINK.captures(&text) { |
| 315 | return Err(format!("{rel}: links {:?}, a retired zh-CN route; the site is English only", &c[1])); |
| 316 | } |
| 317 | } |
| 318 | Ok(()) |
| 319 | } |
| 320 | let mut n = 0; |
| 321 | walk(dist, dist, &mut n)?; |
| 322 | Ok(n) |
| 323 | } |
| 324 | |
| 325 | /// The engineer record (the former drakestapleton.com, now /engineer/), |
| 326 | /// compiled in from its committed source so a generated tree cannot add |
| 327 | /// pages to it. |
| 328 | pub const ENGINEER_RAW: &str = include_str!("../../../public/data/engineer.json"); |
| 329 | |
| 330 | /// The paths of the engineer record after validating every entry: a |
| 331 | /// lowercase path under /engineer/ made of `a-z 0-9 -` segments, listed |
| 332 | /// once; a name, title and description; a known kind, exactly one `home` at |
| 333 | /// /engineer/ itself; old paths that are root-relative. |
| 334 | pub fn engineer_paths(raw: &str) -> Result<Vec<String>, String> { |
| 335 | const KINDS: [&str; 5] = ["home", "page", "collection", "work", "infographic"]; |
| 336 | let v: Value = serde_json::from_str(raw).map_err(|e| format!("engineer.json does not parse: {e}"))?; |
| 337 | let pages = v["pages"].as_array().filter(|a| !a.is_empty()).ok_or("engineer.json has no pages")?; |
| 338 | let mut out: Vec<String> = Vec::new(); |
| 339 | let mut homes = 0; |
| 340 | for p in pages { |
| 341 | let path = p["path"].as_str().ok_or("engineer.json entry without a path")?; |
| 342 | let inner = path.strip_prefix("/engineer/").ok_or(format!("engineer.json: {path} is not under /engineer/"))?; |
| 343 | if !path.ends_with('/') |
| 344 | || !inner.trim_end_matches('/').split('/').all(|s| inner.is_empty() || (!s.is_empty() && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'))) |
| 345 | { |
| 346 | return Err(format!("engineer.json: {path} must be lowercase a-z, 0-9 and - segments ending in /")); |
| 347 | } |
| 348 | if out.iter().any(|o| o == path) { |
| 349 | return Err(format!("engineer.json: {path} is listed twice")); |
| 350 | } |
| 351 | for field in ["name", "title", "description"] { |
| 352 | if p[field].as_str().is_none_or(|s| s.trim().is_empty()) { |
| 353 | return Err(format!("engineer.json: {path} has no {field}")); |
| 354 | } |
| 355 | } |
| 356 | let kind = p["kind"].as_str().unwrap_or_default(); |
| 357 | if !KINDS.contains(&kind) { |
| 358 | return Err(format!("engineer.json: {path} has unknown kind {kind:?}")); |
| 359 | } |
| 360 | if kind == "home" { |
| 361 | homes += 1; |
| 362 | if path != "/engineer/" { |
| 363 | return Err(format!("engineer.json: the home must be /engineer/, not {path}")); |
| 364 | } |
| 365 | } |
| 366 | let old = p["old"].as_array().ok_or(format!("engineer.json: {path} has no old paths"))?; |
| 367 | if !old.iter().all(|o| o.as_str().is_some_and(|s| s.starts_with('/') && !s.starts_with("//"))) { |
| 368 | return Err(format!("engineer.json: {path} old paths must be root-relative")); |
| 369 | } |
| 370 | out.push(path.to_string()); |
| 371 | } |
| 372 | if homes != 1 { |
| 373 | return Err(format!("engineer.json needs exactly one home, found {homes}")); |
| 374 | } |
| 375 | Ok(out) |
| 376 | } |
| 377 | |
| 378 | /// The engineer record and the About-the-engineer section of [`PAGES`] name |
| 379 | /// exactly the same pages: the Rust builder registers every engineer page in |
| 380 | /// [`PAGES`], and the record is the authored source the generator renders. |
| 381 | pub fn check_engineer_registered(paths: &[String]) -> Result<(), String> { |
| 382 | for path in paths { |
| 383 | if !seo::info_for(path).is_some_and(|p| p.section == seo::Section::Engineer) { |
| 384 | return Err(format!("engineer.json: {path} is not an About-the-engineer page in seo::PAGES")); |
| 385 | } |
| 386 | } |
| 387 | for page in PAGES.iter().filter(|p| p.section == seo::Section::Engineer) { |
| 388 | if !paths.iter().any(|p| p == page.path) { |
| 389 | return Err(format!("seo::PAGES: {} is missing from engineer.json", page.path)); |
| 390 | } |
| 391 | } |
| 392 | Ok(()) |
| 393 | } |
| 394 | |
| 395 | /// Every English page the site must publish: [`PAGES`], which carries the |
| 396 | /// engineer record's pages once the record is shown to agree with it. Both |
| 397 | /// are Rust-side sources, never the generator's own output. |
| 398 | pub fn registry() -> BTreeSet<String> { |
| 399 | let engineer = engineer_paths(ENGINEER_RAW).unwrap_or_else(|e| panic!("{e}")); |
| 400 | check_engineer_registered(&engineer).unwrap_or_else(|e| panic!("{e}")); |
| 401 | PAGES.iter().map(|p| p.path.to_string()).collect() |
| 402 | } |
| 403 | |
| 404 | /// The written pages and the registry agree in both directions. |
| 405 | pub fn check_registry(paths: &[String]) -> Result<(), String> { |
| 406 | check_registry_against(paths, ®istry()) |
| 407 | } |
| 408 | |
| 409 | fn check_registry_against(paths: &[String], registry: &BTreeSet<String>) -> Result<(), String> { |
| 410 | let written: BTreeSet<&str> = paths.iter().map(String::as_str).collect(); |
| 411 | for p in paths { |
| 412 | if !registry.contains(p) { |
| 413 | return Err(format!("{p} was written but is not in seo::PAGES or the engineer record")); |
| 414 | } |
| 415 | } |
| 416 | for path in registry { |
| 417 | if !written.contains(path.as_str()) { |
| 418 | return Err(format!("the registry lists {path} but no such page was written")); |
| 419 | } |
| 420 | } |
| 421 | Ok(()) |
| 422 | } |
| 423 | |
| 424 | /// The opening tags of a head, with the text of its `<title>`. |
| 425 | struct Head { |
| 426 | title: Option<String>, |
| 427 | tags: Vec<String>, |
| 428 | } |
| 429 | |
| 430 | fn read_head(html: &str) -> Result<Head, String> { |
| 431 | let lower = html.to_ascii_lowercase(); |
| 432 | let open = lower |
| 433 | .match_indices("<head") |
| 434 | .map(|(h, _)| h) |
| 435 | .find(|&h| lower[h + 5..].starts_with(['>', ' ', '\t', '\n', '\r'])) |
| 436 | .ok_or("no <head>")?; |
| 437 | let start = open + lower[open..].find('>').ok_or("unterminated <head>")? + 1; |
| 438 | let end = start + lower[start..].find("</head>").ok_or("no </head>")?; |
| 439 | let head = &html[start..end]; |
| 440 | let lower_head = &lower[start..end]; |
| 441 | let mut tags = Vec::new(); |
| 442 | let mut title = None; |
| 443 | let mut i = 0; |
| 444 | while let Some(lt) = head[i..].find('<') { |
| 445 | let at = i + lt; |
| 446 | let rest = &head[at..]; |
| 447 | if rest.starts_with("<!--") { |
| 448 | i = at + rest.find("-->").ok_or("unterminated comment in <head>")? + 3; |
| 449 | continue; |
| 450 | } |
| 451 | let gt = rest.find('>').ok_or("unterminated tag in <head>")?; |
| 452 | let tag = &rest[..=gt]; |
| 453 | let name = tag_name(tag); |
| 454 | if !rest.starts_with("</") && (name == "title" || name == "script" || name == "style") { |
| 455 | let close = format!("</{name}"); |
| 456 | let body_start = at + gt + 1; |
| 457 | let close_at = lower_head[body_start..].find(&close).map(|c| body_start + c).ok_or(format!("<{name}> does not close in <head>"))?; |
| 458 | if name == "title" { |
| 459 | if title.is_some() { |
| 460 | return Err("more than one <title>".into()); |
| 461 | } |
| 462 | title = Some(head[body_start..close_at].trim().to_string()); |
| 463 | } |
| 464 | tags.push(tag.to_string()); |
| 465 | i = close_at + close.len(); |
| 466 | continue; |
| 467 | } |
| 468 | if !rest.starts_with("</") && !rest.starts_with("<!") { |
| 469 | tags.push(tag.to_string()); |
| 470 | } |
| 471 | i = at + gt + 1; |
| 472 | } |
| 473 | Ok(Head { title, tags }) |
| 474 | } |
| 475 | |
| 476 | /// The head of one page: a title, a description, the social title and |
| 477 | /// description, one canonical URL on the www host that is this page, the |
| 478 | /// og:url equal to it, an English `<html lang>`, and no hreflang alternates |
| 479 | /// (the site has one language, so a page names no other version of itself). |
| 480 | pub fn check_head(path: &str, html: &str) -> Result<(), String> { |
| 481 | let head = read_head(html)?; |
| 482 | if head.title.as_deref().is_none_or(str::is_empty) { |
| 483 | return Err("no <title>".into()); |
| 484 | } |
| 485 | let meta = |key: &str| { |
| 486 | head.tags |
| 487 | .iter() |
| 488 | .filter(|t| tag_name(t) == "meta") |
| 489 | .filter(|t| attr(t, "name").or_else(|| attr(t, "property")).as_deref() == Some(key)) |
| 490 | .filter_map(|t| attr(t, "content")) |
| 491 | .find(|c| !c.trim().is_empty()) |
| 492 | }; |
| 493 | if meta("description").is_none() && meta("og:description").is_none() { |
| 494 | return Err("no meta description".into()); |
| 495 | } |
| 496 | if meta("og:title").is_none() { |
| 497 | return Err("no og:title".into()); |
| 498 | } |
| 499 | if meta("og:description").is_none() { |
| 500 | return Err("no og:description".into()); |
| 501 | } |
| 502 | let links = |rel: &str| -> Vec<&String> { |
| 503 | head.tags.iter().filter(|t| tag_name(t) == "link" && attr(t, "rel").as_deref() == Some(rel)).collect() |
| 504 | }; |
| 505 | let url = format!("{HOST}{path}"); |
| 506 | let canonical: Vec<String> = links("canonical").iter().filter_map(|t| attr(t, "href")).collect(); |
| 507 | if canonical != [url.clone()] { |
| 508 | return Err(format!("needs exactly one canonical {url}, found {canonical:?}")); |
| 509 | } |
| 510 | if meta("og:url").as_deref() != Some(url.as_str()) { |
| 511 | return Err(format!("og:url must equal the canonical {url}")); |
| 512 | } |
| 513 | let lang = html |
| 514 | .find("<html") |
| 515 | .and_then(|h| html[h..].find('>').map(|g| attr(&html[h..=h + g], "lang"))) |
| 516 | .flatten() |
| 517 | .unwrap_or_default(); |
| 518 | if !(lang == "en" || lang.starts_with("en-")) { |
| 519 | return Err(format!("<html lang> is {lang:?}, not English")); |
| 520 | } |
| 521 | if let Some(h) = links("alternate").iter().find_map(|t| attr(t, "hreflang")) { |
| 522 | return Err(format!("hreflang alternate on a site with no translations (hreflang {h:?})")); |
| 523 | } |
| 524 | Ok(()) |
| 525 | } |
| 526 | |
| 527 | /// A seo::REDIRECTS stub: not a page, so it is checked only as a stub. It |
| 528 | /// must stay out of search, forward with and without scripts to `new`, and |
| 529 | /// `new` must be a written page. |
| 530 | pub fn check_redirect(new: &str, html: &str, written: &BTreeSet<&str>) -> Result<(), String> { |
| 531 | if !written.contains(new) { |
| 532 | return Err(format!("forwards to {new}, which was not written")); |
| 533 | } |
| 534 | let need = [ |
| 535 | "<meta name=\"robots\" content=\"noindex\">".to_string(), |
| 536 | format!("<meta http-equiv=\"refresh\" content=\"0; url={new}\">"), |
| 537 | format!("<script src=\"/js/redirect.js\" data-to=\"{new}\"></script>"), |
| 538 | format!("<a href=\"{new}\">"), |
| 539 | ]; |
| 540 | match need.iter().find(|n| !html.contains(n.as_str())) { |
| 541 | Some(n) => Err(format!("redirect stub lacks {n}")), |
| 542 | None => Ok(()), |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | /// Every page in dist: registered, with a complete head, and linking the |
| 547 | /// six destinations (there is no nav bar, so each page carries them itself). |
| 548 | /// seo::REDIRECTS stubs are checked as stubs and are not pages. |
| 549 | pub fn verify_pages(dist: &Path) -> Result<usize, String> { |
| 550 | let all = html_pages(dist)?; |
| 551 | let stub = |p: &str| crate::seo::REDIRECTS.iter().find(|(old, _)| *old == p).map(|(_, new)| *new); |
| 552 | let paths: Vec<String> = all.iter().filter(|p| stub(p).is_none()).cloned().collect(); |
| 553 | check_registry(&paths)?; |
| 554 | let written: BTreeSet<&str> = paths.iter().map(String::as_str).collect(); |
| 555 | for p in &all { |
| 556 | if let Some(new) = stub(p) { |
| 557 | let file = dist.join(p.trim_start_matches('/')).join("index.html"); |
| 558 | let html = fs::read_to_string(&file).map_err(|e| format!("read {}: {e}", file.display()))?; |
| 559 | check_redirect(new, &html, &written).map_err(|e| format!("{p}: {e}"))?; |
| 560 | } |
| 561 | } |
| 562 | for p in &paths { |
| 563 | let file = dist.join(p.trim_start_matches('/')).join("index.html"); |
| 564 | let html = fs::read_to_string(&file).map_err(|e| format!("read {}: {e}", file.display()))?; |
| 565 | check_head(p, &html).map_err(|e| format!("{p}: {e}"))?; |
| 566 | crate::components::navbar::check_destinations(&html).map_err(|e| format!("{p}: {e}"))?; |
| 567 | } |
| 568 | Ok(paths.len()) |
| 569 | } |
| 570 | |
| 571 | fn no_dash(name: &str, raw: &str) -> Result<(), String> { |
| 572 | if raw.contains('\u{2014}') || raw.contains('\u{2013}') { |
| 573 | return Err(format!("{name} has an em or en dash")); |
| 574 | } |
| 575 | Ok(()) |
| 576 | } |
| 577 | |
| 578 | pub fn check_machines(raw: &str) -> Result<(), String> { |
| 579 | no_dash("machines.json", raw)?; |
| 580 | crate::components::machines::parse(raw).map(|_| ()) |
| 581 | } |
| 582 | |
| 583 | pub fn check_omega(raw: &str) -> Result<(), String> { |
| 584 | no_dash("omega.json", raw)?; |
| 585 | crate::components::omega::validate(&crate::components::omega::parse(raw)?) |
| 586 | } |
| 587 | |
| 588 | pub fn check_cudaplusplus(raw: &str) -> Result<(), String> { |
| 589 | no_dash("cudaplusplus.json", raw)?; |
| 590 | crate::components::cudaplusplus::validate(&crate::components::cudaplusplus::parse(raw)?) |
| 591 | } |
| 592 | |
| 593 | pub fn check_research_status(raw: &str) -> Result<(), String> { |
| 594 | crate::components::research_status::parse(raw).map(|_| ()) |
| 595 | } |
| 596 | |
| 597 | pub fn check_progress(raw: &str) -> Result<(), String> { |
| 598 | let v: Value = serde_json::from_str(raw).map_err(|e| format!("project-progress.json does not parse: {e}"))?; |
| 599 | crate::collector::validate_snapshot(&v) |
| 600 | } |
| 601 | |
| 602 | /// The layer states: the five fixed status words, and every layer named, |
| 603 | /// in one of them, with a note and either no receipt or an https one. |
| 604 | pub fn check_status(raw: &str) -> Result<(), String> { |
| 605 | const STATUSES: [&str; 5] = ["IMPLEMENTED", "QUALIFIED", "EXPERIMENTAL", "BLOCKED", "PLANNED"]; |
| 606 | no_dash("status.json", raw)?; |
| 607 | let v: Value = serde_json::from_str(raw).map_err(|e| format!("status.json does not parse: {e}"))?; |
| 608 | let statuses: Vec<&str> = v["statuses"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); |
| 609 | if statuses != STATUSES { |
| 610 | return Err(format!("status.json statuses differ from the fixed set: {statuses:?}")); |
| 611 | } |
| 612 | let layers = v["layers"].as_array().filter(|a| !a.is_empty()).ok_or("status.json has no layers")?; |
| 613 | for l in layers { |
| 614 | let name = l["name"].as_str().filter(|s| !s.trim().is_empty()).ok_or("status.json layer without a name")?; |
| 615 | let status = l["status"].as_str().unwrap_or_default(); |
| 616 | if !STATUSES.contains(&status) { |
| 617 | return Err(format!("status.json layer {name}: unknown status {status:?}")); |
| 618 | } |
| 619 | if l["note"].as_str().is_none_or(|s| s.trim().is_empty()) { |
| 620 | return Err(format!("status.json layer {name}: no note")); |
| 621 | } |
| 622 | match &l["receipt"] { |
| 623 | Value::Null => {} |
| 624 | // A forge receipt, or a plain label (repository and number) with no URL at all. |
| 625 | Value::String(r) if r.starts_with(crate::forge::FORGE) || (!r.trim().is_empty() && !r.contains("://")) => {} |
| 626 | other => return Err(format!("status.json layer {name}: receipt must be null, a forge URL or a plain label, not {other}")), |
| 627 | } |
| 628 | } |
| 629 | Ok(()) |
| 630 | } |
| 631 | |
| 632 | /// data/pages.json, the published page list, names exactly the pages of |
| 633 | /// [`PAGES`], each once, with a title and a description, as its own |
| 634 | /// English page. The oracle never reads this file to decide what the site |
| 635 | /// is; it checks the file against the Rust registry. |
| 636 | pub fn check_pages_json(raw: &str) -> Result<(), String> { |
| 637 | let v: Value = serde_json::from_str(raw).map_err(|e| format!("data/pages.json does not parse: {e}"))?; |
| 638 | let rows = v.as_array().ok_or("data/pages.json is not a list")?; |
| 639 | let mut listed = BTreeSet::new(); |
| 640 | for r in rows { |
| 641 | let path = r["path"].as_str().ok_or("data/pages.json entry without a path")?; |
| 642 | for field in ["title", "description"] { |
| 643 | if r[field].as_str().is_none_or(|s| s.trim().is_empty()) { |
| 644 | return Err(format!("data/pages.json: {path} has no {field}")); |
| 645 | } |
| 646 | } |
| 647 | if r["english"].as_str() != Some(path) { |
| 648 | return Err(format!("data/pages.json: {path} must name itself as its English page")); |
| 649 | } |
| 650 | if !listed.insert(path) { |
| 651 | return Err(format!("data/pages.json lists {path} twice")); |
| 652 | } |
| 653 | } |
| 654 | let registry = registry(); |
| 655 | let expected: BTreeSet<&str> = registry.iter().map(String::as_str).collect(); |
| 656 | if listed != expected { |
| 657 | let missing: Vec<_> = expected.difference(&listed).collect(); |
| 658 | let extra: Vec<_> = listed.difference(&expected).collect(); |
| 659 | return Err(format!("data/pages.json differs from seo::PAGES plus the engineer record: missing {missing:?}, unexpected {extra:?}")); |
| 660 | } |
| 661 | Ok(()) |
| 662 | } |
| 663 | |
| 664 | /// data/index.json lists exactly [`DATA_FILES`], each at its www URL. |
| 665 | pub fn check_data_index(raw: &str) -> Result<(), String> { |
| 666 | let v: Value = serde_json::from_str(raw).map_err(|e| format!("data/index.json does not parse: {e}"))?; |
| 667 | let files = v["files"].as_array().ok_or("data/index.json has no files")?; |
| 668 | let mut listed = BTreeSet::new(); |
| 669 | for f in files { |
| 670 | let path = f["path"].as_str().ok_or("data/index.json entry without a path")?; |
| 671 | if f["url"].as_str() != Some(format!("{HOST}{path}").as_str()) { |
| 672 | return Err(format!("data/index.json: {path} must carry url {HOST}{path}")); |
| 673 | } |
| 674 | if !listed.insert(path) { |
| 675 | return Err(format!("data/index.json lists {path} twice")); |
| 676 | } |
| 677 | } |
| 678 | let expected: BTreeSet<&str> = DATA_FILES.iter().map(|d| d.path).collect(); |
| 679 | if listed != expected { |
| 680 | let missing: Vec<_> = expected.difference(&listed).collect(); |
| 681 | let extra: Vec<_> = listed.difference(&expected).collect(); |
| 682 | return Err(format!("data/index.json differs from seo::DATA_FILES: missing {missing:?}, unexpected {extra:?}")); |
| 683 | } |
| 684 | Ok(()) |
| 685 | } |
| 686 | |
| 687 | /// Every published data file parses and passes the same validation the |
| 688 | /// renderer applied to its source, read from dist rather than compiled in. |
| 689 | pub fn verify_data(dist: &Path) -> Result<(), String> { |
| 690 | let read = |rel: &str| fs::read_to_string(dist.join(rel)).map_err(|e| format!("read {rel}: {e}")); |
| 691 | let checks: [(&str, fn(&str) -> Result<(), String>); 9] = [ |
| 692 | ("machines.json", check_machines), |
| 693 | ("omega.json", check_omega), |
| 694 | ("cudaplusplus.json", check_cudaplusplus), |
| 695 | ("research-status.json", check_research_status), |
| 696 | ("status.json", check_status), |
| 697 | ("data/project-progress.json", check_progress), |
| 698 | ("data/index.json", check_data_index), |
| 699 | ("data/pages.json", check_pages_json), |
| 700 | ("now.json", |raw| serde_json::from_str::<Value>(raw).map(|_| ()).map_err(|e| format!("now.json does not parse: {e}"))), |
| 701 | ]; |
| 702 | for (rel, check) in checks { |
| 703 | check(&read(rel)?).map_err(|e| format!("{rel}: {e}"))?; |
| 704 | } |
| 705 | crate::facts::Facts::load(&dist.join("facts.json"))?; |
| 706 | crate::components::agents::Repos::load(&dist.join("data/agent-repos.json"))?; |
| 707 | // The published engineer record is the committed one, byte for byte. |
| 708 | if read("data/engineer.json")? != ENGINEER_RAW { |
| 709 | return Err("data/engineer.json differs from the committed public/data/engineer.json".into()); |
| 710 | } |
| 711 | Ok(()) |
| 712 | } |
| 713 | |
| 714 | /// Aien's own page retains the native introduction. Real elements (not text in a |
| 715 | /// comment or a script) carry `id="allen"` and `id="site-door"`; a reader |
| 716 | /// with scripts reaches a link to the classic site, and so does a reader |
| 717 | /// without them, through a `<noscript>` link of its own. |
| 718 | pub fn check_aien_intro(html: &str) -> Result<(), String> { |
| 719 | for id in ["allen", "site-door"] { |
| 720 | if !has_id(html, id) { |
| 721 | return Err(format!("the root has no element with id=\"{id}\"")); |
| 722 | } |
| 723 | } |
| 724 | let classic = |links: Vec<(String, String)>| links.iter().any(|(h, t)| h == "/classic/" && !t.is_empty()); |
| 725 | if !classic(anchors(&reachable(html))) { |
| 726 | return Err("the root must link the classic site at /classic/ where a reader can reach it".into()); |
| 727 | } |
| 728 | if !noscript(html).iter().any(|n| classic(anchors(&strip(n, &[], true)))) { |
| 729 | return Err("the root must link /classic/ inside <noscript> for readers without scripts".into()); |
| 730 | } |
| 731 | Ok(()) |
| 732 | } |
| 733 | |
| 734 | /// The homepage is readable without entering the animated Aien experience. |
| 735 | /// Since 2026-11-09 it is the live factory floor plus short routes; the |
| 736 | /// machines and speeds it used to carry are required on /record/ instead. |
| 737 | pub fn check_root(html: &str) -> Result<(), String> { |
| 738 | let visible = reachable(html); |
| 739 | for id in ["main-content", "root", "factory-floor", "follow"] { |
| 740 | if !has_id(&visible, id) { |
| 741 | return Err(format!("readable homepage is missing {id}")); |
| 742 | } |
| 743 | } |
| 744 | if has_id(html, "site-door") || has_id(html, "allen") { |
| 745 | return Err("the homepage must not contain the Aien entrance".into()); |
| 746 | } |
| 747 | for path in ["/aien/", "/engineer/", "/machine/", "/evidence/", "/record/"] { |
| 748 | if !anchors(&visible).iter().any(|(h, t)| h == path && !t.is_empty()) { |
| 749 | return Err(format!("homepage must link {path}")); |
| 750 | } |
| 751 | } |
| 752 | Ok(()) |
| 753 | } |
| 754 | |
| 755 | /// The record holds the former homepage's machines and speeds where a reader |
| 756 | /// can reach them, without the Aien entrance. |
| 757 | pub fn check_record(html: &str) -> Result<(), String> { |
| 758 | let visible = reachable(html); |
| 759 | for id in ["main-content", "root", "machines", "speed"] { |
| 760 | if !has_id(&visible, id) { |
| 761 | return Err(format!("readable record is missing {id}")); |
| 762 | } |
| 763 | } |
| 764 | if has_id(html, "site-door") || has_id(html, "allen") { |
| 765 | return Err("the record must not contain the Aien entrance".into()); |
| 766 | } |
| 767 | Ok(()) |
| 768 | } |
| 769 | |
| 770 | /// Every root-relative script source and stylesheet that `html` loads, in |
| 771 | /// real markup (comments skipped; script and style bodies are not markup). |
| 772 | pub fn page_assets(html: &str) -> Vec<String> { |
| 773 | let m = strip(html, &[], false); |
| 774 | let mut out = Vec::new(); |
| 775 | let mut i = 0; |
| 776 | while let Some(lt) = m[i..].find('<') { |
| 777 | let at = i + lt; |
| 778 | let Some(gt) = m[at..].find('>').map(|g| at + g) else { break }; |
| 779 | let tag = &m[at..=gt]; |
| 780 | let name = tag_name(tag); |
| 781 | i = gt + 1; |
| 782 | if tag.starts_with("</") { |
| 783 | continue; |
| 784 | } |
| 785 | let url = match name.as_str() { |
| 786 | "script" => attr(tag, "src"), |
| 787 | "link" if attr(tag, "rel").is_some_and(|r| r.split_ascii_whitespace().any(|t| t.eq_ignore_ascii_case("stylesheet"))) => attr(tag, "href"), |
| 788 | _ => None, |
| 789 | }; |
| 790 | if let Some(u) = url.filter(|u| u.starts_with('/') && !u.starts_with("//")) { |
| 791 | out.push(u); |
| 792 | } |
| 793 | if name == "script" || name == "style" { |
| 794 | i = element_end(&m, gt + 1, &name).unwrap_or(m.len()); |
| 795 | } |
| 796 | } |
| 797 | out |
| 798 | } |
| 799 | |
| 800 | /// The regular file under dist that a root-relative URL names, or why not. |
| 801 | pub fn resolve_asset(dist: &Path, url: &str) -> Result<(), String> { |
| 802 | let path = url.split(['?', '#']).next().unwrap_or(""); |
| 803 | let rel = path.trim_start_matches('/'); |
| 804 | if rel.is_empty() || path.ends_with('/') || rel.split('/').any(|s| s.is_empty() || s == "." || s == ".." || s.contains('\\')) { |
| 805 | return Err(format!("{url} does not name a file")); |
| 806 | } |
| 807 | let file = dist.join(rel); |
| 808 | let meta = fs::symlink_metadata(&file).map_err(|_| format!("{url} is not in dist"))?; |
| 809 | if !meta.file_type().is_file() { |
| 810 | return Err(format!("{url} is not a regular file in dist")); |
| 811 | } |
| 812 | Ok(()) |
| 813 | } |
| 814 | |
| 815 | /// Every `.html` in dist loads only scripts and stylesheets that dist holds. |
| 816 | pub fn verify_assets(dist: &Path) -> Result<usize, String> { |
| 817 | fn walk(dir: &Path, dist: &Path, n: &mut usize) -> Result<(), String> { |
| 818 | for entry in fs::read_dir(dir).map_err(|e| format!("read {}: {e}", dir.display()))? { |
| 819 | let entry = entry.map_err(|e| format!("read {}: {e}", dir.display()))?; |
| 820 | let p = entry.path(); |
| 821 | if entry.file_type().map_err(|e| format!("stat {}: {e}", p.display()))?.is_dir() { |
| 822 | walk(&p, dist, n)?; |
| 823 | } else if p.extension().is_some_and(|e| e == "html") { |
| 824 | let html = fs::read_to_string(&p).map_err(|e| format!("read {}: {e}", p.display()))?; |
| 825 | for url in page_assets(&html) { |
| 826 | resolve_asset(dist, &url).map_err(|e| format!("{}: {e}", p.display()))?; |
| 827 | *n += 1; |
| 828 | } |
| 829 | } |
| 830 | } |
| 831 | Ok(()) |
| 832 | } |
| 833 | let mut n = 0; |
| 834 | walk(dist, dist, &mut n)?; |
| 835 | Ok(n) |
| 836 | } |
| 837 | |
| 838 | /// The sitemap lists every registered page, engineer record included, at |
| 839 | /// its www URL. (seo::verify covers [`PAGES`] with its other surfaces.) |
| 840 | pub fn check_sitemap(sitemap: &str) -> Result<(), String> { |
| 841 | for path in registry() { |
| 842 | if !sitemap.contains(&format!("<loc>{HOST}{path}</loc>")) { |
| 843 | return Err(format!("sitemap.xml must list {path}")); |
| 844 | } |
| 845 | } |
| 846 | Ok(()) |
| 847 | } |
| 848 | |
| 849 | /// The verify-only gates, in one call from `verify_site`. |
| 850 | pub fn verify(dist: &Path) { |
| 851 | let read = check_no_translations(dist).unwrap_or_else(|e| panic!("{e}")); |
| 852 | let n = verify_pages(dist).unwrap_or_else(|e| panic!("{e}")); |
| 853 | let sitemap = fs::read_to_string(dist.join("sitemap.xml")).unwrap_or_else(|e| panic!("read sitemap.xml: {e}")); |
| 854 | check_sitemap(&sitemap).unwrap_or_else(|e| panic!("{e}")); |
| 855 | let root = fs::read_to_string(dist.join("index.html")).unwrap_or_else(|e| panic!("read index.html: {e}")); |
| 856 | check_root(&root).unwrap_or_else(|e| panic!("index.html: {e}")); |
| 857 | let record = fs::read_to_string(dist.join("record/index.html")).unwrap_or_else(|e| panic!("read record/index.html: {e}")); |
| 858 | check_record(&record).unwrap_or_else(|e| panic!("record/index.html: {e}")); |
| 859 | let aien = fs::read_to_string(dist.join("aien/index.html")).expect("Aien page"); |
| 860 | check_aien_intro(&aien).unwrap_or_else(|e| panic!("aien/index.html: {e}")); |
| 861 | let assets = verify_assets(dist).unwrap_or_else(|e| panic!("{e}")); |
| 862 | verify_data(dist).unwrap_or_else(|e| panic!("{e}")); |
| 863 | println!(" Registry and heads: {n} pages; {assets} script and stylesheet loads resolve; no translations: {read} files hold no zh-CN copy, alternate or link; published data files validated"); |
| 864 | } |
| 865 | |
| 866 | #[cfg(test)] |
| 867 | mod tests { |
| 868 | use super::*; |
| 869 | |
| 870 | fn page(path: &str, lang: &str, extra: &str) -> String { |
| 871 | format!( |
| 872 | "<!doctype html><html lang=\"{lang}\"><head><meta charset=\"utf-8\"><title>T</title><meta name=\"description\" content=\"D\"><meta property=\"og:title\" content=\"T\"><meta property=\"og:description\" content=\"D\"><link rel=\"canonical\" href=\"{HOST}{path}\"><meta property=\"og:url\" content=\"{HOST}{path}\">{extra}</head><body></body></html>" |
| 873 | ) |
| 874 | } |
| 875 | |
| 876 | fn all_pages() -> Vec<String> { |
| 877 | registry().into_iter().collect() |
| 878 | } |
| 879 | |
| 880 | #[test] |
| 881 | fn sitemap_must_list_every_registered_page() { |
| 882 | let full: String = all_pages().iter().map(|p| format!("<url><loc>{HOST}{p}</loc></url>")).collect(); |
| 883 | check_sitemap(&full).unwrap(); |
| 884 | assert!(check_sitemap(&full.replace(&format!("<loc>{HOST}/engineer/</loc>"), "")).is_err(), "an engineer page left out"); |
| 885 | assert!(check_sitemap(&full.replace(&format!("<loc>{HOST}/classic/</loc>"), "<loc>https://aienos.com/classic/</loc>")).is_err(), "the apex host"); |
| 886 | } |
| 887 | |
| 888 | #[test] |
| 889 | fn the_engineer_record_is_registered() { |
| 890 | let paths = engineer_paths(ENGINEER_RAW).expect("the committed record validates"); |
| 891 | assert!(paths.iter().any(|p| p == "/engineer/")); |
| 892 | check_engineer_registered(&paths).expect("the record and seo::PAGES agree"); |
| 893 | let all = registry(); |
| 894 | assert_eq!(all.len(), PAGES.len(), "every engineer page is one seo::PAGES entry"); |
| 895 | assert!(paths.iter().all(|p| all.contains(p))); |
| 896 | let dropped: Vec<String> = paths.iter().filter(|p| p.as_str() != "/engineer/").cloned().collect(); |
| 897 | assert!(check_engineer_registered(&dropped).unwrap_err().contains("/engineer/ is missing"), "a page only in seo::PAGES is caught"); |
| 898 | let mut extra = paths.clone(); |
| 899 | extra.push("/engineer/not-registered/".to_string()); |
| 900 | assert!(check_engineer_registered(&extra).unwrap_err().contains("/engineer/not-registered/"), "a page only in the record is caught"); |
| 901 | let mut stray = paths.clone(); |
| 902 | stray.push("/machine/".to_string()); |
| 903 | assert!(check_engineer_registered(&stray).is_err(), "a page from another section is caught"); |
| 904 | let missing: Vec<String> = all_pages().into_iter().filter(|p| p != "/engineer/").collect(); |
| 905 | assert!(check_registry(&missing).unwrap_err().contains("/engineer/"), "a dropped engineer page is caught"); |
| 906 | } |
| 907 | |
| 908 | #[test] |
| 909 | fn engineer_record_negative_controls() { |
| 910 | let entry = |path: &str, kind: &str| format!("{{\"path\":\"{path}\",\"old\":[\"/x\"],\"name\":\"N\",\"title\":\"T\",\"description\":\"D\",\"kind\":\"{kind}\",\"body_html\":\"\"}}"); |
| 911 | let rec = |rows: &[String]| format!("{{\"source\":\"s\",\"pages\":[{}]}}", rows.join(",")); |
| 912 | let home = entry("/engineer/", "home"); |
| 913 | engineer_paths(&rec(&[home.clone(), entry("/engineer/works/a-1/", "work")])).unwrap(); |
| 914 | let cases = [ |
| 915 | ("no pages", rec(&[])), |
| 916 | ("no home", rec(&[entry("/engineer/a/", "page")])), |
| 917 | ("two homes", rec(&[home.clone(), entry("/engineer/b/", "home")])), |
| 918 | ("outside /engineer/", rec(&[home.clone(), entry("/machine/x/", "page")])), |
| 919 | ("uppercase path", rec(&[home.clone(), entry("/engineer/Atlas/", "page")])), |
| 920 | ("prefix in another case", rec(&[home.clone(), entry("/Engineer/a/", "page")])), |
| 921 | ("no trailing slash", rec(&[home.clone(), entry("/engineer/a", "page")])), |
| 922 | ("empty segment", rec(&[home.clone(), entry("/engineer//a/", "page")])), |
| 923 | ("dot segment", rec(&[home.clone(), entry("/engineer/../a/", "page")])), |
| 924 | ("duplicate", rec(&[home.clone(), entry("/engineer/a/", "page"), entry("/engineer/a/", "page")])), |
| 925 | ("unknown kind", rec(&[home.clone(), entry("/engineer/a/", "secret")])), |
| 926 | ("empty title", rec(&[home.clone(), entry("/engineer/a/", "page").replace("\"title\":\"T\"", "\"title\":\" \"")])), |
| 927 | ("external old path", rec(&[home.clone(), entry("/engineer/a/", "page").replace("[\"/x\"]", "[\"//evil.example/\"]")])), |
| 928 | ("not JSON", "{".to_string()), |
| 929 | ]; |
| 930 | for (what, raw) in cases { |
| 931 | assert!(engineer_paths(&raw).is_err(), "must reject: {what}"); |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | #[test] |
| 936 | fn registry_accepts_exactly_the_listed_pages() { |
| 937 | check_registry(&all_pages()).expect("the registry itself passes"); |
| 938 | } |
| 939 | |
| 940 | #[test] |
| 941 | fn registry_rejects_an_extra_page_and_a_missing_page() { |
| 942 | let mut extra = all_pages(); |
| 943 | extra.push("/foo/".into()); |
| 944 | assert!(check_registry(&extra).unwrap_err().contains("/foo/ was written but is not in seo::PAGES")); |
| 945 | let mut stray = all_pages(); |
| 946 | stray.push("/engineer/unlisted/".into()); |
| 947 | assert!(check_registry(&stray).is_err(), "an engineer page not in the record"); |
| 948 | let missing: Vec<String> = all_pages().into_iter().filter(|p| p != "/discoveries/").collect(); |
| 949 | assert!(check_registry(&missing).unwrap_err().contains("lists /discoveries/")); |
| 950 | let mut retired = all_pages(); |
| 951 | retired.push("/zh-CN/machine/".into()); |
| 952 | assert!(check_registry(&retired).unwrap_err().contains("/zh-CN/machine/ was written but is not in seo::PAGES"), "a retired translation is an unlisted page"); |
| 953 | } |
| 954 | |
| 955 | #[test] |
| 956 | fn registry_carries_the_six_dashboards_and_the_peer_pages() { |
| 957 | for p in ["/", "/classic/", "/omega/", "/machine/", "/discoveries/", "/learn/", "/aien/", "/alpha/"] { |
| 958 | assert!(seo::info_for(p).is_some(), "{p} must be registered"); |
| 959 | } |
| 960 | } |
| 961 | |
| 962 | const ROOT: &str = "<body><div id=\"allen\" class=\"allen-scene\"><button id=\"site-door\">Enter</button></div><a href=\"/classic/\">Classic site</a><noscript><a href=\"/classic/\">Read the classic site</a></noscript><main>intro</main></body>"; |
| 963 | |
| 964 | #[test] |
| 965 | fn the_root_door_passes() { |
| 966 | check_aien_intro(ROOT).expect("real Allen and door, classic linked with and without scripts"); |
| 967 | } |
| 968 | |
| 969 | #[test] |
| 970 | fn root_negative_controls() { |
| 971 | let cases = [ |
| 972 | ("allen id only in a comment", ROOT.replace("<div id=\"allen\" class=\"allen-scene\">", "<!-- id=\"allen\" --><div class=\"allen-scene\">")), |
| 973 | ("allen id only in a script", ROOT.replace("<div id=\"allen\" class=\"allen-scene\">", "<script>var s='<div id=\"allen\">'</script><div class=\"allen-scene\">")), |
| 974 | ("door id only as text", ROOT.replace("<button id=\"site-door\">Enter</button>", "<p>id=\"site-door\"</p>")), |
| 975 | ("door id only in a template", ROOT.replace("<button id=\"site-door\">Enter</button>", "<template><button id=\"site-door\">Enter</button></template>")), |
| 976 | ("classic link hidden", ROOT.replace("<a href=\"/classic/\">Classic site</a>", "<a href=\"/classic/\" hidden>Classic site</a>")), |
| 977 | ("classic link only in noscript", ROOT.replace("<a href=\"/classic/\">Classic site</a>", "")), |
| 978 | ("classic link only in a comment", ROOT.replace("<a href=\"/classic/\">Classic site</a>", "<!-- <a href=\"/classic/\">Classic site</a> -->")), |
| 979 | ("no noscript route", ROOT.replace("<noscript><a href=\"/classic/\">Read the classic site</a></noscript>", "")), |
| 980 | ("noscript route hidden", ROOT.replace("<noscript><a href=\"/classic/\">", "<noscript><a href=\"/classic/\" aria-hidden=\"true\">")), |
| 981 | ("noscript inside a hidden element", ROOT.replace("<noscript>", "<div hidden><noscript>").replace("</noscript>", "</noscript></div>")), |
| 982 | ("noscript route without text", ROOT.replace("Read the classic site", "")), |
| 983 | ]; |
| 984 | for (what, html) in cases { |
| 985 | assert!(check_aien_intro(&html).is_err(), "must reject: {what}"); |
| 986 | } |
| 987 | } |
| 988 | |
| 989 | #[test] |
| 990 | fn readable_home_rejects_hidden_content_and_the_old_entrance() { |
| 991 | let home = r#"<main id="main-content"><div id="root"><section id="factory-floor"></section><section id="follow"></section><a href="/aien/">Aien</a><a href="/engineer/">Engineer</a><a href="/machine/">Machine</a><a href="/evidence/">Evidence</a><a href="/record/">The record</a></div></main>"#; |
| 992 | check_root(home).unwrap(); |
| 993 | for id in ["main-content", "root", "factory-floor", "follow"] { |
| 994 | assert!(check_root(&home.replace(&format!("id=\"{id}\""), "hidden")).is_err()); |
| 995 | } |
| 996 | assert!(check_root(&format!("{home}<div id=\"site-door\"></div>")).is_err()); |
| 997 | assert!(check_root(&home.replace("href=\"/engineer/\"", "href=\"/engineer/\" hidden")).is_err()); |
| 998 | assert!(check_root(&home.replace("<a href=\"/record/\">The record</a>", "")).is_err()); |
| 999 | } |
| 1000 | |
| 1001 | #[test] |
| 1002 | fn readable_record_keeps_machines_and_speeds() { |
| 1003 | let record = r#"<main id="main-content"><div id="root"><section id="machines"></section><section id="speed"></section></div></main>"#; |
| 1004 | check_record(record).unwrap(); |
| 1005 | for id in ["main-content", "root", "machines", "speed"] { |
| 1006 | assert!(check_record(&record.replace(&format!("id=\"{id}\""), "hidden")).is_err()); |
| 1007 | } |
| 1008 | assert!(check_record(&record.replace("<section id=\"speed\">", "<section hidden id=\"speed\">")).is_err()); |
| 1009 | assert!(check_record(&format!("{record}<div id=\"allen\"></div>")).is_err()); |
| 1010 | } |
| 1011 | |
| 1012 | #[test] |
| 1013 | fn reachability_drops_hidden_noscript_and_non_markup() { |
| 1014 | let html = "<p>a</p><!-- <p>b</p> --><noscript><p>c</p></noscript><div hidden><p>d</p></div><div aria-hidden=\"true\"><p>e</p></div><script>'<p>f</p>'</script><template><p>g</p></template><p title=\"hidden\" class=\"visually-hidden\">h</p><img hidden src=\"/x.png\"><p>i</p>"; |
| 1015 | let t = reader_text(&reachable(html)); |
| 1016 | assert_eq!(t, "a h i"); |
| 1017 | assert_eq!(attr_names("<p title=\"hidden\" data-x='a b' hidden>"), ["title", "data-x", "hidden"]); |
| 1018 | assert_eq!(reader_text(&reachable("<p>a</p><div hidden><p>never closes")), "a", "unclosed hidden content hides, never adds"); |
| 1019 | } |
| 1020 | |
| 1021 | #[test] |
| 1022 | fn assets_must_resolve_to_regular_files() { |
| 1023 | let dir = std::env::temp_dir().join(format!("oracle-assets-{}", std::process::id())); |
| 1024 | let _ = fs::remove_dir_all(&dir); |
| 1025 | fs::create_dir_all(dir.join("js/dir.js")).unwrap(); |
| 1026 | fs::create_dir_all(dir.join("assets")).unwrap(); |
| 1027 | fs::write(dir.join("js/site.js"), "x").unwrap(); |
| 1028 | fs::write(dir.join("assets/site.css"), "x").unwrap(); |
| 1029 | let page = "<head><link rel=\"stylesheet\" href=\"/assets/site.css?v=1\"><script defer src=\"/js/site.js\"></script><!-- <script src=\"/js/gone.js\"></script> --><script>var s='<script src=\"/js/inline.js\">'</script><link rel=\"icon\" href=\"/missing.ico\"><script src=\"https://example.com/a.js\"></script></head>"; |
| 1030 | assert_eq!(page_assets(page), ["/assets/site.css?v=1", "/js/site.js"]); |
| 1031 | for url in page_assets(page) { |
| 1032 | resolve_asset(&dir, &url).unwrap(); |
| 1033 | } |
| 1034 | for bad in ["/js/missing.js", "/js/dir.js", "/js/", "/", "/js/../js/site.js", "/js//site.js"] { |
| 1035 | assert!(resolve_asset(&dir, bad).is_err(), "must reject {bad}"); |
| 1036 | } |
| 1037 | fs::write(dir.join("index.html"), page).unwrap(); |
| 1038 | assert_eq!(verify_assets(&dir).unwrap(), 2); |
| 1039 | fs::write(dir.join("index.html"), page.replace("/js/site.js", "/js/missing.js")).unwrap(); |
| 1040 | assert!(verify_assets(&dir).is_err(), "a page loading a missing script fails"); |
| 1041 | fs::write(dir.join("index.html"), page.replace("rel=\"stylesheet\" href=\"/assets/site.css?v=1\"", "rel=\"preload stylesheet\" href=\"/assets/gone.css\"")).unwrap(); |
| 1042 | assert!(verify_assets(&dir).is_err(), "a missing stylesheet fails"); |
| 1043 | fs::remove_dir_all(&dir).unwrap(); |
| 1044 | } |
| 1045 | |
| 1046 | #[test] |
| 1047 | fn walker_finds_every_index_page() { |
| 1048 | let dir = std::env::temp_dir().join(format!("oracle-walk-{}", std::process::id())); |
| 1049 | let _ = fs::remove_dir_all(&dir); |
| 1050 | for rel in ["index.html", "machine/index.html", "research/status/index.html", "machine/other.html"] { |
| 1051 | let f = dir.join(rel); |
| 1052 | fs::create_dir_all(f.parent().unwrap()).unwrap(); |
| 1053 | fs::write(f, "x").unwrap(); |
| 1054 | } |
| 1055 | assert_eq!(html_pages(&dir).unwrap(), ["/", "/machine/", "/research/status/"]); |
| 1056 | fs::remove_dir_all(&dir).unwrap(); |
| 1057 | assert!(html_pages(&dir).is_err(), "a missing tree is an error, not an empty site"); |
| 1058 | } |
| 1059 | |
| 1060 | #[test] |
| 1061 | fn a_complete_head_passes() { |
| 1062 | let m = "/machine/"; |
| 1063 | check_head(m, &page(m, "en", "")).unwrap(); |
| 1064 | check_head("/", &page("/", "en", "")).unwrap(); |
| 1065 | check_head(m, &page(m, "en-US", "")).expect("a regional English tag is English"); |
| 1066 | let commented = page(m, "en", "<!-- <link rel=\"canonical\" href=\"https://aienos.com/old/\"> -->"); |
| 1067 | check_head(m, &commented).expect("a commented-out tag is not a tag"); |
| 1068 | } |
| 1069 | |
| 1070 | #[test] |
| 1071 | fn no_translations_gate_rejects_each_trace_and_passes_a_bare_mention() { |
| 1072 | let dir = std::env::temp_dir().join(format!("oracle-no-zh-{}", std::process::id())); |
| 1073 | let reset = |files: &[(&str, &str)]| { |
| 1074 | let _ = fs::remove_dir_all(&dir); |
| 1075 | for (rel, body) in files { |
| 1076 | let f = dir.join(rel); |
| 1077 | fs::create_dir_all(f.parent().unwrap()).unwrap(); |
| 1078 | fs::write(f, body).unwrap(); |
| 1079 | } |
| 1080 | }; |
| 1081 | let clean = page("/machine/", "en", ""); |
| 1082 | reset(&[("index.html", page("/", "en", "").as_str()), ("machine/index.html", clean.as_str()), ("sitemap.xml", format!("<url><loc>{HOST}/machine/</loc></url>").as_str()), ("llms.txt", format!("- [Machine]({HOST}/machine/): the machine").as_str())]); |
| 1083 | assert_eq!(check_no_translations(&dir).expect("a clean English dist passes"), 4); |
| 1084 | let cases: [(&str, Vec<(&str, String)>, &str); 9] = [ |
| 1085 | ("(a) a file under zh-CN/", vec![("zh-CN/index.html", page("/zh-CN/", "en", ""))], "zh-CN/index.html: nothing may live under zh-CN/"), |
| 1086 | ("(b) an English page with a zh-CN alternate (O8-b)", vec![("machine/index.html", page("/machine/", "en", &format!("<link rel=\"alternate\" hreflang=\"zh-CN\" href=\"{HOST}/zh-CN/\">")))], "machine/index.html: hreflang \"zh-CN\""), |
| 1087 | ("(b) hreflang in another case, unquoted", vec![("machine/index.html", page("/machine/", "en", "<link rel=alternate HREFLANG=ZH-hans href=/machine/>"))], "machine/index.html: hreflang \"ZH-hans\""), |
| 1088 | ("(b) a sitemap alternate", vec![("sitemap.xml", "<xhtml:link rel=\"alternate\" hreflang=\"zh-CN\" href=\"x\"/>".into())], "sitemap.xml: hreflang"), |
| 1089 | ("(c) a root-relative link to /zh-CN/", vec![("machine/index.html", clean.replace("<body></body>", "<body><a href=\"/zh-CN/\">x</a></body>"))], "machine/index.html: links \"/zh-CN\""), |
| 1090 | ("(c) an absolute link to a /zh-CN/ page", vec![("machine/index.html", clean.replace("<body></body>", &format!("<body><a href='{HOST}/zh-CN/machine/'>x</a></body>")))], "machine/index.html: links"), |
| 1091 | ("(c) a markdown link in llms.txt", vec: y"))], "llms.txt: links"), |
| 1092 | ("(c) a sitemap entry", vec![("sitemap.xml", format!("<url><loc>{HOST}/zh-CN/machine/</loc></url>"))], "sitemap.xml: links"), |
| 1093 | ("a Chinese <html lang>", vec![("machine/index.html", page("/machine/", "zh-CN", ""))], "machine/index.html: <html lang=\"zh-CN\">"), |
| 1094 | ]; |
| 1095 | for (what, files, want) in cases { |
| 1096 | let files: Vec<(&str, &str)> = files.iter().map(|(r, b)| (*r, b.as_str())).collect(); |
| 1097 | reset(&files); |
| 1098 | let err = check_no_translations(&dir).expect_err(what); |
| 1099 | assert!(err.starts_with(want), "{what}: got {err:?}, want a message starting {want:?}"); |
| 1100 | } |
| 1101 | reset(&[("machine/index.html", clean.replace("<body></body>", "<body><main><p>zh-CN</p><p>Readers translate /zh-CN/ pages themselves.</p><a href=\"/zh-cnx/\">x</a></main></body>").as_str())]); |
| 1102 | check_no_translations(&dir).expect("a bare mention (O8-pos), prose naming the route and a lookalike path are not links to it"); |
| 1103 | fs::remove_dir_all(&dir).unwrap(); |
| 1104 | } |
| 1105 | |
| 1106 | #[test] |
| 1107 | fn head_negative_controls() { |
| 1108 | let good = page("/machine/", "en", ""); |
| 1109 | let m = "/machine/"; |
| 1110 | let cases: [(&str, &str, String); 13] = [ |
| 1111 | ("no <head>", m, good.replace("<head>", "<div>")), |
| 1112 | ("no </head>", m, good.replace("</head>", "")), |
| 1113 | ("empty title", m, good.replace("<title>T</title>", "<title> </title>")), |
| 1114 | ("no description", m, good.replace("<meta name=\"description\" content=\"D\">", "").replace("<meta property=\"og:description\" content=\"D\">", "")), |
| 1115 | ("no og:title", m, good.replace("<meta property=\"og:title\" content=\"T\">", "")), |
| 1116 | ("canonical elsewhere", m, good.replace(&format!("href=\"{HOST}/machine/\""), "href=\"https://aienos.com/machine/\"")), |
| 1117 | ("two canonicals", m, good.replace("</head>", &format!("<link rel=\"canonical\" href=\"{HOST}/machine/\"></head>"))), |
| 1118 | ("og:url differs", m, good.replace(&format!("content=\"{HOST}/machine/\""), &format!("content=\"{HOST}/\""))), |
| 1119 | ("wrong language", m, good.replace("lang=\"en\"", "lang=\"zh-CN\"")), |
| 1120 | ("title only outside the head", m, good.replace("<title>T</title>", "").replace("<body>", "<body><title>T</title>")), |
| 1121 | ("an English alternate", m, page(m, "en", &format!("<link rel=\"alternate\" hreflang=\"en\" href=\"{HOST}/machine/\">"))), |
| 1122 | ("an x-default alternate alone", m, page(m, "en", &format!("<link rel=\"alternate\" hreflang=\"x-default\" href=\"{HOST}/machine/\">"))), |
| 1123 | ("no <html lang>", m, good.replace(" lang=\"en\"", "")), |
| 1124 | ]; |
| 1125 | for (what, path, html) in cases { |
| 1126 | assert!(check_head(path, &html).is_err(), "must reject: {what}"); |
| 1127 | } |
| 1128 | } |
| 1129 | |
| 1130 | #[test] |
| 1131 | fn compiled_data_passes_its_published_checks() { |
| 1132 | check_machines(crate::components::machines::RAW).unwrap(); |
| 1133 | check_omega(crate::components::omega::RAW).unwrap(); |
| 1134 | check_cudaplusplus(crate::components::cudaplusplus::RAW).unwrap(); |
| 1135 | check_research_status(crate::components::research_status::RAW).unwrap(); |
| 1136 | check_status(&crate::components::status::status_json()).unwrap(); |
| 1137 | } |
| 1138 | |
| 1139 | #[test] |
| 1140 | fn data_negative_controls() { |
| 1141 | let dash = |raw: &str| raw.replacen("\": \"", "\": \"\u{2014}", 1); |
| 1142 | assert!(check_machines(&dash(crate::components::machines::RAW)).is_err()); |
| 1143 | assert!(check_omega(&dash(crate::components::omega::RAW)).is_err()); |
| 1144 | assert!(check_cudaplusplus(&dash(crate::components::cudaplusplus::RAW)).is_err()); |
| 1145 | assert!(check_research_status(&dash(crate::components::research_status::RAW)).is_err()); |
| 1146 | for bad in ["{", "[]", "{\"machines\": 1}"] { |
| 1147 | assert!(check_machines(bad).is_err(), "machines {bad}"); |
| 1148 | assert!(check_omega(bad).is_err(), "omega {bad}"); |
| 1149 | assert!(check_cudaplusplus(bad).is_err(), "cudaplusplus {bad}"); |
| 1150 | assert!(check_research_status(bad).is_err(), "research status {bad}"); |
| 1151 | assert!(check_progress(bad).is_err(), "progress {bad}"); |
| 1152 | } |
| 1153 | let status = crate::components::status::status_json(); |
| 1154 | assert!(check_status(&status.replacen("\"status\": \"", "\"status\": \"ALMOST", 1)).is_err()); |
| 1155 | assert!(check_status(&status.replace("\"BLOCKED\", ", "")).is_err()); |
| 1156 | assert!(check_status("{\"statuses\":[\"IMPLEMENTED\",\"QUALIFIED\",\"EXPERIMENTAL\",\"BLOCKED\",\"PLANNED\"],\"layers\":[{\"name\":\"x\",\"status\":\"PLANNED\",\"note\":\"n\",\"receipt\":\"http://x\"}]}").is_err()); |
| 1157 | } |
| 1158 | |
| 1159 | #[test] |
| 1160 | fn published_page_list_must_match_the_rust_registry() { |
| 1161 | let row = |p: &str| format!("{{\"path\":\"{p}\",\"title\":\"T\",\"description\":\"D\",\"english\":\"{p}\"}}"); |
| 1162 | let all: Vec<String> = all_pages().iter().map(|p| row(p)).collect(); |
| 1163 | check_pages_json(&format!("[{}]", all.join(","))).unwrap(); |
| 1164 | let short = &all[..all.len() - 1]; |
| 1165 | assert!(check_pages_json(&format!("[{}]", short.join(","))).is_err(), "a dropped page"); |
| 1166 | let mut extra = all.clone(); |
| 1167 | extra.push(row("/unlisted/")); |
| 1168 | assert!(check_pages_json(&format!("[{}]", extra.join(","))).is_err(), "an unlisted page"); |
| 1169 | let mut twice = short.to_vec(); |
| 1170 | twice.push(all[0].clone()); |
| 1171 | assert!(check_pages_json(&format!("[{}]", twice.join(","))).is_err(), "a page twice"); |
| 1172 | assert!(check_pages_json(&format!("[{}]", all.join(",").replacen("\"title\":\"T\"", "\"title\":\" \"", 1))).is_err(), "an empty title"); |
| 1173 | assert!(check_pages_json(&format!("[{}]", all.join(",").replacen("\"english\":\"/\"", "\"english\":\"/x/\"", 1))).is_err(), "a wrong English page"); |
| 1174 | assert!(check_pages_json("{}").is_err()); |
| 1175 | } |
| 1176 | |
| 1177 | #[test] |
| 1178 | fn redirect_stub_forwards_to_a_written_page() { |
| 1179 | let stub = "<meta name=\"robots\" content=\"noindex\"><meta http-equiv=\"refresh\" content=\"0; url=/aien/\"><script src=\"/js/redirect.js\" data-to=\"/aien/\"></script><a href=\"/aien/\">"; |
| 1180 | let written: BTreeSet<&str> = ["/aien/"].into_iter().collect(); |
| 1181 | check_redirect("/aien/", stub, &written).unwrap(); |
| 1182 | assert!(check_redirect("/aien/", stub, &BTreeSet::new()).is_err(), "a target that was not written"); |
| 1183 | assert!(check_redirect("/aien/", &stub.replace("noindex", "index"), &written).is_err(), "an indexed stub"); |
| 1184 | assert!(check_redirect("/aien/", &stub.replace("url=/aien/", "url=/x/"), &written).is_err(), "a refresh elsewhere"); |
| 1185 | assert!(check_redirect("/aien/", &stub.replace("data-to=\"/aien/\"", ""), &written).is_err(), "no scripted forward"); |
| 1186 | } |
| 1187 | |
| 1188 | #[test] |
| 1189 | fn data_index_must_list_exactly_the_data_files() { |
| 1190 | let entry = |p: &str| format!("{{\"path\":\"{p}\",\"url\":\"{HOST}{p}\"}}"); |
| 1191 | let all: Vec<String> = DATA_FILES.iter().map(|d| entry(d.path)).collect(); |
| 1192 | check_data_index(&format!("{{\"files\":[{}]}}", all.join(","))).unwrap(); |
| 1193 | let short = &all[..all.len() - 1]; |
| 1194 | assert!(check_data_index(&format!("{{\"files\":[{}]}}", short.join(","))).is_err()); |
| 1195 | let mut swapped = short.to_vec(); |
| 1196 | swapped.push(entry("/data/secret.tsv")); |
| 1197 | assert!(check_data_index(&format!("{{\"files\":[{}]}}", swapped.join(","))).is_err(), "same length, different set"); |
| 1198 | let wrong_url = all.join(",").replacen(HOST, "https://aienos.com", 1); |
| 1199 | assert!(check_data_index(&format!("{{\"files\":[{wrong_url}]}}")).is_err()); |
| 1200 | } |
| 1201 | } |