← Commit history

v2.1.4: Docs and source only: the skill now describes the fixed vendor services (DigiKey returns every listing of a part, JLCPCB search answers carry prices), and the published binary is built from this repo with its original `src/wiki.rs`. No change in behaviour from 2.1.3.

Colby Knox ·4e70fefbef · ·parent 8517d17
7 files changed +259−224
Cargo.lock+1−1
@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"  [[package]] name = "adom-parts-search"-version = "2.1.3"+version = "2.1.4" dependencies = [  "base64",  "clap",
Cargo.toml+1−1
@@ -1,6 +1,6 @@ [package] name = "adom-parts-search"-version = "2.1.3"+version = "2.1.4" edition = "2021" description = "Parts Search Electronics component search — CLI, backend HTTP service, and Hydrogen webview app" license = "MIT"
VERSION+1−1
@@ -1 +1 @@-2.1.3+2.1.4
install.sh

  
package.json+1−40
@@ -34,44 +34,5 @@     "SKILL.md",     "BUILD-SKILL.md",     "CHANGELOG.md"-  ],-  "changelog": "Docs and source only: the skill now describes the fixed vendor services (DigiKey returns every listing of a part, JLCPCB search answers carry prices), and the published binary is built from this repo with its original `src/wiki.rs`. No change in behaviour from 2.1.3.",-  "discovery_triggers": [-    "parts search",-    "find part",-    "source component",-    "source part",-    "compare distributors",-    "compare vendors",-    "Mouser or DigiKey",-    "BOM sourcing",-    "price this part",-    "where can I get",-    "check stock",-    "parts availability",-    "fastest delivery",-    "cheapest part",-    "component search",-    "part lookup",-    "price breaks"-  ],-  "discovery_pitch": "Search Mouser, DigiKey and JLCPCB in parallel with product photos; Mouser-preferred best-source pick. Say 'with parts search' to your AI.",-  "sample_prompts": [-    {-      "label": "source an STM32F103RBT6",-      "prompt": "source an STM32F103RBT6"-    },-    {-      "label": "where can I get an ESP32-S3-WROOM cheape",-      "prompt": "where can I get an ESP32-S3-WROOM cheapest and fastest"-    },-    {-      "label": "compare Mouser, DigiKey and JLCPCB for a",-      "prompt": "compare Mouser, DigiKey and JLCPCB for an LM555"-    },-    {-      "label": "price this BOM across distributors",-      "prompt": "price this BOM across distributors"-    }   ]-}\ No newline at end of file+}
src/wiki.rs+255−181
@@ -1,19 +1,24 @@-//! The Adom wiki side of a search: component pages with ready-made CAD, their Verified state and Adom stock, the-//! request flow for a part with no page, and the transport for the wiki's parts-search route. wiki.adom.inc is the-//! only host this module calls.+//! The Adom wiki is the ONLY source (Ray, 2026-11-04: "I'm going to make the wiki search the sole endpoint for+//! adom-parts-search and that way we're not burning Mouser and DigiKey API calls. If someone asks the wiki for+//! something, either we have it, or we will make it quickly."). A part with a component page has ready-made CAD+//! (symbol, footprint, 3D, STEP, an Eagle .lbr), often a Verified record, its distributor numbers, the stock the wiki+//! has cached, and for Adom's own parts the Adom part number and stock. A part without one is recorded as a search+//! miss and can be requested; Adom's factory builds the page. No distributor is asked on a person's search: the+//! wiki's stock route serves its cache only. //!-//! This file was missing from the page repo (publish.sh never listed it), so 2.1.3 rebuilt it from the routes, keys and-//! messages in the 2.1.2 binary and checked it against that binary's output. If the original turns up, diff the two.+//! Auth is the wiki CLI's own (ADOM_WIKI_TOKEN, else ~/.config/adom-wiki/token or its config.json), so a signed-in+//! user also sees the private pages they may see and nothing else; without a token the search is anonymous and only+//! public pages come back.  use serde::{Deserialize, Serialize};-use serde_json::{json, Value};+use serde_json::Value;+use std::sync::mpsc; use std::thread;-use std::time::Duration;+use std::time::{Duration, Instant};  pub const DEFAULT_WIKI: &str = "https://wiki.adom.inc";-/// How many search rows are looked at closely: each one costs up to three wiki reads.-const MAX_PAGES: usize = 5;-const USER_AGENT: &str = concat!("adom-parts-search/", env!("CARGO_PKG_VERSION"));+/// Pages read in full per search (page.json + verification each). The search itself returns more.+const DETAIL_PAGES: usize = 5;  #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct Cad {@@ -27,30 +32,38 @@ pub struct Cad {  #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct WikiHit {+    /// owner/slug     pub r#ref: String,     pub url: String,     pub title: String,     pub mpn: String,     pub manufacturer: String,     pub visibility: String,+    /// The page's component MPN (or slug) is exactly the query.     pub exact: bool,     pub cad: Cad,-    /// "none", "verified" or "stale".+    /// "verified" (a current record), "stale" (a pinned file changed since), or "none".     pub verified: String,-    #[serde(default, skip_serializing_if = "Option::is_none")]-    pub lifecycle: Option<String>,-    #[serde(default, skip_serializing_if = "Option::is_none")]+    /// component.adom: Adom's own part number and stock label, on Adom-made and Adom basic parts.+    #[serde(skip_serializing_if = "Option::is_none")]     pub adom: Option<Value>,+    /// The maker's lifecycle when the page records it (preview, active, nrnd, ...).+    #[serde(skip_serializing_if = "Option::is_none")]+    pub lifecycle: Option<String>,+    /// component.distributor_links: the distributor part numbers (a string), or false where a distributor was+    /// checked and does not carry the part.     #[serde(default)]     pub distributor_links: Value,-    #[serde(default, skip_serializing_if = "Option::is_none")]-    pub stock: Option<Value>,-    #[serde(default, skip_serializing_if = "Option::is_none")]+    /// GET /api/pages/<ref>/stock: the wiki's cached vendor numbers ({mouser, digikey, lcsc}, each null when not+    /// cached) and when they were read. Never a live lookup.+    #[serde(default)]+    pub stock: Value,+    #[serde(skip_serializing_if = "Option::is_none")]     pub datasheet_url: Option<String>,-    #[serde(default, skip_serializing_if = "Option::is_none")]-    pub package: Option<String>,-    #[serde(default, skip_serializing_if = "Option::is_none")]-    pub description: Option<String>,+    #[serde(default)]+    pub package: String,+    #[serde(default)]+    pub description: String, }  #[derive(Debug, Clone, Serialize, Deserialize, Default)]@@ -59,222 +72,283 @@ pub struct WikiBlock {     #[serde(default, skip_serializing_if = "std::ops::Not::not")]     pub skipped: bool,     pub error: Option<String>,+    /// True when an exact page exists: the part has ready-made CAD on the Adom wiki.     pub ready_made: bool,     pub hits: Vec<WikiHit>,-    #[serde(default, skip_serializing_if = "Option::is_none")]+    /// No exact page: how to have the factory build one.+    #[serde(skip_serializing_if = "Option::is_none")]     pub request: Option<Value>,+    /// The orderable part numbers behind the query (GET /api/part-request/candidates), each with its page when one+    /// exists, its lifecycle (a "preview" tag) and the maker's page.     #[serde(default, skip_serializing_if = "Vec::is_empty")]     pub candidates: Vec<Value>,+    /// The search was recorded as a miss (POST /api/part-search-miss): enough searchers queue the part even when no+    /// one clicks Request, and the counts are Adom's market signal.+    #[serde(default)]     pub miss_recorded: bool,+    /// Why a miss was not recorded, when it was not (the wiki takes misses from its own search page today:+    /// PART_SEARCH_MISS_CROSS_SITE).     #[serde(default, skip_serializing_if = "Option::is_none")]     pub miss_note: Option<String>,     pub signed_in: bool,     pub elapsed_ms: u64, } -/// The wiki's public route, or a direct test route (ADOM_PARTS_SEARCH_URL + ADOM_PARTS_SEARCH_KEY).-#[derive(Debug, Clone)]-pub struct Route {-    pub url: String,-    pub via: String,-    pub key: Option<String>,-    pub user: Option<String>,+pub fn norm(s: &str) -> String { s.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_uppercase() }++/// The wiki CLI's token: ADOM_WIKI_TOKEN, else ~/.config/adom-wiki/token, else that folder's config.json api_token.+fn token() -> Option<String> {+    if let Ok(t) = std::env::var("ADOM_WIKI_TOKEN") { if !t.trim().is_empty() { return Some(t.trim().into()); } }+    let dir = format!("{}/.config/adom-wiki", std::env::var("HOME").unwrap_or_default());+    if let Ok(t) = std::fs::read_to_string(format!("{}/token", dir)) { if !t.trim().is_empty() { return Some(t.trim().into()); } }+    let cfg: Value = serde_json::from_str(&std::fs::read_to_string(format!("{}/config.json", dir)).ok()?).ok()?;+    cfg.get("api_token").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).map(String::from) } +/// Where the distributor search goes (Ray, 2026-11-04: through the wiki, which forwards to Component Ocean).+/// The public route by default; ADOM_PARTS_SEARCH_URL (with ADOM_PARTS_SEARCH_KEY and ADOM_PARTS_SEARCH_USER) points+/// it elsewhere for testing until the wiki route ships (adom/wiki#261).+pub struct Route { pub url: String, pub via: &'static str, headers: Vec<(String, String)> }+ pub fn parts_search_route() -> Route {-    let env = |k: &str| std::env::var(k).ok().filter(|s| !s.is_empty());-    if let Some(url) = env("ADOM_PARTS_SEARCH_URL") {-        return Route { url, via: "test-route".into(), key: env("ADOM_PARTS_SEARCH_KEY"), user: env("ADOM_PARTS_SEARCH_USER") };+    if let Ok(u) = std::env::var("ADOM_PARTS_SEARCH_URL") {+        if !u.trim().is_empty() {+            let mut headers = vec![];+            if let Ok(k) = std::env::var("ADOM_PARTS_SEARCH_KEY") { headers.push(("X-Adom-Request-Key".into(), k.trim().to_string())); }+            headers.push(("X-Adom-User".into(), std::env::var("ADOM_PARTS_SEARCH_USER").unwrap_or_else(|_| "anon".into())));+            if std::env::var("ADOM_PARTS_SEARCH_USER").is_err() { headers.push(("X-Adom-Anon-Ip".into(), "127.0.0.1".into())); }+            return Route { url: u.trim().to_string(), via: "test-route", headers };+        }     }-    Route { url: format!("{}/api/parts-search", DEFAULT_WIKI), via: "wiki".into(), key: None, user: None }+    let headers = token().map(|t| vec![("Authorization".to_string(), format!("Bearer {}", t))]).unwrap_or_default();+    Route { url: format!("{}/api/parts-search", DEFAULT_WIKI), via: "wiki", headers } } -/// The wiki CLI's sign-in: ADOM_WIKI_TOKEN, or api_token in ~/.config/adom-wiki/config.json.-fn token() -> Option<String> {-    if let Some(t) = std::env::var("ADOM_WIKI_TOKEN").ok().filter(|s| !s.trim().is_empty()) { return Some(t.trim().to_string()); }-    let home = std::env::var("HOME").ok()?;-    let raw = std::fs::read_to_string(format!("{}/.config/adom-wiki/config.json", home)).ok()?;-    let v: Value = serde_json::from_str(&raw).ok()?;-    v.get("api_token").and_then(|t| t.as_str()).map(str::trim).filter(|s| !s.is_empty()).map(String::from)+pub fn post_route(r: &Route, body: Value) -> Result<Value, String> {+    let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(60)).build();+    netlog("POST", &r.url);+    let mut req = agent.post(&r.url).set("Content-Type", "application/json")+        .set("User-Agent", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION"))).set("X-Adom-Client", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION")));+    for (k, v) in &r.headers { req = req.set(k, v); }+    match req.send_json(body) {+        Ok(x) => x.into_json().map_err(|e| format!("JSON: {}", e)),+        Err(ureq::Error::Status(404, _)) if r.via == "wiki" => Err("http 404 the wiki's parts-search route is not live yet (adom/wiki#261)".into()),+        Err(ureq::Error::Status(code, x)) => Err(format!("http {} {}", code, x.into_string().unwrap_or_default().chars().take(200).collect::<String>())),+        Err(e) => Err(format!("{}", e)),+    } } -pub fn signed_in() -> bool { token().is_some() }--fn netlog(method: &str, url: &str) {+/// ADOM_PARTS_SEARCH_NETLOG=1: print every outbound request (method, host, path) to stderr, so a test can show which+/// hosts a search touches (the wiki only).+pub fn netlog(method: &str, url: &str) {     if std::env::var("ADOM_PARTS_SEARCH_NETLOG").map(|v| v == "1").unwrap_or(false) {-        eprintln!("NET {} {}", method, url.split('?').next().unwrap_or(url));+        let u = url.split('?').next().unwrap_or(url);+        eprintln!("NET {} {}", method, u);     } } -fn agent(secs: u64) -> ureq::Agent { ureq::AgentBuilder::new().timeout(Duration::from_secs(secs)).build() }+/// Signed in to the wiki (the wiki CLI's token is present).+pub fn signed_in() -> bool { token().is_some() } -fn with_identity(mut req: ureq::Request) -> ureq::Request {-    req = req.set("User-Agent", USER_AGENT).set("X-Adom-Client", USER_AGENT).set("X-Adom-Caller", "parts-search");-    if let Some(t) = token() { req = req.set("Authorization", &format!("Bearer {}", t)); }-    req+fn get(base: &str, path: &str, tok: &Option<String>, secs: u64) -> Result<Value, String> {+    let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(secs)).build();+    netlog("GET", &format!("{}{}", base.trim_end_matches('/'), path));+    let mut req = agent.get(&format!("{}{}", base.trim_end_matches('/'), path))+        .set("User-Agent", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION")))+        .set("X-Adom-Caller", "parts-search");+    if let Some(t) = tok { req = req.set("Authorization", &format!("Bearer {}", t)); }+    match req.call() {+        Ok(r) => r.into_json().map_err(|e| format!("JSON: {}", e)),+        Err(ureq::Error::Status(code, _)) => Err(format!("http {}", code)),+        Err(e) => Err(format!("{}", e)),+    } } -fn answer(res: Result<ureq::Response, ureq::Error>) -> Result<Value, String> {-    match res {-        Ok(r) => r.into_json().map_err(|e| format!("bad JSON: {}", e)),+fn post(base: &str, path: &str, body: Value, tok: &Option<String>, secs: u64) -> Result<Value, String> {+    let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(secs)).build();+    netlog("POST", &format!("{}{}", base.trim_end_matches('/'), path));+    let mut req = agent.post(&format!("{}{}", base.trim_end_matches('/'), path))+        .set("User-Agent", concat!("adom-parts-search/", env!("CARGO_PKG_VERSION")))+        .set("X-Adom-Caller", "parts-search").set("Content-Type", "application/json");+    if let Some(t) = tok { req = req.set("Authorization", &format!("Bearer {}", t)); }+    match req.send_json(body) {+        Ok(r) => r.into_json().map_err(|e| format!("JSON: {}", e)),         Err(ureq::Error::Status(code, r)) => Err(format!("http {}: {}", code, r.into_string().unwrap_or_default().chars().take(300).collect::<String>())),-        Err(e) => Err(e.to_string()),+        Err(e) => Err(format!("{}", e)),     } } -fn get(path: &str, secs: u64) -> Result<Value, String> {-    let url = format!("{}{}", DEFAULT_WIKI, path);-    netlog("GET", &url);-    answer(with_identity(agent(secs).get(&url)).call())+/// Have Adom's factory build a page for this part, through the wiki's own request flow (the "Request this part"+/// button posts the same call). The answer carries the request, its status_url and its position or ETA.+pub fn request(mpn: &str, urgency: &str, base: Option<&str>) -> Result<Value, String> {+    let tok = token();+    if tok.is_none() { return Err("not signed in to the wiki: run `adom-wiki auth login` (or set ADOM_WIKI_TOKEN), then request again".into()); }+    let base = base.unwrap_or(DEFAULT_WIKI);+    let mut r = post(base, "/api/part-request", serde_json::json!({"mpn": mpn.trim(), "urgency": urgency}), &tok, 60)?;+    // the wiki answers a site-relative status link; a CLI or another app needs the full one+    if let Some(u) = r.get("status_url").and_then(|v| v.as_str()).filter(|u| u.starts_with('/')).map(String::from) {+        r["status_url"] = Value::String(format!("{}{}", base.trim_end_matches('/'), u));+    }+    Ok(r) } -fn post(path: &str, body: Value, secs: u64) -> Result<Value, String> {-    let url = format!("{}{}", DEFAULT_WIKI, path);-    netlog("POST", &url);-    answer(with_identity(agent(secs).post(&url)).set("Content-Type", "application/json").send_json(body))+/// Where a request stands now (GET /api/part-request/status/<id>).+pub fn request_status(id: &str, base: Option<&str>) -> Result<Value, String> {+    get(base.unwrap_or(DEFAULT_WIKI), &format!("/api/part-request/status/{}", urlencode(id)), &token(), 20) } -/// One search through the parts-search route. Component Ocean may ask three vendors live, so this waits longer than a read.-pub fn post_route(route: &Route, body: Value) -> Result<Value, String> {-    netlog("POST", &route.url);-    let mut req = with_identity(agent(60).post(&route.url)).set("Content-Type", "application/json");-    if route.via == "test-route" {-        if let Some(k) = &route.key { req = req.set("X-Adom-Request-Key", k); }-        req = req.set("X-Adom-User", route.user.as_deref().unwrap_or("anon")).set("X-Adom-Anon-Ip", "127.0.0.1");+/// What one page carries: CAD from component.parts, component.adom, lifecycle, and its verification state.+pub fn hit_from(r: &Value, page: &Value, verification: &Value, base: &str, query: &str) -> WikiHit {+    let owner = r.get("owner").and_then(|v| v.as_str()).unwrap_or("");+    let slug = r.get("slug").and_then(|v| v.as_str()).unwrap_or("");+    let c = page.get("component").cloned().unwrap_or(Value::Null);+    let parts = c.get("parts").cloned().unwrap_or(Value::Null);+    let has = |k: &str| parts.get(k).and_then(|v| v.as_str()).map(|s| !s.is_empty()).unwrap_or(false);+    let mpn = c.get("mpn").and_then(|v| v.as_str()).unwrap_or("").to_string();+    let q = norm(query);+    let entries = verification.get("verification").and_then(|v| v.get("entries")).and_then(|v| v.as_array()).cloned().unwrap_or_default();+    let verified = if entries.iter().any(|e| e.get("state").and_then(|s| s.as_str()) == Some("current")) { "verified" }+        else if !entries.is_empty() { "stale" } else { "none" };+    let lifecycle = c.pointer("/distributor_check/manufacturer/lifecycle").and_then(|v| v.as_str()).map(String::from)+        .or_else(|| c.get("lifecycle").and_then(|v| v.as_str()).map(String::from));+    WikiHit {+        r#ref: format!("{}/{}", owner, slug),+        url: format!("{}/{}/{}", base.trim_end_matches('/'), owner, slug),+        title: r.get("title").and_then(|v| v.as_str()).unwrap_or(slug).to_string(),+        manufacturer: c.get("manufacturer").and_then(|v| v.as_str()).unwrap_or("").to_string(),+        visibility: r.get("visibility").and_then(|v| v.as_str()).unwrap_or("public").to_string(),+        exact: !q.is_empty() && (norm(&mpn) == q || norm(slug) == q),+        cad: Cad { symbol: has("symbol"), footprint: has("footprint"), model_3d: has("model_3d") || has("model_3d_plain"),+                   step: has("model_3d_step") || has("model_3d_step_plain"), lbr: has("lbr") },+        verified: verified.into(),+        adom: c.get("adom").cloned().filter(|v| v.is_object()),+        lifecycle,+        distributor_links: c.get("distributor_links").cloned().unwrap_or(Value::Null),+        stock: Value::Null,+        datasheet_url: c.get("datasheet").and_then(|v| v.get("url").or(Some(v))).and_then(|v| v.as_str()).map(String::from),+        package: c.get("package").and_then(|v| v.as_str()).unwrap_or("").to_string(),+        description: page.get("description").or_else(|| r.get("brief")).and_then(|v| v.as_str()).unwrap_or("").to_string(),+        mpn,     }-    answer(req.send_json(body)).map_err(|e| {-        if e.starts_with("http 404") { format!("{} the wiki's parts-search route is not live yet (adom/wiki#261)", e) } else { e }-    }) } -fn enc(s: &str) -> String {-    let mut out = String::new();-    for b in s.bytes() {-        match b {-            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),-            _ => out.push_str(&format!("%{:02X}", b)),+/// The wiki's component pages for this query: search, then each of the top pages in full, in parallel.+pub fn search(query: &str, base: Option<&str>) -> WikiBlock {+    let base = base.unwrap_or(DEFAULT_WIKI).to_string();+    let t0 = Instant::now();+    let tok = token();+    let mut block = WikiBlock { signed_in: tok.is_some(), ..Default::default() };+    let q = urlencode(query);+    let found = match get(&base, &format!("/api/search?q={}&type=component&limit=12", q), &tok, 12) {+        Ok(v) => v,+        Err(e) => { block.error = Some(format!("wiki search failed: {}", e)); block.elapsed_ms = t0.elapsed().as_millis() as u64; return block; }+    };+    let mut results: Vec<Value> = found.get("results").and_then(|v| v.as_array()).cloned().unwrap_or_default();+    // exact slugs first, so the page for the part itself is always read in full+    let qn = norm(query);+    results.sort_by_key(|r| if norm(r.get("slug").and_then(|v| v.as_str()).unwrap_or("")) == qn { 0 } else { 1 });+    results.truncate(DETAIL_PAGES);+    let (tx, rx) = mpsc::channel::<(usize, WikiHit)>();+    for (i, r) in results.iter().cloned().enumerate() {+        let (tx, base, tok, query) = (tx.clone(), base.clone(), tok.clone(), query.to_string());+        thread::spawn(move || {+            let owner = r.get("owner").and_then(|v| v.as_str()).unwrap_or("").to_string();+            let slug = r.get("slug").and_then(|v| v.as_str()).unwrap_or("").to_string();+            let page = get(&base, &format!("/api/pages/{}/{}/files/page.json", owner, slug), &tok, 10).unwrap_or(Value::Null);+            let ver = get(&base, &format!("/api/pages/{}/{}/verification", owner, slug), &tok, 10).unwrap_or(Value::Null);+            let mut h = hit_from(&r, &page, &ver, &base, &query);+            // the cache only: this route never asks a distributor (refresh "declined" for a non-widget read)+            if h.cad.footprint || h.exact { h.stock = get(&base, &format!("/api/pages/{}/{}/stock", owner, slug), &tok, 10).unwrap_or(Value::Null); }+            let _ = tx.send((i, h));+        });+    }+    drop(tx);+    let mut hits: Vec<(usize, WikiHit)> = rx.iter().collect();+    hits.sort_by_key(|(i, h)| (if h.exact { 0 } else { 1 }, *i));+    block.hits = hits.into_iter().map(|(_, h)| h).filter(|h| h.cad.footprint || h.cad.symbol || h.exact).collect();+    block.ok = true;+    block.ready_made = block.hits.iter().any(|h| h.exact && (h.cad.symbol || h.cad.footprint));+    if !block.ready_made && looks_like_mpn(query) {+        block.request = Some(request_offer(query));+        // the orderable numbers behind it (Component Ocean answers this behind the wiki), and the miss recorded+        if let Ok(v) = get(&base, &format!("/api/part-request/candidates?q={}", q), &tok, 20) {+            block.candidates = v.get("candidates").and_then(|c| c.as_array()).cloned().unwrap_or_default();+            block.candidates.truncate(10);+        }+        match post(&base, "/api/part-search-miss", serde_json::json!({"mpn": query.trim()}), &tok, 10) {+            Ok(_) => block.miss_recorded = true,+            Err(e) => block.miss_note = Some(if e.contains("PART_SEARCH_MISS_CROSS_SITE") {+                "not recorded: the wiki accepts search misses from its own search page only (an API route is pending on the wiki side)".to_string()+            } else { format!("not recorded: {}", e.chars().take(160).collect::<String>()) }),         }     }-    out+    block.elapsed_ms = t0.elapsed().as_millis() as u64;+    block } +/// How to have Adom's factory build the page: the wiki CLI, or Component Ocean's request endpoint (the wiki's own+/// "Request this part" button posts there too). pub fn request_offer(mpn: &str) -> Value {-    json!({+    serde_json::json!({         "mpn": mpn,         "message": format!("No Adom wiki page for {} yet. Request it and Adom's factory builds one (symbol, footprint, 3D, datasheet).", mpn),         "cli": format!("adom-parts-search request {}", mpn),-        "web": format!("{}/search?q={}", DEFAULT_WIKI, enc(mpn)),+        "web": format!("{}/search?q={}", DEFAULT_WIKI, urlencode(mpn)),     }) } -fn norm(s: &str) -> String { s.trim().to_uppercase() }--fn text(v: &Value, ptr: &str) -> Option<String> {-    v.pointer(ptr).and_then(|x| x.as_str()).map(str::trim).filter(|s| !s.is_empty()).map(String::from)+/// One token, letters and digits with at least one digit: a part number, not a phrase like "10k 0603 resistor".+pub fn looks_like_mpn(q: &str) -> bool {+    let q = q.trim();+    !q.is_empty() && !q.contains(char::is_whitespace) && q.chars().any(|c| c.is_ascii_digit()) && q.chars().any(|c| c.is_ascii_alphabetic()) } -fn raw_text(v: &Value, ptr: &str) -> Option<String> { v.pointer(ptr).and_then(|x| x.as_str()).map(String::from) }--/// page.json + verification + stock -> one hit. A file that does not answer leaves its fields empty, never an error.-/// None for a page that is neither the part asked for nor has a symbol or footprint (a group page, a library): it is no-/// part to show, and its stock is not read.-fn hit_from(row: &Value, q: &str) -> Option<WikiHit> {-    let owner = row.get("owner").and_then(|v| v.as_str()).unwrap_or("").to_string();-    let slug = row.get("slug").and_then(|v| v.as_str()).unwrap_or("").to_string();-    let reference = format!("{}/{}", owner, slug);-    let base = format!("/api/pages/{}/{}", owner, slug);-    let page = get(&format!("{}/files/page.json", base), 10).unwrap_or(Value::Null);-    let parts = page.pointer("/component/parts").cloned().unwrap_or(Value::Null);-    let has = |k: &str| parts.get(k).and_then(|v| v.as_str()).map(|s| !s.is_empty()).unwrap_or(false);-    let title = row.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string();-    let mpn = text(&page, "/component/mpn").unwrap_or_else(|| title.clone());-    let verified = match get(&format!("{}/verification", base), 10).ok().and_then(|v| v.get("verification").cloned()).filter(|v| !v.is_null()) {-        None => "none",-        Some(v) if v.get("stale").and_then(|s| s.as_bool()).unwrap_or(false) => "stale",-        Some(_) => "verified",-    }.to_string();-    let exact = norm(&mpn) == norm(q) || norm(&slug) == norm(q) || norm(&title) == norm(q);-    if !(exact || has("symbol") || has("footprint")) { return None; }-    let stock = get(&format!("{}/stock", base), 10).ok();-    Some(WikiHit {-        url: format!("{}/{}", DEFAULT_WIKI, reference),-        exact,-        r#ref: reference,-        title,-        manufacturer: text(&page, "/component/manufacturer").unwrap_or_default(),-        visibility: row.get("visibility").and_then(|v| v.as_str()).unwrap_or("public").to_string(),-        cad: Cad {-            symbol: has("symbol"),-            footprint: has("footprint"),-            model_3d: has("model_3d") || has("model_3d_plain"),-            step: has("model_3d_step") || has("model_3d_step_plain"),-            lbr: has("lbr"),-        },-        verified,-        lifecycle: text(&page, "/component/lifecycle").or_else(|| text(&page, "/distributor_check/manufacturer/lifecycle")),-        adom: stock.as_ref().and_then(|s| s.get("adom")).filter(|a| !a.is_null()).cloned(),-        distributor_links: page.pointer("/component/distributor_links").cloned().unwrap_or(Value::Null),-        stock,-        datasheet_url: raw_text(&page, "/component/datasheet"),-        package: Some(raw_text(&page, "/component/package").unwrap_or_default()),-        description: text(&page, "/brief").or_else(|| row.get("brief").and_then(|v| v.as_str()).map(String::from)),-        mpn,-    })+pub fn urlencode(s: &str) -> String {+    s.bytes().map(|b| match b {+        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),+        _ => format!("%{:02X}", b),+    }).collect() } -/// Tell the wiki an exact part had no page. The wiki takes this from its own search page only for now, so a refusal is-/// a note on the block, never a failed search. Component Ocean counts the demand either way.-fn record_miss(q: &str) -> (bool, Option<String>) {-    match post("/api/part-search-miss", json!({"mpn": q}), 8) {-        Ok(_) => (true, None),-        Err(e) if e.contains("PART_SEARCH_MISS_CROSS_SITE") =>-            (false, Some("not recorded: the wiki accepts search misses from its own search page only (an API route is pending on the wiki side)".into())),-        Err(e) => (false, Some(format!("not recorded: {}", e))),-    }-}+#[cfg(test)]+mod tests {+    use super::*;+    use serde_json::json; -pub fn search(q: &str, _host: Option<&str>) -> WikiBlock {-    let t0 = std::time::Instant::now();-    let mut block = WikiBlock { signed_in: signed_in(), ..Default::default() };-    let found = get(&format!("/api/search?q={}&type=component&limit=12", enc(q)), 10);-    let rows = match found {-        Ok(v) => v.get("results").and_then(|r| r.as_array()).cloned().unwrap_or_default(),-        Err(e) => { block.error = Some(e); block.elapsed_ms = t0.elapsed().as_millis() as u64; return block; }-    };-    block.ok = true;-    let handles: Vec<_> = rows.into_iter().take(MAX_PAGES).map(|row| { let q = q.to_string(); thread::spawn(move || hit_from(&row, &q)) }).collect();-    let mut hits: Vec<WikiHit> = handles.into_iter().filter_map(|h| h.join().ok().flatten()).collect();-    hits.sort_by_key(|h| !h.exact); // exact pages first; the sort is stable, so the wiki's rank holds within each group-    block.ready_made = hits.iter().any(|h| h.exact && (h.cad.symbol || h.cad.footprint));-    // keywords ("100nF 0402") are not a part number the request flow can take-    if !hits.iter().any(|h| h.exact) && !q.trim().contains(char::is_whitespace) {-        let candidates = get(&format!("/api/part-request/candidates?q={}", enc(q)), 10).unwrap_or(Value::Null);-        block.candidates = candidates.get("candidates").and_then(|c| c.as_array()).cloned().unwrap_or_default();-        if candidates.get("exact").and_then(|e| e.as_bool()).unwrap_or(false) {-            let mpn = block.candidates.iter().find(|c| norm(c.get("mpn").and_then(|m| m.as_str()).unwrap_or("")) == norm(q))-                .and_then(|c| c.get("mpn").and_then(|m| m.as_str())).unwrap_or(q.trim()).to_string();-            block.request = Some(request_offer(&mpn));-            let (recorded, note) = record_miss(&mpn);-            block.miss_recorded = recorded;-            block.miss_note = note;-        }+    #[test]+    fn a_page_reports_its_cad_verification_stock_and_exact_match() {+        let r = json!({"owner": "adom", "slug": "lm358dr", "title": "LM358DR", "visibility": "public"});+        let page = json!({"component": {"mpn": "LM358DR", "manufacturer": "Texas Instruments",+            "parts": {"symbol": "lm358dr.kicad_sym", "footprint": "lm358dr.kicad_mod", "model_3d": "lm358dr-etched.glb",+                      "model_3d_step": "lm358dr-etched.step", "lbr": "lm358dr.lbr"},+            "adom": {"part_number": "LM358DR", "kind": "adom-basic", "stock": "1k+"},+            "distributor_check": {"manufacturer": {"lifecycle": "preview"}}}});+        let ver = json!({"verification": {"entries": [{"state": "current"}]}});+        let h = hit_from(&r, &page, &ver, DEFAULT_WIKI, "lm358dr");+        assert!(h.exact);+        assert!(h.cad.symbol && h.cad.footprint && h.cad.model_3d && h.cad.step && h.cad.lbr);+        assert_eq!(h.verified, "verified");+        assert_eq!(h.adom.unwrap()["stock"], "1k+");+        assert_eq!(h.lifecycle.as_deref(), Some("preview"));+        assert_eq!(h.url, "https://wiki.adom.inc/adom/lm358dr");     }-    block.hits = hits;-    block.elapsed_ms = t0.elapsed().as_millis() as u64;-    block-} -/// The wiki's own request flow (POST /api/part-request). Needs a sign-in.-pub fn request(mpn: &str, urgency: &str, _host: Option<&str>) -> Result<Value, String> {-    if !signed_in() { return Err("not signed in to the wiki: run `adom-wiki auth login` (or set ADOM_WIKI_TOKEN), then request again".into()); }-    let mut v = post("/api/part-request", json!({"mpn": mpn, "urgency": urgency}), 30)?;-    // the route answers a site-relative status link; print one a person can open-    if let Some(path) = v.get("status_url").and_then(|u| u.as_str()).filter(|u| u.starts_with('/')).map(String::from) {-        v["status_url"] = json!(format!("{}{}", DEFAULT_WIKI, path));+    #[test]+    fn a_family_page_is_not_an_exact_match_and_an_old_record_is_stale() {+        let r = json!({"owner": "adom", "slug": "lm358drg"});+        let page = json!({"component": {"mpn": "LM358DRG", "parts": {"footprint": "x.kicad_mod"}}});+        let h = hit_from(&r, &page, &json!({"verification": {"entries": [{"state": "superseded"}]}}), DEFAULT_WIKI, "LM358DR");+        assert!(!h.exact);+        assert_eq!(h.verified, "stale");+        assert!(!h.cad.symbol && h.cad.footprint);+        assert_eq!(hit_from(&r, &page, &json!({"verification": null}), DEFAULT_WIKI, "x").verified, "none");     }-    Ok(v)-} -pub fn request_status(id: &str, _host: Option<&str>) -> Result<Value, String> {-    get(&format!("/api/part-request/status/{}", enc(id)), 15)+    #[test]+    fn only_part_numbers_get_a_request_offer() {+        assert!(looks_like_mpn("LM2903L-Q1"));+        assert!(!looks_like_mpn("10k 0603 resistor"));+        assert!(!looks_like_mpn("resistor"));+        assert_eq!(request_offer("LM2903L-Q1")["cli"], "adom-parts-search request LM2903L-Q1");+    } }
uninstall.sh