~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
183 lines · 6.7 KB Raw History
//! What a person wrote, marked as Bluesky's app marks a post's text: its
//! links, its mentions (an @handle, made the DID it names) and its tags,
//! each by its UTF-8 byte range, as `app.bsky.richtext.facet`s, which a
//! Grain comment's facets are too. Each is a word, apart by whitespace, an
//! opening bracket before it and punctuation after it left out. A link is an
//! http(s) URL with a dotted host, or a bare domain (`grain.social/explore`)
//! as `https://` and it: dotted labels of letters, digits and inner hyphens,
//! the last a top-level domain on IANA's list (`tlds.rs`, written by
//! scripts/tlds.mjs), then nothing or a path, query or fragment.

mod tlds;

use serde_json::{Value, json};

/// A part of the text to mark: its byte range and what it is.
#[derive(Debug, PartialEq)]
pub struct Mark {
    pub start: usize,
    pub end: usize,
    pub kind: Kind,
}

#[derive(Debug, PartialEq)]
pub enum Kind {
    /// An http(s) URL.
    Link(String),
    /// A handle, without its @, to be made a DID.
    Mention(String),
    /// A tag, without its #.
    Tag(String),
}

/// The longest tag Bluesky's app marks, in characters.
const TAG_MAX: usize = 64;

/// The links, mentions and tags of `text`, in its order.
pub fn marks(text: &str) -> Vec<Mark> {
    words(text)
        .filter_map(|(start, word)| mark(start, word))
        .collect()
}

/// Each word of `text` with its byte offset: runs between whitespace.
fn words(text: &str) -> impl Iterator<Item = (usize, &str)> {
    let mut at = 0;
    text.split(char::is_whitespace).filter_map(move |w| {
        let start = at;
        at += w.len()
            + text[at + w.len()..]
                .chars()
                .next()
                .map_or(0, char::len_utf8);
        (!w.is_empty()).then_some((start, w))
    })
}

fn mark(start: usize, word: &str) -> Option<Mark> {
    // An opening bracket before it, punctuation after it, are the
    // sentence's: "(see https://a.example)." marks the URL alone.
    let lead = word.len() - word.trim_start_matches(['(', '[', '"', '\'']).len();
    let word = &word[lead..];
    let start = start + lead;
    let trimmed = word.trim_end_matches(['.', ',', ';', ':', '!', '?', ')', ']', '"', '\'']);
    let at = |len: usize, kind| {
        Some(Mark {
            start,
            end: start + len,
            kind,
        })
    };
    if let Some(handle) = trimmed.strip_prefix('@') {
        let handle = handle.to_ascii_lowercase();
        return atproto::syntax::is_handle(&handle)
            .then_some(())
            .and_then(|()| at(trimmed.len(), Kind::Mention(handle)));
    }
    if let Some(tag) = trimmed
        .strip_prefix('#')
        .or_else(|| trimmed.strip_prefix('#'))
    {
        let n = tag.chars().count();
        let ok = (1..=TAG_MAX).contains(&n)
            && !tag.contains(['#', '#'])
            && !tag.chars().all(|c| c.is_ascii_digit());
        return ok
            .then_some(())
            .and_then(|()| at(trimmed.len(), Kind::Tag(tag.to_string())));
    }
    if trimmed.starts_with("https://") || trimmed.starts_with("http://") {
        let url = url::Url::parse(trimmed).ok()?;
        url.host_str().filter(|h| h.contains('.'))?;
        return at(trimmed.len(), Kind::Link(trimmed.to_string()));
    }
    is_bare_domain(trimmed)
        .then_some(())
        .and_then(|()| at(trimmed.len(), Kind::Link(format!("https://{trimmed}"))))
}

/// Whether `word` is a domain written without its scheme, as Bluesky's app
/// links one: dotted labels of letters, digits and inner hyphens, the last a
/// top-level domain, up to a path, query or fragment if any. `a@b.com`,
/// `node.js` and `1.2.3` are none.
fn is_bare_domain(word: &str) -> bool {
    let host = word.split(['/', '?', '#']).next().unwrap_or_default();
    let last = host.rsplit('.').next().unwrap_or_default();
    host.contains('.')
        && host.split('.').all(|label| {
            (1..=63).contains(&label.len())
                && !label.starts_with('-')
                && !label.ends_with('-')
                && label
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'-')
        })
        && tlds::TLDS
            .binary_search_by(|tld| {
                tld.bytes()
                    .cmp(last.bytes().map(|b| b.to_ascii_lowercase()))
            })
            .is_ok()
}

/// A mark as an `app.bsky.richtext.facet`, its mention's DID given.
pub fn facet(mark: &Mark, did: Option<&str>) -> Option<Value> {
    let feature = match &mark.kind {
        Kind::Link(uri) => json!({ "$type": "app.bsky.richtext.facet#link", "uri": uri }),
        Kind::Mention(_) => json!({ "$type": "app.bsky.richtext.facet#mention", "did": did? }),
        Kind::Tag(tag) => json!({ "$type": "app.bsky.richtext.facet#tag", "tag": tag }),
    };
    Some(
        json!({ "index": { "byteStart": mark.start, "byteEnd": mark.end }, "features": [feature] }),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The table every copy of the rule is tested against, HUDKit's fixture.
    const CASES: &str =
        include_str!("../../../ios/HUDKit/Tests/HUDKitTests/Fixtures/richtext.json");

    #[test]
    fn marks_as_every_copy_of_the_rule_does() {
        let table: Value = serde_json::from_str(CASES).unwrap();
        for case in table["cases"].as_array().unwrap() {
            let text = case["text"].as_str().unwrap();
            let found: Vec<Value> = marks(text)
                .iter()
                .map(|m| {
                    let (kind, value) = match &m.kind {
                        Kind::Link(v) => ("link", v),
                        Kind::Mention(v) => ("mention", v),
                        Kind::Tag(v) => ("tag", v),
                    };
                    // Byte offsets, not characters: é is two bytes.
                    json!({ "text": &text[m.start..m.end], "kind": kind, "value": value, "byteStart": m.start })
                })
                .collect();
            assert_eq!(Value::from(found), case["marks"], "{text}");
        }
    }

    #[test]
    fn a_mark_as_a_facet() {
        let found = marks("héllo @Alice.test grain.social");
        assert_eq!(
            facet(&found[0], Some("did:plc:alice")),
            Some(json!({ "index": { "byteStart": 7, "byteEnd": 18 },
                "features": [{ "$type": "app.bsky.richtext.facet#mention", "did": "did:plc:alice" }] }))
        );
        assert_eq!(
            facet(&found[0], None),
            None,
            "a handle that resolves to no DID is not marked"
        );
        assert_eq!(
            facet(&found[1], None),
            Some(json!({ "index": { "byteStart": 19, "byteEnd": 31 },
                "features": [{ "$type": "app.bsky.richtext.facet#link", "uri": "https://grain.social" }] }))
        );
    }
}