//! Forgiving lookups for the registry tools.
//!
//! Agents often pass a near miss for a registry name: a different case,
//! spaces instead of hyphens, a package's short name, a capability name where
//! a skill is expected, or a platform where a template is expected. A lookup
//! that finds nothing is a successful answer ("there is no such item, here
//! are the valid names"), not a tool failure, so these helpers return either
//! the registry name to use or a complete answer to send back.
//!
//! Resolution order, first step with any match wins:
//! 1. the exact name;
//! 2. the same name ignoring case and separators (`Mesh Networking`,
//! `nearby_chat`), or an item's title;
//! 3. a package's short name (`mesh-sdk` -> `@offline-protocol/mesh-sdk`);
//! 4. a capability name -> the skills, workflows or packages that cover it;
//! 5. aliases: a platform or workflow -> its starter templates, a template
//! -> its workflow, a package or workflow -> its skills, a platform -> its
//! packages and guides.
//!
//! One match resolves (with a `note` saying what was resolved); several
//! matches are listed; none gives the closest names and the full list.
use offline_registry::{
platform_label, unsupported_framework, Registry, CLI_NPM_PACKAGE, PACKAGE_ONLY_PLATFORMS,
};
use serde_json::{json, Value};
/// Platform values the tool schemas accept.
pub const PLATFORM_ENUM: &[&str] = &[
"react-native",
"nextjs",
"react-vite",
"web",
"rust",
"python",
"java",
];
/// Aliases accepted for each platform value, in normalized form (see [`key`]).
const PLATFORM_ALIASES: &[(&str, &[&str])] = &[
(
"react-native",
&[
"react-native",
"reactnative",
"rn",
"mobile",
"ios",
"android",
],
),
("react-vite", &["react-vite", "vite", "react"]),
("nextjs", &["nextjs", "next", "next-js"]),
("web", &["web", "browser"]),
("rust", &["rust", "cargo", "crates"]),
("python", &["python", "py", "python3", "pypi"]),
("java", &["java", "jvm", "jdk", "kotlin-jvm"]),
// Package-only platforms: packages, no workflow plans or templates.
(
"ios-native",
&[
"ios-native",
"native-ios",
"swift",
"swiftui",
"swiftpm",
"swift-package",
],
),
(
"android-native",
&[
"android-native",
"native-android",
"kotlin",
"android-kotlin",
"jetpack-compose",
"jetpack",
],
),
(
"embedded",
&[
"embedded",
"esp32",
"firmware",
"microcontroller",
"mcu",
"leaf",
],
),
("flutter", &["flutter", "dart"]),
("c", &["c", "c-api", "capi", "c-binding"]),
("ruby", &["ruby", "rb", "rubygems"]),
(
"csharp",
&["csharp", "c-sharp", "dotnet", "net", "net8", "cs", "c-net"],
),
];
/// Where the supported platforms and transports are documented.
pub const PLATFORMS_DOCS: &str = "https://www.offlineprotocol.com/docs/getting-started/platforms";
const SCOPE: &str = "offline-protocol-";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Skill,
Package,
Workflow,
Template,
}
impl Kind {
pub fn noun(self) -> &'static str {
match self {
Kind::Skill => "skill",
Kind::Package => "package",
Kind::Workflow => "workflow",
Kind::Template => "template",
}
}
fn tool(self) -> &'static str {
match self {
Kind::Skill => "get_skill",
Kind::Package => "get_package",
Kind::Workflow => "get_workflow",
Kind::Template => "get_template",
}
}
}
/// The outcome of a lookup.
#[derive(Debug)]
pub enum Lookup {
/// Use this registry name. `note` is set when the input was not the
/// exact name.
Found { name: String, note: Option<String> },
/// Send this answer back as the tool result: several matches, no match,
/// or a name that is not a registry item (the CLI package).
Answer(Value),
}
/// Normalized form for comparisons: lowercase, every run of characters other
/// than letters and digits becomes one `-`, no leading or trailing `-`.
pub fn key(s: &str) -> String {
let mut out = String::new();
for c in s.trim().chars() {
if c.is_alphanumeric() {
out.extend(c.to_lowercase());
} else if !out.is_empty() && !out.ends_with('-') {
out.push('-');
}
}
while out.ends_with('-') {
out.pop();
}
out
}
struct Candidate {
name: String,
/// Normalized names that match this item in step 2.
keys: Vec<String>,
}
fn candidates(registry: &Registry, kind: Kind) -> Vec<Candidate> {
match kind {
Kind::Skill => registry
.skills()
.map(|s| Candidate {
name: s.name.clone(),
keys: vec![key(&s.name), key(&s.title)],
})
.collect(),
Kind::Package => registry
.packages()
.map(|p| Candidate {
name: p.name.clone(),
keys: std::iter::once(&p.name)
.chain(&p.aliases)
.map(|n| key(n))
.collect(),
})
.collect(),
Kind::Workflow => registry
.workflows()
.map(|w| Candidate {
name: w.name.clone(),
keys: vec![key(&w.name), key(&w.title)],
})
.collect(),
Kind::Template => registry
.templates()
.map(|t| Candidate {
name: t.name.clone(),
keys: vec![key(&t.name), key(&t.title)],
})
.collect(),
}
}
fn exists(registry: &Registry, kind: Kind, name: &str) -> bool {
match kind {
Kind::Skill => registry.skill(name).is_some(),
Kind::Package => registry.package(name).is_some(),
Kind::Workflow => registry.workflow(name).is_some(),
Kind::Template => registry.template(name).is_some(),
}
}
/// A package name without a trailing `@version` (`@scope/name@1.2.3`).
fn strip_version(input: &str) -> &str {
let s = input.trim();
match s.char_indices().skip(1).find(|(_, c)| *c == '@') {
Some((i, _)) => &s[..i],
None => s,
}
}
/// A package's unscoped name keys: `mesh-sdk` and `mesh`.
fn package_short_keys(name: &str) -> Vec<String> {
let short = key(name.rsplit('/').next().unwrap_or(name));
let mut keys = vec![short.clone()];
if let Some(base) = short.strip_suffix("-sdk") {
keys.push(base.to_string());
}
keys
}
/// Resolve `input` to a registry item of `kind`.
pub fn lookup(registry: &Registry, kind: Kind, input: &str) -> Lookup {
if exists(registry, kind, input) {
return Lookup::Found {
name: input.to_string(),
note: None,
};
}
let raw = if kind == Kind::Package {
strip_version(input)
} else {
input.trim()
};
if exists(registry, kind, raw) {
return found(input, raw, None);
}
let q = key(raw);
let all = candidates(registry, kind);
// 2. Case, separators and titles.
let step: Vec<String> = all
.iter()
.filter(|c| !q.is_empty() && c.keys.contains(&q))
.map(|c| c.name.clone())
.collect();
if let Some(answer) = settle(registry, kind, input, step, None) {
return answer;
}
// 3. Package short names, and the CLI, which is not an SDK package.
if kind == Kind::Package {
let unscoped = q.strip_prefix(SCOPE).unwrap_or(&q).to_string();
if matches!(unscoped.as_str(), "cli" | "offline-cli") {
return Lookup::Answer(cli_package_answer(input));
}
let step: Vec<String> = all
.iter()
.filter(|c| !unscoped.is_empty() && package_short_keys(&c.name).contains(&unscoped))
.map(|c| c.name.clone())
.collect();
if let Some(answer) = settle(registry, kind, input, step, None) {
return answer;
}
}
// 4. A capability name.
if kind != Kind::Template {
if let Some(cap) = registry
.capabilities()
.into_iter()
.find(|c| key(&c.name) == q)
{
let names = match kind {
Kind::Skill => cap.skills.clone(),
Kind::Workflow => cap.workflows.clone(),
Kind::Package => cap.packages.clone(),
Kind::Template => Vec::new(),
};
let why = if names.len() == 1 {
format!(
"`{}` is a capability, not a {noun} name; this {noun} covers it",
cap.name,
noun = kind.noun()
)
} else {
format!(
"`{}` is a capability, not a {noun} name; these {noun}s cover it",
cap.name,
noun = kind.noun()
)
};
if let Some(answer) = settle(registry, kind, input, names, Some(why)) {
return answer;
}
}
}
// A platform with packages but no starter templates.
if kind == Kind::Template {
if let Some(platforms) = platform_alias(&q) {
if !registry
.templates()
.any(|t| platforms.contains(&t.platform.as_str()))
{
return Lookup::Answer(no_template_platform_answer(registry, input, platforms[0]));
}
}
}
// 5. Aliases.
let (names, why) = aliases(registry, kind, &q);
if let Some(answer) = settle(registry, kind, input, names, why) {
return answer;
}
Lookup::Answer(unknown_answer(registry, kind, input, &q, &all))
}
/// One match resolves, several are listed, none continues.
fn settle(
registry: &Registry,
kind: Kind,
input: &str,
mut names: Vec<String>,
why: Option<String>,
) -> Option<Lookup> {
names.dedup();
let mut seen = Vec::new();
names.retain(|n| {
let fresh = !seen.contains(n);
seen.push(n.clone());
fresh
});
match names.len() {
0 => None,
1 => Some(found(input, &names[0], why)),
_ => Some(Lookup::Answer(several_answer(
registry, kind, input, &names, why,
))),
}
}
fn found(input: &str, name: &str, why: Option<String>) -> Lookup {
let note = match why {
Some(why) => format!("resolved `{}` to `{name}`: {why}", input.trim()),
None => format!("resolved `{}` to `{name}`", input.trim()),
};
Lookup::Found {
name: name.to_string(),
note: Some(note),
}
}
/// Step 5 for each kind.
fn aliases(registry: &Registry, kind: Kind, q: &str) -> (Vec<String>, Option<String>) {
if q.is_empty() {
return (Vec::new(), None);
}
match kind {
Kind::Template => {
if let Some(platforms) = platform_alias(q) {
let names: Vec<String> = registry
.templates()
.filter(|t| platforms.contains(&t.platform.as_str()))
.map(|t| t.name.clone())
.collect();
let label = platforms.join(" and ");
return (
names,
Some(format!(
"`{q}` names a platform; starter templates for {label}"
)),
);
}
if let Some(wf) = registry
.workflows()
.find(|w| key(&w.name) == q || key(&w.title) == q)
{
return (
wf.templates.values().cloned().collect(),
Some(format!("starter template for the `{}` workflow", wf.name)),
);
}
let needle = format!("-{q}-");
let names = registry
.templates()
.filter(|t| q.len() >= 3 && format!("-{}-", t.name).contains(&needle))
.map(|t| t.name.clone())
.collect();
(names, None)
}
Kind::Workflow => {
let names = registry
.templates()
.filter(|t| key(&t.name) == q || key(&t.title) == q)
.filter_map(|t| t.workflow.clone())
.collect::<Vec<_>>();
(
names,
Some(format!("`{q}` is a starter template; this is its workflow")),
)
}
Kind::Skill => {
let unscoped = q.strip_prefix(SCOPE).unwrap_or(q);
if let Some(pkg) = registry.packages().find(|p| {
key(&p.name) == q || package_short_keys(&p.name).contains(&unscoped.to_string())
}) {
return (
pkg.skills.clone(),
Some(format!("`{}` is a package; guides for it", pkg.name)),
);
}
if let Some(wf) = registry
.workflows()
.find(|w| (key(&w.name) == q || key(&w.title) == q) && !w.skills.is_empty())
{
return (
wf.skills.clone(),
Some(format!("`{}` is a workflow; guides for it", wf.name)),
);
}
if let Some(platforms) = package_platforms(q) {
// The platform's packages list their guides in reading
// order; other guides for the platform follow.
let on_platform =
|list: &[String]| list.iter().any(|p| platforms.contains(&p.as_str()));
let mut names: Vec<String> = registry
.packages()
.filter(|p| on_platform(&p.platforms))
.flat_map(|p| p.skills.iter().cloned())
.collect();
names.extend(
registry
.skills()
.filter(|s| on_platform(&s.platforms))
.map(|s| s.name.clone()),
);
return (
names,
Some(format!(
"`{q}` names a platform; guides for {}",
platform_label(platforms[0])
)),
);
}
(Vec::new(), None)
}
Kind::Package => match package_platforms(q) {
Some(platforms) => (
registry
.packages()
.filter(|p| p.platforms.iter().any(|x| platforms.contains(&x.as_str())))
.map(|p| p.name.clone())
.collect(),
Some(format!(
"`{q}` names a platform; packages for {}",
platform_label(platforms[0])
)),
),
None => (Vec::new(), None),
},
}
}
/// The platform value a normalized alias names, if any.
fn package_platform(q: &str) -> Option<&'static str> {
PLATFORM_ALIASES
.iter()
.find(|(_, aliases)| aliases.contains(&q))
.map(|(value, _)| *value)
}
/// Platform values packages and guides list for a platform alias. `web`
/// covers both web stacks and the packages that say `web`.
fn package_platforms(q: &str) -> Option<Vec<&'static str>> {
Some(match package_platform(q)? {
"web" => vec!["web", "nextjs", "react-vite"],
v => vec![v],
})
}
/// A platform with packages but no starter templates.
fn no_template_platform_answer(registry: &Registry, input: &str, platform: &str) -> Value {
let packages: Vec<String> = registry
.packages()
.filter(|p| p.platforms.iter().any(|x| x == platform))
.map(|p| p.name.clone())
.collect();
json!({
"found": false,
"kind": "template",
"query": input,
"message": format!(
"There is no starter template for {}: the starter templates are React Native and React web apps. Install the {} package{} directly instead: {}.",
platform_label(platform),
platform_label(platform),
if packages.len() == 1 { "" } else { "s" },
packages.join(", ")
),
"packages": entries(registry, Kind::Package, &packages),
"validNames": registry.templates().map(|t| t.name.clone()).collect::<Vec<_>>(),
})
}
/// Platform values (as templates and workflows name them) for a platform
/// alias in normalized form. `web` covers both web stacks.
fn platform_alias(q: &str) -> Option<Vec<&'static str>> {
let (value, _) = PLATFORM_ALIASES
.iter()
.find(|(_, aliases)| aliases.contains(&q))?;
Some(match *value {
"web" => vec!["nextjs", "react-vite"],
v => vec![v],
})
}
/// First sentence of a description, at most about 160 characters.
pub fn one_line(description: &str) -> String {
let text = description.split_whitespace().collect::<Vec<_>>().join(" ");
let first = match text.find(". ") {
Some(i) => text[..=i].to_string(),
None => text,
};
if first.chars().count() <= 160 {
first
} else {
let cut: String = first.chars().take(157).collect();
format!("{}...", cut.trim_end())
}
}
fn description_of(registry: &Registry, kind: Kind, name: &str) -> String {
let d = match kind {
Kind::Skill => registry.skill(name).map(|s| s.description.as_str()),
Kind::Package => registry.package(name).map(|p| p.description.as_str()),
Kind::Workflow => registry.workflow(name).map(|w| w.description.as_str()),
Kind::Template => registry.template(name).map(|t| t.description.as_str()),
};
one_line(d.unwrap_or_default())
}
fn entries(registry: &Registry, kind: Kind, names: &[String]) -> Vec<Value> {
names
.iter()
.map(|n| json!({"name": n, "description": description_of(registry, kind, n)}))
.collect()
}
fn several_answer(
registry: &Registry,
kind: Kind,
input: &str,
names: &[String],
why: Option<String>,
) -> Value {
let why = why.map(|w| format!(" ({w})")).unwrap_or_default();
json!({
"found": false,
"kind": kind.noun(),
"query": input,
"message": format!(
"Several matches: `{}` matches {} {}s{why}: {}. Call {} again with one of these names.",
input.trim(),
names.len(),
kind.noun(),
names.join(", "),
kind.tool()
),
"matches": entries(registry, kind, names),
})
}
fn levenshtein(a: &str, b: &str) -> usize {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
let mut prev: Vec<usize> = (0..=b.len()).collect();
for (i, ca) in a.iter().enumerate() {
let mut cur = vec![i + 1; b.len() + 1];
for (j, cb) in b.iter().enumerate() {
let cost = usize::from(ca != cb);
cur[j + 1] = (prev[j] + cost).min(prev[j + 1] + 1).min(cur[j] + 1);
}
prev = cur;
}
prev[b.len()]
}
fn similarity(a: &str, b: &str) -> f32 {
let longest = a.chars().count().max(b.chars().count());
if longest == 0 {
return 0.0;
}
1.0 - levenshtein(a, b) as f32 / longest as f32
}
/// Up to three names closest to `q`: near spellings first, then keyword
/// search hits, then looser spellings.
fn closest(
registry: &Registry,
kind: Kind,
input: &str,
q: &str,
all: &[Candidate],
) -> Vec<String> {
let mut scored: Vec<(f32, &str)> = all
.iter()
.map(|c| {
let mut keys = c.keys.clone();
if kind == Kind::Package {
keys.extend(package_short_keys(&c.name));
}
let best = keys
.iter()
.map(|k| {
let s = similarity(q, k);
let contains = q.len() >= 3 && (k.contains(q) || q.contains(k.as_str()));
if contains {
s.max(0.6)
} else {
s
}
})
.fold(0.0_f32, f32::max);
(best, c.name.as_str())
})
.collect();
scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
let hits: Vec<String> = match kind {
Kind::Skill => registry.search_skills(input),
Kind::Package => registry.search_packages(input),
Kind::Workflow => registry.search_workflows(input),
Kind::Template => Vec::new(),
}
.into_iter()
.map(|h| h.name)
.collect();
let mut out: Vec<String> = Vec::new();
let push = |name: &str, out: &mut Vec<String>| {
if out.len() < 3 && !out.iter().any(|n| n == name) {
out.push(name.to_string());
}
};
for (score, name) in &scored {
if *score >= 0.6 {
push(name, &mut out);
}
}
for name in &hits {
push(name, &mut out);
}
for (score, name) in &scored {
if *score >= 0.5 {
push(name, &mut out);
}
}
out
}
fn unknown_answer(
registry: &Registry,
kind: Kind,
input: &str,
q: &str,
all: &[Candidate],
) -> Value {
let close = closest(registry, kind, input, q, all);
let valid: Vec<&str> = all.iter().map(|c| c.name.as_str()).collect();
let closest_text = if close.is_empty() {
"No name is close.".to_string()
} else {
format!("Closest matches: {}.", close.join(", "))
};
json!({
"found": false,
"kind": kind.noun(),
"query": input,
"message": format!(
"There is no Offline Protocol {} named `{}`. {closest_text} Valid {} names: {}.",
kind.noun(),
input.trim(),
kind.noun(),
valid.join(", ")
),
"closestMatches": entries(registry, kind, &close),
"validNames": valid,
})
}
/// `@offline-protocol/cli` ships the `offline` command and this MCP server;
/// it is not an SDK package an app depends on.
fn cli_package_answer(input: &str) -> Value {
json!({
"supported": false,
"query": input,
"reason": format!(
"`{CLI_NPM_PACKAGE}` is the Offline Protocol CLI (the `offline` command and the local MCP server), not an SDK package an app installs, so it is not in the package registry."
),
"cli": {
"package": CLI_NPM_PACKAGE,
"version": offline_registry::CLI_VERSION,
"run": offline_registry::mcp_serve_command_line(),
},
"alternatives": [
{"description": "SDK packages an app installs: @offline-protocol/mesh-sdk (React Native mesh networking), @offline-protocol/id-react-native and @offline-protocol/id-react (Offline ID), @offline-protocol/pol (proof of location), offline-protocol-sdk (Python, on PyPI), offline-protocol (Rust crate), offline-protocol-java (Java, on Maven Central), offline-protocol-ruby (Ruby, on RubyGems), offline-protocol-c (the C API, a release download), offline-protocol-web (the browser engine, experimental), and the previews offline-protocol-swift (Swift package), offline-protocol-android (Android library on Maven Central), offline-protocol-flutter (Flutter plugin, from source) and offline-protocol-csharp (C# for .NET, from source)."}
],
})
}
/// How a `platform` argument maps to a schema value.
#[derive(Debug, PartialEq, Eq)]
pub enum PlatformInput {
/// One of [`PLATFORM_ENUM`], exactly as given.
Exact,
/// An alias of this schema value, with a note for the result.
Alias(&'static str, String),
/// A framework no Offline Protocol package supports (display name).
Unsupported(&'static str),
/// Nothing it could mean.
Unknown,
}
pub fn classify_platform(input: &str) -> PlatformInput {
if PLATFORM_ENUM.contains(&input) {
return PlatformInput::Exact;
}
// `key` drops the `#`, which would read "C#" as the C API.
let lowered = input.trim().to_lowercase();
let q = if lowered.starts_with("c#") {
"csharp".to_string()
} else {
key(input)
};
if let Some((value, _)) = PLATFORM_ALIASES
.iter()
.find(|(_, aliases)| aliases.contains(&q.as_str()))
{
let note = match q.as_str() {
"ios" | "android" | "mobile" => format!(
"platform `{}` read as `react-native`: React Native (@offline-protocol/mesh-sdk) is the supported way to build for iOS and Android; the native packages are early previews (platform `swift` for the Swift package, `kotlin` for the Android library, `flutter` for the Flutter plugin)",
input.trim()
),
_ if PACKAGE_ONLY_PLATFORMS.contains(value) => format!(
"platform `{}` read as `{value}` ({}): packages only, with no workflow plans or starter templates",
input.trim(),
platform_label(value)
),
"browser" => format!(
"platform `{}` read as `web`",
input.trim()
),
_ => format!("platform `{}` read as `{value}`", input.trim()),
};
return PlatformInput::Alias(value, note);
}
match unsupported_framework(input) {
Some(framework) => PlatformInput::Unsupported(framework),
None => PlatformInput::Unknown,
}
}
/// The aliases [`classify_platform`] accepts, for error messages.
pub const PLATFORM_ALIAS_HELP: &str = "Also accepted: ios, android, mobile and rn (react-native), react and vite (react-vite), next (nextjs), browser (web), py and python3 (python), jvm and kotlin-jvm (java), and the package-only platforms swift (ios-native), kotlin (android-native), esp32 (embedded), flutter, c, ruby and csharp (c#, dotnet), which have packages but no starter templates.";
/// The message for a platform value that maps to nothing.
pub fn unknown_platform_message(input: &str) -> String {
format!(
"Unknown platform `{}`. Valid platforms: {}. {PLATFORM_ALIAS_HELP}",
input.trim(),
PLATFORM_ENUM.join(", ")
)
}
/// A platform or framework no package supports.
pub fn unsupported_platform_answer(input: &str, framework: &str, plan: bool) -> Value {
let reason = format!(
"There is no Offline Protocol package for {framework}. The packages target React Native (@offline-protocol/mesh-sdk, id-react-native, pol), React web apps (@offline-protocol/id-react, pol), Python (offline-protocol-sdk), Rust (offline-protocol), Java (offline-protocol-java), Ruby (offline-protocol-ruby), C (offline-protocol-c), the browser (offline-protocol-web, experimental) and, as previews, native Swift (offline-protocol-swift), Kotlin (offline-protocol-android), Flutter (offline-protocol-flutter) and C# (offline-protocol-csharp), so a {framework} integration is not available."
);
let mut answer = json!({"supported": false});
if plan {
answer["planGenerated"] = json!(false);
answer["reason"] = json!(format!("no plan generated: {reason}"));
} else {
answer["reason"] = json!(reason);
}
answer["requestedPlatform"] = json!(input);
answer["supportedPlatforms"] = json!(PLATFORM_ENUM);
answer["alternatives"] = json!([{
"description": "React Native covers iOS and Android. If the user chooses React Native, call again with platform `react-native`.",
"arguments": {"platform": "react-native"},
}]);
answer["docs"] = json!(PLATFORMS_DOCS);
answer
}
#[cfg(test)]
mod tests {
use super::*;
fn reg() -> Registry {
Registry::load_embedded().unwrap()
}
fn found_name(l: Lookup) -> (String, Option<String>) {
match l {
Lookup::Found { name, note } => (name, note),
Lookup::Answer(v) => panic!("expected a match, got {v}"),
}
}
fn answer(l: Lookup) -> Value {
match l {
Lookup::Answer(v) => v,
Lookup::Found { name, .. } => panic!("expected an answer, got {name}"),
}
}
#[test]
fn key_normalizes_case_and_separators() {
assert_eq!(key("Mesh Networking"), "mesh-networking");
assert_eq!(key("nearby_chat"), "nearby-chat");
assert_eq!(
key("@offline-protocol/mesh-sdk"),
"offline-protocol-mesh-sdk"
);
assert_eq!(key(" React--Native "), "react-native");
}
#[test]
fn exact_names_resolve_without_a_note() {
let r = reg();
for (kind, name) in [
(Kind::Skill, "messaging"),
(Kind::Skill, "mesh-networking"),
(Kind::Package, "@offline-protocol/mesh-sdk"),
(Kind::Workflow, "nearby-chat"),
(Kind::Template, "react-native-mesh-app"),
] {
assert_eq!(found_name(lookup(&r, kind, name)), (name.to_string(), None));
}
// Every registry name resolves to itself.
for s in r.skills() {
assert_eq!(found_name(lookup(&r, Kind::Skill, &s.name)).1, None);
}
for p in r.packages() {
assert_eq!(found_name(lookup(&r, Kind::Package, &p.name)).1, None);
}
for w in r.workflows() {
assert_eq!(found_name(lookup(&r, Kind::Workflow, &w.name)).1, None);
}
for t in r.templates() {
assert_eq!(found_name(lookup(&r, Kind::Template, &t.name)).1, None);
}
}
#[test]
fn near_misses_resolve_with_a_note() {
let r = reg();
let cases = [
(Kind::Skill, "Mesh Networking", "mesh-networking"),
(Kind::Skill, "MESSAGING", "messaging"),
(Kind::Skill, "peer_discovery", "peer-discovery"),
(Kind::Skill, "offline-messaging", "messaging"),
(Kind::Skill, "group messaging", "groups"),
(Kind::Package, "mesh-sdk", "@offline-protocol/mesh-sdk"),
(Kind::Package, "id-react", "@offline-protocol/id-react"),
(Kind::Package, "mesh", "@offline-protocol/mesh-sdk"),
(
Kind::Package,
"@Offline-Protocol/Mesh-SDK",
"@offline-protocol/mesh-sdk",
),
(
Kind::Package,
"@offline-protocol/mesh-sdk@0.27.0",
"@offline-protocol/mesh-sdk",
),
(
Kind::Package,
"mesh-networking",
"@offline-protocol/mesh-sdk",
),
(Kind::Workflow, "nearby chat", "nearby-chat"),
(Kind::Workflow, "Nearby_Chat", "nearby-chat"),
(Kind::Workflow, "durable-handoff", "local-handoff"),
(Kind::Workflow, "react-native-mesh-handoff", "local-handoff"),
(Kind::Template, "nextjs", "nextjs-social"),
(Kind::Template, "vite", "react-vite-social"),
(Kind::Template, "local-handoff", "react-native-mesh-handoff"),
(
Kind::Template,
"React Native Mesh App",
"react-native-mesh-app",
),
(Kind::Template, "handoff", "react-native-mesh-handoff"),
];
for (kind, input, expected) in cases {
let (name, note) = found_name(lookup(&r, kind, input));
assert_eq!(name, expected, "{kind:?} {input}");
let note = note.unwrap_or_else(|| panic!("{input}: no note"));
assert!(
note.starts_with(&format!("resolved `{input}` to `{expected}`")),
"{note}"
);
}
let (_, note) = found_name(lookup(&r, Kind::Skill, "offline-messaging"));
assert!(note.unwrap().contains("is a capability"));
}
#[test]
fn ambiguous_inputs_list_every_match() {
let r = reg();
let v = answer(lookup(&r, Kind::Template, "react-native"));
assert_eq!(v["found"], false);
let names: Vec<&str> = v["matches"]
.as_array()
.unwrap()
.iter()
.map(|m| m["name"].as_str().unwrap())
.collect();
let rn: Vec<&str> = r
.templates()
.filter(|t| t.platform == "react-native")
.map(|t| t.name.as_str())
.collect();
assert_eq!(names, rn);
assert!(v["message"]
.as_str()
.unwrap()
.starts_with("Several matches:"));
for m in v["matches"].as_array().unwrap() {
assert!(!m["description"].as_str().unwrap().is_empty());
}
let v = answer(lookup(&r, Kind::Workflow, "offline-messaging"));
assert!(v["matches"].as_array().unwrap().len() > 1);
let v = answer(lookup(&r, Kind::Package, "identity"));
let names: Vec<&str> = v["matches"]
.as_array()
.unwrap()
.iter()
.map(|m| m["name"].as_str().unwrap())
.collect();
assert!(names.contains(&"@offline-protocol/id-react"));
assert!(names.contains(&"@offline-protocol/id-react-native"));
let v = answer(lookup(&r, Kind::Template, "web"));
assert_eq!(v["matches"].as_array().unwrap().len(), 2);
}
#[test]
fn unknown_names_answer_with_closest_and_valid_names() {
let r = reg();
let v = answer(lookup(&r, Kind::Skill, "mesh-netwrking-guide"));
assert_eq!(v["found"], false);
assert!(v["message"]
.as_str()
.unwrap()
.starts_with("There is no Offline Protocol skill named `mesh-netwrking-guide`."));
assert_eq!(v["closestMatches"][0]["name"], "mesh-networking");
assert_eq!(
v["validNames"].as_array().unwrap().len(),
r.skills().count()
);
let v = answer(lookup(&r, Kind::Package, "@offline-protocol/flutter-sdk"));
assert!(v["message"]
.as_str()
.unwrap()
.contains("no Offline Protocol package named"));
assert_eq!(
v["validNames"].as_array().unwrap().len(),
r.packages().count()
);
let v = answer(lookup(&r, Kind::Template, "zzzz"));
assert_eq!(v["closestMatches"], json!([]));
assert!(v["message"].as_str().unwrap().contains("No name is close."));
let v = answer(lookup(&r, Kind::Workflow, ""));
assert_eq!(v["found"], false);
}
#[test]
fn the_cli_is_not_an_sdk_package() {
let r = reg();
for input in [
"@offline-protocol/cli",
"cli",
"offline-cli",
"@offline-protocol/cli@0.5.0",
] {
let v = answer(lookup(&r, Kind::Package, input));
assert_eq!(v["supported"], false, "{input}");
assert!(v["reason"].as_str().unwrap().contains("not an SDK package"));
assert_eq!(v["cli"]["package"], CLI_NPM_PACKAGE);
}
}
#[test]
fn every_capability_resolves_to_a_skill() {
let r = reg();
for cap in r.capabilities() {
assert!(!cap.skills.is_empty(), "{} has no skill", cap.name);
match lookup(&r, Kind::Skill, &cap.name) {
Lookup::Found { name, .. } => assert!(cap.skills.contains(&name)),
Lookup::Answer(v) => assert_eq!(
v["matches"].as_array().unwrap().len(),
cap.skills.len(),
"{}",
cap.name
),
}
}
}
#[test]
fn platform_inputs_classify() {
for p in PLATFORM_ENUM {
assert_eq!(classify_platform(p), PlatformInput::Exact);
}
for (input, value) in [
("ios", "react-native"),
("Android", "react-native"),
("React Native", "react-native"),
("react", "react-vite"),
("vite", "react-vite"),
("next", "nextjs"),
("Next.js", "nextjs"),
("browser", "web"),
("WEB", "web"),
] {
match classify_platform(input) {
PlatformInput::Alias(v, note) => {
assert_eq!(v, value, "{input}");
assert!(note.contains(input), "{note}");
}
other => panic!("{input}: {other:?}"),
}
}
// Python has a starter, so it is a schema value, not package-only.
assert_eq!(classify_platform("python"), PlatformInput::Exact);
let PlatformInput::Alias(value, note) = classify_platform("Python3") else {
unreachable!()
};
assert_eq!(value, "python");
assert!(!note.contains("packages only"), "{note}");
// Java has a starter (kotlin-mesh-chat) too; Kotlin alone still
// means Android.
assert_eq!(classify_platform("java"), PlatformInput::Exact);
let PlatformInput::Alias(value, note) = classify_platform("JVM") else {
unreachable!()
};
assert_eq!(value, "java");
assert!(!note.contains("packages only"), "{note}");
let PlatformInput::Alias(_, note) = classify_platform("ios") else {
unreachable!()
};
assert!(
note.contains("native packages are early previews"),
"{note}"
);
assert_eq!(
classify_platform("xamarin"),
PlatformInput::Unsupported("Xamarin")
);
assert_eq!(
classify_platform("unity"),
PlatformInput::Unsupported("Unity")
);
// SDK 0.28.0: package-only platforms are aliases, not unsupported.
for (input, value) in [
("swift", "ios-native"),
("SwiftUI", "ios-native"),
("Kotlin", "android-native"),
("android native", "android-native"),
("Jetpack Compose", "android-native"),
("ESP32", "embedded"),
("firmware", "embedded"),
// SDK 0.30.0.
("flutter", "flutter"),
("Dart", "flutter"),
("c", "c"),
("C API", "c"),
// SDK 0.31.0.
("ruby", "ruby"),
("Ruby", "ruby"),
("rb", "ruby"),
// SDK 0.32.0.
("csharp", "csharp"),
("C#", "csharp"),
("c#", "csharp"),
("dotnet", "csharp"),
(".NET", "csharp"),
] {
match classify_platform(input) {
PlatformInput::Alias(v, note) => {
assert_eq!(v, value, "{input}");
assert!(note.contains("packages only"), "{note}");
assert!(
offline_registry::normalize_platform(v).as_deref() == Some(value),
"{v}"
);
}
other => panic!("{input}: {other:?}"),
}
}
assert_eq!(classify_platform("windows95"), PlatformInput::Unknown);
assert!(unknown_platform_message("windows95").contains("react-native, nextjs"));
}
#[test]
fn sdk_0_28_platform_and_feature_names_resolve() {
let r = reg();
let cases = [
(Kind::Package, "python", "offline-protocol-sdk"),
(Kind::Package, "Python", "offline-protocol-sdk"),
(Kind::Package, "swift", "offline-protocol-swift"),
(
Kind::Package,
"OfflineProtocolSDK",
"offline-protocol-swift",
),
(Kind::Package, "kotlin", "offline-protocol-android"),
(Kind::Package, "android native", "offline-protocol-android"),
(
Kind::Package,
"com.offlineprotocol:offline-protocol-sdk",
"offline-protocol-android",
),
(Kind::Package, "esp32", "offline-protocol-leaf"),
(Kind::Package, "leaf", "offline-protocol-leaf"),
(Kind::Package, "local api", "offline-protocol-sdk"),
(Kind::Skill, "local api", "local-api"),
(Kind::Skill, "Custody", "custody"),
(Kind::Skill, "swift", "native-platforms"),
(Kind::Skill, "kotlin", "native-platforms"),
(Kind::Skill, "esp32", "embedded-leaf"),
(Kind::Skill, "embedded-leaf", "embedded-leaf"),
];
for (kind, input, expected) in cases {
let (name, _) = found_name(lookup(&r, kind, input));
assert_eq!(name, expected, "{kind:?} {input}");
}
// Custody is in the React Native, Python and Rust packages.
let v = answer(lookup(&r, Kind::Package, "custody"));
let names: Vec<&str> = v["matches"]
.as_array()
.unwrap()
.iter()
.map(|m| m["name"].as_str().unwrap())
.collect();
for name in [
"@offline-protocol/mesh-sdk",
"offline-protocol-sdk",
"offline-protocol",
] {
assert!(names.contains(&name), "{names:?}");
}
// Rust lists the engine crate and the leaf crate.
let v = answer(lookup(&r, Kind::Package, "rust"));
assert_eq!(v["matches"].as_array().unwrap().len(), 2, "{v}");
}
#[test]
fn package_only_platforms_have_no_templates_and_say_what_to_install() {
let r = reg();
for (input, package) in [
("swift", "offline-protocol-swift"),
("kotlin", "offline-protocol-android"),
("esp32", "offline-protocol-leaf"),
("rust", "offline-protocol"),
] {
let v = answer(lookup(&r, Kind::Template, input));
assert_eq!(v["found"], false);
let message = v["message"].as_str().unwrap();
assert!(message.contains("no starter template"), "{message}");
assert!(message.contains(package), "{input}: {message}");
assert!(v["packages"]
.as_array()
.unwrap()
.iter()
.any(|p| p["name"] == package));
}
// Platforms with templates still list them, Python included.
assert_eq!(
found_name(lookup(&r, Kind::Template, "vite")).0,
"react-vite-social"
);
assert_eq!(
found_name(lookup(&r, Kind::Template, "python")).0,
"python-mesh-chat"
);
assert_eq!(
found_name(lookup(&r, Kind::Template, "jvm")).0,
"kotlin-mesh-chat"
);
}
#[test]
fn one_line_keeps_the_first_sentence() {
assert_eq!(one_line("First. Second."), "First.");
assert!(one_line(&"word ".repeat(80)).ends_with("..."));
}
}