← Commit history

Publish 1.1.1

barrett-land ·9c488424cb · ·parent c998a96
4 files changed +98−36
DEVELOPING.md+13
@@ -111,6 +111,19 @@ His KiCad user libraries:   file) + wiki blob download latency. Symbols are batched (one write/lib) so they're no longer the cost. - Bulk wiki writes are bounded by the **wiki's own rate limit (HTTP 429, ~10/min)** — pace bulk commits. +## ⚠️ NEVER clobber a user's symbol library (data-loss incident)++A symbol lib is ONE file merged into via read→merge→write. If the read silently fails and the code+falls back to an empty template, the write **destroys every existing symbol** in the user's library.+This actually happened — it truncated real `JLC_Capacitors_BLT` (30→1) and `JLC_Resistors_BLT` (53→1).+`fileSymbolsBatched` now has two hard guards (keep them):+1. **Empty template ONLY when the file is genuinely absent.** If `read_file` fails but `[ -f path ]`+   says the file EXISTS, ABORT that library — never overwrite a lib we couldn't read.+2. **Never shrink.** Count symbols (`(property "Reference"`) before and after the merge; if the result+   has fewer than the file already had, ABORT — refuse the write.+Both guards add an error to `DB.send.errors` and skip the lib (no data lost). The old per-component+`fileSymbol` (which lacked these guards) was REMOVED — only the guarded batched path remains.+ ## Hard rules  - **Re-checking the wiki must NEVER delete user-uploaded files or user-edited fields.** `runCheck`
package.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "chip-fetcher-lite",   "title": "Chip Fetcher Lite",-  "version": "1.1.0",+  "version": "1.1.1",   "type": "app",   "description": "Lightweight wiki-first component staging area. Add a component, check the Adom wiki for KiCad/Altium/Fusion files, upload what's missing, then file the symbol + footprint + 3D model straight into your EDA libraries — with library destinations matched per manufacturer and a clean 5-field symbol.",   "tags": [
page.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "chip-fetcher-lite",   "title": "Chip Fetcher Lite",-  "version": "1.1.0",+  "version": "1.1.1",   "type": "app",   "description": "Lightweight wiki-first component staging area. Add a component, check the Adom wiki for KiCad/Altium/Fusion files, upload what's missing, then file the symbol + footprint + 3D model straight into your EDA libraries — with library destinations matched per manufacturer and a clean 5-field symbol.",   "tags": [
server.js+83−34
@@ -110,6 +110,41 @@ function passiveTokens(s) {     val = (vm[1] + (vm[2] || '') + (vm[3] || '')).toLowerCase().replace(/[µμ]/g, 'u');   return { pkg, val }; }+// --- Generic-part resolution. Wiki component pages are keyed by MPN ONLY. For resistors the+// resistance is encoded INSIDE the MPN (e.g. "...1001..." = 100×10^1 = 1kΩ) and NEVER appears as+// human-readable "1k" in the page title/desc — so a description search ("1k 0402 resistor") can't+// text-match a resistor page (FTS just returns whatever mentions "0402"). We must decode the value+// to its EIA code(s) and match those against candidate MPNs, then verify package via page metadata.+// (Capacitors usually DO carry "100nF" in the title so they resolve by text; this is the fallback.)+function ohmsFromToken(val) {+  const m = String(val || '').toLowerCase().replace(/ohm|Ω|ω/g, '').match(/^(\d*\.?\d+)([rkmg]?)$/);+  if (!m) return null;+  const mult = { '': 1, r: 1, k: 1e3, m: 1e6, g: 1e9 }[m[2]];+  const n = parseFloat(m[1]);+  return (isFinite(n) && mult != null) ? n * mult : null;+}+// EIA value codes for a resistance, most-specific (4-digit/1%) first: 1000Ω -> ["1001", "102"]+function eiaResistorCodes(ohms) {+  if (!(ohms > 0)) return [];+  const out = [];+  for (const sig of [3, 2]) {                       // 4-digit (3 sig figs) then 3-digit (2 sig figs)+    let exp = Math.floor(Math.log10(ohms)) - (sig - 1);+    let mant = Math.round(ohms / Math.pow(10, exp));+    if (mant >= Math.pow(10, sig)) { mant = Math.round(mant / 10); exp++; }+    if (exp >= 0 && mant >= Math.pow(10, sig - 1)) out.push(String(mant) + String(exp));+  }+  return out;+}+// 3-digit pF code for a capacitance string ("100nf" -> "104", "4.7uf" -> "475", "10pf" -> "100")+function pfCapCode(val) {+  const m = String(val || '').toLowerCase().match(/^(\d*\.?\d+)(p|n|u|µ)?f?$/);+  if (!m) return null;+  const pf = parseFloat(m[1]) * ({ p: 1, n: 1e3, u: 1e6, 'µ': 1e6, '': 1 }[m[2] || '']);+  if (!(pf > 0)) return null;+  const exp = Math.max(0, Math.floor(Math.log10(pf)) - 1);+  return String(Math.round(pf / Math.pow(10, exp))) + String(exp);+}+ async function classify(mpn) {   const slug = norm(mpn);   let rows = await adompkgSearch(mpn);@@ -125,15 +160,39 @@ async function classify(mpn) {   // 1. exact: slug, the MPN parsed from a result title, or a title equal to the input   let exact = comps.find(r => r.slug === slug || norm(titleMpn(r)) === slug || r.title.toLowerCase() === mpn.toLowerCase()) || null; -  // 2. description -> MPN: the user may type "100nF 0402 capacitor"; resolve to the real MPN-  //    page (the FTS already ranks it #1) by matching value + package against a passive result.+  // 2. description -> MPN. Wiki pages are keyed by MPN only, so a descriptive request+  //    ("1k 0402 resistor", "100nF 0402 capacitor") must be resolved to a real MPN page.   if (!exact) {     const tok = passiveTokens(mpn);-    const descriptive = (tok.pkg && tok.val) || /capacitor|resistor|inductor|\bled\b|ferrite|diode|mlcc/i.test(mpn);+    const isR = /resistor/i.test(mpn), isC = /capacitor|mlcc/i.test(mpn);+    const descriptive = (tok.pkg && tok.val) || isR || isC || /inductor|\bled\b|ferrite|diode/i.test(mpn);     if (descriptive) {       const hay = r => (r.title + ' ' + r.desc).toLowerCase().replace(/\s+/g, '');       const isPassive = r => /capacitor|resistor|inductor|\bled\b|ferrite|diode|mlcc|oscillator|crystal/i.test(r.title + ' ' + r.desc);+      // (a) text match — works for caps/LEDs whose title carries the human value ("100nF MLCC …")       exact = comps.find(r => isPassive(r) && (!tok.val || hay(r).includes(tok.val)) && (!tok.pkg || hay(r).includes(tok.pkg))) || null;+      // (b) MPN-code match — resistors (and caps) encode the value IN the MPN, not the page text.+      //     FTS on the description often misses the family pages entirely, so search by+      //     type+package, match the decoded EIA value code in the MPN, then VERIFY package via meta.+      if (!exact && tok.pkg && tok.val && (isR || isC)) {+        const typeWord = isR ? 'resistor' : 'capacitor';+        const codes = isR ? eiaResistorCodes(ohmsFromToken(tok.val)) : [pfCapCode(tok.val)].filter(Boolean);+        if (codes.length) {+          const seen = new Set(comps.map(r => r.slug));+          const extra = (await adompkgSearch(`${typeWord} ${tok.pkg}`)).filter(r => r.type === 'component' && !seen.has(r.slug));+          const pool = comps.concat(extra);+          const idOf = r => (r.slug + ' ' + r.title).toLowerCase().replace(/[^a-z0-9]/g, '');+          const matchCat = r => new RegExp(typeWord, 'i').test(r.title + ' ' + r.desc);+          const cands = [];+          for (const code of codes) for (const r of pool)   // 4-digit (specific) candidates first+            if (matchCat(r) && idOf(r).includes(code) && !cands.includes(r)) cands.push(r);+          for (const r of cands.slice(0, 8)) {              // confirm the package matches the page+            const pm = await wikiJSON(`/api/v1/pages/${r.slug}`);+            const pkg = pm && pm.metadata && String(pm.metadata.package || '').toLowerCase();+            if (pkg === tok.pkg) { exact = r; break; }+          }+        }+      }     }   } @@ -653,32 +712,6 @@ async function file3D(c, tmpdir) {   const r = await sendFiles([tmp], d.path);   return (r.j && r.j.success === false) ? ('send failed: ' + (r.j.error || '')) : 'ok'; }-async function fileSymbol(c, tmpdir) {-  const d = c.dest && c.dest.symbol; if (!d || !d.path) return 'no dest';-  const got = await getFileContent(c, 'symbol'); if (!got) return 'no source file';-  const block0 = extractSymbolBlock(got.buf.toString('utf8')); if (!block0) return 'no symbol block';-  const oldN = symbolNameOf(block0) || c.mpn;-  const newN = (c.names && c.names.symbol) || c.mpn;-  let block = renameSymbol(block0, oldN, newN);-  block = stripExtraProps(block);                       // drop the wiki symbol's many custom spec fields-  if (c.description) block = setSymProp(block, 'Description', c.description);-  const fpd = c.dest.footprint;-  if (fpd) {-    const nick = baseNoExt(fpd.name);-    const fpName = (fpd.source === 'kicad-default' && fpd.fpName) ? fpd.fpName : ((c.names && c.names.footprint) || c.mpn);-    block = setSymProp(block, 'Footprint', `${nick}:${fpName}`);-  }-  if (c.datasheetUrl) block = setSymProp(block, 'Datasheet', c.datasheetUrl);-  if (c.jlcPart) block = setSymProp(block, 'LCSC', c.jlcPart);   // LCSC/JLCPCB part number field-  const r = await adomDesktopJSON('read_file', { path: d.path, encoding: 'utf8' });-  const destText = (r.j && r.j.success && r.j.content) || '(kicad_symbol_lib (version 20211014) (generator chip-fetcher-lite)\n)\n';-  const { text, skipped } = mergeSymbol(destText, block, newN);-  if (skipped) return 'already present';-  await runDesktopShell(`cp ${shq(d.path)} ${shq(d.path + '.bak')} 2>/dev/null || true`, 20);-  const tmp = path.join(tmpdir, baseNoExt(d.name) + '.kicad_sym'); fs.writeFileSync(tmp, text);-  const sr = await sendFiles([tmp], dirOf(d.path));-  return (sr.j && sr.j.success === false) ? ('send failed: ' + (sr.j.error || '')) : 'ok';-} // redirect a component's destinations under a temp root (mirrors Symbols/Footprints/3D), for a // dry-run export that doesn't touch the user's real libraries or lib tables. function tempDest(c, tempRoot) {@@ -718,10 +751,23 @@ async function fileSymbolsBatched(components, tmpdir, opts = {}) {     if (!byLib.has(d.path)) byLib.set(d.path, { name: d.name, comps: [] });     byLib.get(d.path).comps.push(c);   }+  const countSyms = t => (t.match(/\(property "Reference"/g) || []).length;   for (const [pth, grp] of byLib) {-    DB.send.current = `symbols → ${baseNoExt(grp.name)}`; save();+    const nick = baseNoExt(grp.name);+    DB.send.current = `symbols → ${nick}`; save();+    // Read the existing library. SAFETY: only fall back to an empty template when the file is+    // genuinely ABSENT. If the read fails but the file EXISTS, refuse to write — never clobber a+    // user library we couldn't read. (This is the bug that once truncated real JLC libs to 1 symbol.)     const r = await adomDesktopJSON('read_file', { path: pth, encoding: 'utf8' });-    let text = (r.j && r.j.success && r.j.content) || '(kicad_symbol_lib (version 20211014) (generator chip-fetcher-lite)\n)\n';+    let text;+    if (r.j && r.j.success && typeof r.j.content === 'string') {+      text = r.j.content;+    } else {+      const ex = await runDesktopShell(`[ -f ${shq(pth)} ] && echo EXISTS || echo MISSING`, 20);+      if (/EXISTS/.test(ex)) { DB.send.errors.push(`symbols ${nick}: SKIPPED — couldn't read existing library; refusing to overwrite (nothing lost)`); continue; }+      text = '(kicad_symbol_lib (version 20211014) (generator chip-fetcher-lite)\n)\n';+    }+    const before = countSyms(text);     let added = 0;     for (const c of grp.comps) {       try {@@ -730,11 +776,14 @@ async function fileSymbolsBatched(components, tmpdir, opts = {}) {         const m = mergeSymbol(text, b.block, b.newN); text = m.text; if (!m.skipped) added++;       } catch (e) { DB.send.errors.push(`${c.mpn} symbol: ${e.message || e}`); }     }+    // SAFETY: never write a library that has FEWER symbols than it already had.+    const after = countSyms(text);+    if (after < before) { DB.send.errors.push(`symbols ${nick}: SKIPPED — write would drop ${before}→${after} symbols; refusing (no data lost)`); continue; }     await runDesktopShell(`cp ${shq(pth)} ${shq(pth + '.bak')} 2>/dev/null || true`, 20);-    const tmp = path.join(tmpdir, baseNoExt(grp.name) + '.kicad_sym'); fs.writeFileSync(tmp, text);+    const tmp = path.join(tmpdir, nick + '.kicad_sym'); fs.writeFileSync(tmp, text);     const sr = await sendFiles([tmp], dirOf(pth));-    if (sr.j && sr.j.success === false) DB.send.errors.push(`symbols ${baseNoExt(grp.name)}: send failed`);-    DB.send.current = `symbols → ${baseNoExt(grp.name)} (${added})`; save();+    if (sr.j && sr.j.success === false) DB.send.errors.push(`symbols ${nick}: send failed`);+    DB.send.current = `symbols → ${nick} (${added})`; save();   } } async function fileToLibrary(components, opts = {}) {