//! Pure URL helpers — the Reader tool's only "parsing" surface. The port of //! `packages/core/src/engine/urls.ts`. //! //! Cotton accepts ONLY absolute http(s) URLs; bare domains ("example.com") are //! deliberately not promoted to URLs — that would turn the share sheet into a //! typing surface by the back door. //! //! These live in the DOMAIN layer rather than app-side because whoever creates //! a page must derive `host` itself, and a service cannot import from an app. //! One home, every caller — the alternative was a second copy, which is exactly //! the duplication that once shipped two disagreeing day-state functions. use std::sync::LazyLock; use regex::Regex; /// The ECMAScript whitespace class, spelled out. /// /// JavaScript's `\s` and Rust's are NOT the same set — JS includes U+FEFF and /// excludes U+0085, Rust's `\s` does the opposite — and this class decides /// where a shared URL ends inside a sentence. Spelling it out is the only way /// the two implementations cut the same string. const JS_SPACE: &str = r"\t\x0B\x0C \u{00A0}\u{FEFF}\p{Zs}\n\r\u{2028}\u{2029}"; static URL_RE: LazyLock = LazyLock::new(|| { Regex::new(&format!("(?i)https?://[^{JS_SPACE}<>\"'`]+")).expect("a valid pattern") }); /// Trailing punctuation that belongs to the sentence, not the URL. static TRAILING_PUNCT_RE: LazyLock = LazyLock::new(|| Regex::new("[.,;:!?'\"`]+$").expect("a valid pattern")); static HAS_HOST_RE: LazyLock = LazyLock::new(|| Regex::new(r"(?i)^https?://[^/]+").expect("a valid pattern")); static HOST_RE: LazyLock = LazyLock::new(|| Regex::new(r"(?i)^https?://([^/?#]+)").expect("a valid pattern")); static PORT_RE: LazyLock = LazyLock::new(|| Regex::new(r":\d+$").expect("a valid pattern")); static CANONICAL_RE: LazyLock = LazyLock::new(|| Regex::new(r"(?is)^(https?)://([^/?#]*)(.*)$").expect("a valid pattern")); fn js_trim(text: &str) -> &str { text.trim_matches(cotton_store::protocol::js::is_js_whitespace) } /// Closing brackets are stripped only when UNBALANCED (a "(…)" wrapper), so /// URLs with real parens — Wikipedia's "(disambiguation)" paths — survive. fn strip_trailing(candidate: &str) -> String { let mut url = TRAILING_PUNCT_RE.replace(candidate, "").into_owned(); let pairs = [('(', ')'), ('[', ']'), ('{', '}')]; let mut changed = true; while changed { changed = false; for (open, close) in pairs { if url.ends_with(close) { let opens = url.matches(open).count(); let closes = url.matches(close).count(); if closes > opens { // `slice(0, -1)` is one UTF-16 code unit, and the character // being dropped is always the ASCII bracket just matched. url.pop(); url = TRAILING_PUNCT_RE.replace(&url, "").into_owned(); changed = true; } } } } url } /// Every http(s) URL in a blob of text, deduped, order preserved. pub fn extract_urls(text: Option<&str>) -> Vec { let Some(text) = text.filter(|t| !t.is_empty()) else { return Vec::new(); }; let mut out: Vec = Vec::new(); for found in URL_RE.find_iter(text) { let url = strip_trailing(found.as_str()); // A bare scheme ("https://") or scheme+punctuation is not a URL. if !HAS_HOST_RE.is_match(&url) { continue; } if !out.contains(&url) { out.push(url); } } out } /// True when `raw` is a single absolute http(s) URL (after trimming). pub fn is_http_url(raw: Option<&str>) -> bool { let Some(raw) = raw.filter(|r| !r.is_empty()) else { return false; }; let trimmed = js_trim(raw); let urls = extract_urls(Some(trimmed)); urls.len() == 1 && urls[0] == trimmed } /// Display host for a saved page: no scheme, no www, no port. pub fn host_of(url: &str) -> String { let trimmed = js_trim(url); let Some(caps) = HOST_RE.captures(trimmed) else { return String::new(); }; let mut host = caps[1].to_string(); // Strip userinfo. if let Some(at) = host.rfind('@') { host = host[at + 1..].to_string(); } host = PORT_RE.replace(&host, "").to_lowercase(); match host.strip_prefix("www.") { Some(rest) => rest.to_string(), None => host, } } /// Storage form of a page URL: scheme and authority lowercased, path/query/ /// fragment untouched (they are case-significant). /// /// Exists because iOS auto-capitalisation turns a composer-typed URL into /// "HTTPS://…", which WKWebView then refuses to load — found on-device /// 2026-08-14. Every write path stores through this; [`host_of`] already /// lowercases independently. pub fn canonical_url(url: &str) -> String { let trimmed = js_trim(url); let Some(caps) = CANONICAL_RE.captures(trimmed) else { return trimmed.to_string(); }; format!( "{}://{}{}", caps[1].to_lowercase(), caps[2].to_lowercase(), &caps[3] ) } #[cfg(test)] #[path = "urls_tests.rs"] mod tests;