board-logic.mjs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. const VERIFIED = "cross_verified";
  2. const POWER_NET = /^(?:GND|AGND|DGND|PGND|EARTH|VCC|VDD|VBAT|PWR|\+)/i;
  3. const RTL_PORT = /^[A-Za-z_][A-Za-z0-9_$]*(?:\[[0-9]+\])?$/;
  4. const RESISTOR_REF = /^r(\d+)$/i;
  5. const RESISTOR_PAD = /^r(\d+)\.(\d+)$/i;
  6. const BALL_PREFIX = /^ball:(.+)$/i;
  7. const NET_PREFIX = /^net:(.+)$/i;
  8. const VALUE_PREFIX = /^value:(.+)$/i;
  9. const ENDPOINT = /^u\d+\.[a-z]+\d+$/i;
  10. const ANNOTATION_RESISTOR = /(?<![A-Za-z0-9.])R(\d+)\b/g;
  11. const VALUE_GRAMMAR = /^(?:\d+(?:\.\d+)?[rRkKmM]\d*|\d+[rRkKmM]|\d+(?:\.\d+)?(?:ohm|ohms|Ω)?)$/i;
  12. const PACKAGE_OR_DNP = /^(?:0603|0805|0402|1206|1210|2010|2512|dnp|nc|n\/?c)$/i;
  13. const CAPABILITY_ALIASES = {
  14. pwm: ["pwm", "pwm_output"],
  15. gpio_output: ["gpio_output", "digital_output"],
  16. gpio_input: ["gpio_input", "digital_input"],
  17. tach: ["tach", "tach_input"],
  18. fan_tach: ["fan_tach", "tach_input"],
  19. presence: ["presence", "presence_input"],
  20. };
  21. function text(value) {
  22. return value == null ? "" : String(value);
  23. }
  24. function normalized(value) {
  25. return text(value).trim().toLocaleLowerCase();
  26. }
  27. function naturalCompare(left, right) {
  28. return text(left).localeCompare(text(right), undefined, {numeric: true, sensitivity: "base"});
  29. }
  30. function capabilities(pin) {
  31. return Array.isArray(pin?.fpga?.capabilities) ? pin.fpga.capabilities.map(text) : [];
  32. }
  33. function baseBlockers(pin) {
  34. const blockers = [];
  35. if (pin?.evidence_tier !== VERIFIED || pin?.fpga?.evidence_tier !== VERIFIED) {
  36. blockers.push("unverified");
  37. }
  38. if (!pin?.fpga?.ball || !pin?.fpga?.io_standard) blockers.push("missing_fpga_assignment");
  39. if (pin?.mechanical === true || pin?.electrical !== true) blockers.push("mechanical_or_non_electrical");
  40. if (pin?.pad_role !== "contact") blockers.push("not_connector_contact");
  41. if (["power", "ground"].includes(pin?.function_category) || POWER_NET.test(text(pin?.net))) {
  42. blockers.push("power_or_ground");
  43. }
  44. if (pin?.reserved === true) blockers.push("reserved");
  45. if (pin?.fixed_load_conflict === true) blockers.push("fixed_load_conflict");
  46. if (["", "unknown"].includes(normalized(pin?.external_level))) blockers.push("external_level_unknown");
  47. return blockers;
  48. }
  49. export function connectorPinGroups(touchpoint) {
  50. const pins = Array.isArray(touchpoint?.pins) ? touchpoint.pins : [];
  51. const connector = touchpoint?.connector;
  52. const reviewed = connector?.review_status === VERIFIED;
  53. const grid = reviewed && Array.isArray(connector?.contact_grid) ? connector.contact_grid : [];
  54. const byNumber = new Map(
  55. pins
  56. .filter((pin) => pin?.pad_role === "contact" && text(pin?.number))
  57. .map((pin) => [text(pin.number), pin]),
  58. );
  59. const contactRows = grid.map((row) =>
  60. (Array.isArray(row) ? row : []).map((number) => byNumber.get(text(number))).filter(Boolean),
  61. );
  62. return {
  63. contactRows,
  64. contacts: contactRows.flat(),
  65. auxiliary: pins.filter((pin) => pin?.pad_role !== "contact"),
  66. };
  67. }
  68. function pinSearchFields(touchpoint, pin) {
  69. const programming = pin?.programming ?? {};
  70. return [
  71. ["pin", `${touchpoint.reference}.${pin.number}`],
  72. ["reference", touchpoint.reference],
  73. ["pin_number", pin.number],
  74. ["net", pin.net],
  75. ["summary", pin.summary],
  76. ["function", pin.function_category],
  77. ["direction", pin.direction],
  78. ["external_level", pin.external_level],
  79. ["fpga_ball", pin.fpga?.ball],
  80. ["board_signal", pin.fpga?.board_signal],
  81. ["capability", capabilities(pin).join(" ")],
  82. ["mcu_device", pin.mcu?.device],
  83. ["mcu_family", pin.mcu?.family],
  84. ["mcu_pin", pin.mcu?.device && pin.mcu?.pin ? `${pin.mcu.device}.${pin.mcu.pin}` : ""],
  85. ["mcu_signal", pin.mcu?.signal],
  86. ["mcu_capability", Array.isArray(pin.mcu?.capabilities) ? pin.mcu.capabilities.join(" ") : ""],
  87. ["path", Array.isArray(pin.path) ? pin.path.join(" ") : ""],
  88. ["programming_conclusion", programming.conclusion],
  89. ["network_explanation", programming.network_explanation],
  90. ["hdl_guidance", programming.hdl_guidance],
  91. ["connection_guidance", Array.isArray(programming.connection_guidance) ? programming.connection_guidance.join(" ") : ""],
  92. ["programming_constraints", Array.isArray(programming.constraints) ? programming.constraints.join(" ") : ""],
  93. ["programming_risks", Array.isArray(programming.risks) ? programming.risks.join(" ") : ""],
  94. ];
  95. }
  96. /**
  97. * Safe reference / identity match: exact, or prefix only when the next char is not a digit.
  98. * Prevents R12 ⊆ R1225 false positives.
  99. */
  100. export function identityMatch(candidate, query) {
  101. const value = normalized(candidate);
  102. const needle = normalized(query);
  103. if (!value || !needle) return 0;
  104. if (value === needle) return 3;
  105. if (value.startsWith(needle)) {
  106. const next = value.charAt(needle.length);
  107. if (!next || !/\d/.test(next)) return 2;
  108. return 0;
  109. }
  110. return 0;
  111. }
  112. function fieldScore(field, value, query, {allowIncludes = true} = {}) {
  113. const candidate = normalized(value);
  114. if (!candidate) return 0;
  115. const weights = {
  116. pin: 1200,
  117. reference: 1000,
  118. resistor: 1600,
  119. resistor_pad: 1500,
  120. value: 1400,
  121. fpga_ball: 900,
  122. mcu_pin: 900,
  123. mcu_signal: 840,
  124. mcu_device: 800,
  125. mcu_family: 780,
  126. mcu_capability: 720,
  127. net: 850,
  128. board_signal: 820,
  129. function: 760,
  130. capability: 720,
  131. pin_number: 620,
  132. summary: 500,
  133. path: 460,
  134. programming_conclusion: 700,
  135. network_explanation: 610,
  136. hdl_guidance: 590,
  137. connection_guidance: 570,
  138. programming_constraints: 540,
  139. programming_risks: 480,
  140. external_level: 420,
  141. direction: 360,
  142. };
  143. const weight = weights[field] ?? 200;
  144. if (field === "reference" || field === "resistor" || field === "resistor_pad" || field === "pin") {
  145. const grade = identityMatch(candidate, query);
  146. if (grade === 3) return weight;
  147. if (grade === 2) return weight - 120;
  148. return 0;
  149. }
  150. if (field === "fpga_ball") {
  151. // Identifiers: exact / token boundary only — never bare includes.
  152. if (candidate === query) return weight;
  153. return 0;
  154. }
  155. if (candidate === query) return weight;
  156. if (candidate.startsWith(query)) return weight - 120;
  157. if (allowIncludes && candidate.includes(query)) return weight - 240;
  158. return 0;
  159. }
  160. function resultId(type, reference, pinNumber = null) {
  161. return pinNumber == null ? `${type}:${reference}` : `${type}:${reference}.${pinNumber}`;
  162. }
  163. export function buildBoardIndex(data) {
  164. const resistorByReference = new Map();
  165. const resistorPadById = new Map();
  166. const valueTokenIndex = new Map();
  167. const netMembers = new Map();
  168. const relatedByPinId = new Map();
  169. const pushNet = (net, member) => {
  170. const key = text(net);
  171. if (!key) return;
  172. if (!netMembers.has(key)) netMembers.set(key, []);
  173. netMembers.get(key).push(member);
  174. };
  175. for (const resistor of data?.resistors ?? []) {
  176. const reference = text(resistor.reference);
  177. resistorByReference.set(reference, resistor);
  178. resistorByReference.set(normalized(reference), resistor);
  179. for (const token of resistor.value_tokens ?? []) {
  180. const key = normalized(token);
  181. if (!key) continue;
  182. if (!valueTokenIndex.has(key)) valueTokenIndex.set(key, []);
  183. valueTokenIndex.get(key).push(resistor);
  184. }
  185. for (const pad of resistor.pads ?? []) {
  186. const padId = text(pad.id) || `${reference}.pad-${pad.number}`;
  187. resistorPadById.set(padId, {resistor, pad});
  188. resistorPadById.set(`${reference}.${pad.number}`, {resistor, pad});
  189. pushNet(pad.net, {
  190. kind: "resistor_pad",
  191. reference,
  192. pinNumber: text(pad.number),
  193. touchpoint: null,
  194. resistor,
  195. pin: pad,
  196. });
  197. }
  198. }
  199. for (const touchpoint of data?.touchpoints ?? []) {
  200. for (const pin of touchpoint.pins ?? []) {
  201. pushNet(pin.net, {
  202. kind: "touchpoint",
  203. reference: touchpoint.reference,
  204. pinNumber: text(pin.number),
  205. touchpoint,
  206. resistor: null,
  207. pin,
  208. });
  209. if (Array.isArray(pin.related_resistors) && pin.related_resistors.length) {
  210. relatedByPinId.set(text(pin.id), pin.related_resistors);
  211. }
  212. }
  213. }
  214. for (const members of netMembers.values()) {
  215. members.sort((left, right) => {
  216. const referenceOrder = naturalCompare(left.reference, right.reference);
  217. return referenceOrder || naturalCompare(left.pinNumber, right.pinNumber);
  218. });
  219. }
  220. return {
  221. resistorByReference,
  222. resistorPadById,
  223. valueTokenIndex,
  224. netMembers,
  225. relatedByPinId,
  226. evidenceConflicts: Array.isArray(data?.evidence_conflicts) ? data.evidence_conflicts : [],
  227. };
  228. }
  229. function looksLikeResistanceToken(raw) {
  230. const needle = text(raw).trim();
  231. if (!needle) return false;
  232. if (PACKAGE_OR_DNP.test(needle)) return false;
  233. if (!VALUE_GRAMMAR.test(needle)) return false;
  234. if (/^\d{1,2}$/.test(needle)) return false; // short bare numbers need value: or 22R
  235. // Bare package-sized integers like 0805 already rejected; reject 4-digit bare
  236. // numbers that look like imperial package codes when no unit suffix present.
  237. if (/^\d{4}$/.test(needle) && !/[rRkKmM]|ohm|Ω/i.test(needle)) return false;
  238. return true;
  239. }
  240. /** Resolve exact net name from board index; case-sensitive first, then CI. */
  241. export function resolveExactNetName(data, query) {
  242. const raw = text(query).trim();
  243. if (!raw) return null;
  244. const index = buildBoardIndex(data);
  245. if (index.netMembers.has(raw)) return raw;
  246. const needle = normalized(raw);
  247. for (const name of index.netMembers.keys()) {
  248. if (normalized(name) === needle) return name;
  249. }
  250. return null;
  251. }
  252. export function parseBoardQuery(query) {
  253. const raw = text(query).trim();
  254. const needle = normalized(raw);
  255. if (!needle) return {kind: "empty", raw, needle};
  256. const ball = BALL_PREFIX.exec(raw);
  257. if (ball) return {kind: "ball", raw, needle: normalized(ball[1]), value: ball[1].trim()};
  258. const net = NET_PREFIX.exec(raw);
  259. if (net) return {kind: "net", raw, needle: normalized(net[1]), value: net[1].trim()};
  260. const value = VALUE_PREFIX.exec(raw);
  261. if (value) return {kind: "value", raw, needle: normalized(value[1]), value: value[1].trim()};
  262. const pad = RESISTOR_PAD.exec(needle);
  263. if (pad) {
  264. return {
  265. kind: "resistor_pad",
  266. raw,
  267. needle,
  268. reference: `R${pad[1]}`,
  269. padNumber: pad[2],
  270. };
  271. }
  272. const ref = RESISTOR_REF.exec(needle);
  273. if (ref) {
  274. return {
  275. kind: "resistor_ref",
  276. raw,
  277. needle,
  278. reference: `R${ref[1]}`,
  279. };
  280. }
  281. if (ENDPOINT.test(needle)) {
  282. return {kind: "endpoint", raw, needle, value: raw};
  283. }
  284. if (looksLikeResistanceToken(raw)) {
  285. return {kind: "value", raw, needle, value: raw};
  286. }
  287. return {kind: "text", raw, needle};
  288. }
  289. function sortResults(results) {
  290. const typeOrder = {
  291. resistor: 0,
  292. resistor_pad: 1,
  293. evidence_conflict: 2,
  294. touchpoint: 3,
  295. pin: 4,
  296. };
  297. return results.sort((left, right) => {
  298. if (right.score !== left.score) return right.score - left.score;
  299. const leftType = typeOrder[left.type] ?? 9;
  300. const rightType = typeOrder[right.type] ?? 9;
  301. if (leftType !== rightType) return leftType - rightType;
  302. const referenceOrder = naturalCompare(left.reference, right.reference);
  303. if (referenceOrder) return referenceOrder;
  304. return naturalCompare(left.pinNumber, right.pinNumber);
  305. });
  306. }
  307. function searchTouchpoints(data, needle, {ballOnly = false, endpoint = null} = {}) {
  308. const results = [];
  309. for (const touchpoint of data?.touchpoints ?? []) {
  310. if (!ballOnly && !endpoint) {
  311. const touchpointFields = [
  312. ["reference", touchpoint.reference],
  313. ["summary", touchpoint.summary],
  314. ["function", touchpoint.category],
  315. ];
  316. let touchpointScore = 0;
  317. let touchpointField = "";
  318. for (const [field, value] of touchpointFields) {
  319. const score = fieldScore(field, value, needle);
  320. if (score > touchpointScore) {
  321. touchpointScore = score;
  322. touchpointField = field;
  323. }
  324. }
  325. if (touchpointScore) {
  326. results.push({
  327. id: resultId("touchpoint", touchpoint.reference),
  328. type: "touchpoint",
  329. reference: touchpoint.reference,
  330. pinNumber: null,
  331. touchpoint,
  332. resistor: null,
  333. pin: null,
  334. matchedField: touchpointField,
  335. score: touchpointScore + 20,
  336. });
  337. }
  338. }
  339. for (const pin of touchpoint.pins ?? []) {
  340. let score = 0;
  341. let matchedField = "";
  342. if (ballOnly) {
  343. const ballScore = fieldScore("fpga_ball", pin.fpga?.ball, needle, {allowIncludes: false});
  344. if (!ballScore) continue;
  345. score = ballScore;
  346. matchedField = "fpga_ball";
  347. } else if (endpoint) {
  348. const endpointNeedle = normalized(endpoint);
  349. const candidates = [
  350. ["fpga_ball", `u3.${text(pin.fpga?.ball)}`],
  351. ["path", Array.isArray(pin.path) ? pin.path.join(" ") : ""],
  352. ["board_signal", pin.fpga?.board_signal],
  353. ["pin", `${touchpoint.reference}.${pin.number}`],
  354. ];
  355. for (const [field, value] of candidates) {
  356. const candidate = normalized(value);
  357. if (!candidate) continue;
  358. if (candidate === endpointNeedle || candidate.includes(endpointNeedle)) {
  359. const candidateScore = field === "fpga_ball" ? 950 : 700;
  360. if (candidateScore > score) {
  361. score = candidateScore;
  362. matchedField = field;
  363. }
  364. }
  365. }
  366. if (!score) continue;
  367. } else {
  368. for (const [field, value] of pinSearchFields(touchpoint, pin)) {
  369. const candidateScore = fieldScore(field, value, needle, {
  370. allowIncludes: field !== "fpga_ball" && field !== "reference" && field !== "pin",
  371. });
  372. if (candidateScore > score) {
  373. score = candidateScore;
  374. matchedField = field;
  375. }
  376. }
  377. if (!score) continue;
  378. if (baseBlockers(pin).length === 0) score += 40;
  379. }
  380. results.push({
  381. id: resultId("pin", touchpoint.reference, text(pin.number)),
  382. type: "pin",
  383. reference: touchpoint.reference,
  384. pinNumber: text(pin.number),
  385. touchpoint,
  386. resistor: null,
  387. pin,
  388. matchedField,
  389. score,
  390. });
  391. }
  392. }
  393. return results;
  394. }
  395. function pushNetMemberResults(results, members, score = 1400) {
  396. for (const member of members) {
  397. const isResistor = member.kind === "resistor_pad";
  398. results.push({
  399. id: resultId(isResistor ? "resistor_pad" : "pin", member.reference, member.pinNumber),
  400. type: isResistor ? "resistor_pad" : "pin",
  401. reference: member.reference,
  402. pinNumber: member.pinNumber,
  403. touchpoint: member.touchpoint,
  404. resistor: member.resistor,
  405. pin: member.pin,
  406. matchedField: "net",
  407. score,
  408. assemblyStatus: member.resistor?.assembly_status || null,
  409. });
  410. }
  411. }
  412. export function searchBoard(data, query) {
  413. let parsed = parseBoardQuery(query);
  414. if (parsed.kind === "empty") return [];
  415. const index = buildBoardIndex(data);
  416. let results = [];
  417. // Bare string that exactly equals an existing net → exact net query (same as net:).
  418. if (parsed.kind === "text") {
  419. const exactNet = resolveExactNetName(data, parsed.raw);
  420. if (exactNet) {
  421. parsed = {kind: "net", raw: parsed.raw, needle: normalized(exactNet), value: exactNet};
  422. }
  423. }
  424. if (parsed.kind === "resistor_pad") {
  425. const hit = index.resistorPadById.get(`${parsed.reference}.${parsed.padNumber}`);
  426. if (hit) {
  427. results.push({
  428. id: resultId("resistor_pad", parsed.reference, parsed.padNumber),
  429. type: "resistor_pad",
  430. reference: parsed.reference,
  431. pinNumber: parsed.padNumber,
  432. touchpoint: null,
  433. resistor: hit.resistor,
  434. pin: hit.pad,
  435. matchedField: "resistor_pad",
  436. score: 1550,
  437. });
  438. }
  439. return sortResults(results);
  440. }
  441. if (parsed.kind === "resistor_ref") {
  442. const resistor = index.resistorByReference.get(parsed.reference)
  443. || index.resistorByReference.get(normalized(parsed.reference));
  444. if (resistor) {
  445. results.push({
  446. id: resultId("resistor", parsed.reference),
  447. type: "resistor",
  448. reference: parsed.reference,
  449. pinNumber: null,
  450. touchpoint: null,
  451. resistor,
  452. pin: null,
  453. matchedField: "resistor",
  454. score: 1600,
  455. });
  456. }
  457. return sortResults(results);
  458. }
  459. if (parsed.kind === "ball") {
  460. return sortResults(searchTouchpoints(data, parsed.needle, {ballOnly: true}));
  461. }
  462. if (parsed.kind === "endpoint") {
  463. return sortResults(searchTouchpoints(data, parsed.needle, {endpoint: parsed.value}));
  464. }
  465. if (parsed.kind === "net") {
  466. const members =
  467. index.netMembers.get(text(parsed.value))
  468. || index.netMembers.get(parsed.value)
  469. || [];
  470. pushNetMemberResults(results, members, 1400);
  471. if (!results.length) {
  472. for (const [net, rows] of index.netMembers.entries()) {
  473. if (normalized(net) !== parsed.needle) continue;
  474. pushNetMemberResults(results, rows, 1400);
  475. }
  476. }
  477. return sortResults(results);
  478. }
  479. if (parsed.kind === "value") {
  480. const seen = new Set();
  481. const addResistor = (resistor, score = 1400) => {
  482. const reference = text(resistor.reference);
  483. if (seen.has(reference)) return;
  484. seen.add(reference);
  485. const notFitted = resistor.assembly_status === "not_fitted";
  486. results.push({
  487. id: resultId("resistor", reference),
  488. type: "resistor",
  489. reference,
  490. pinNumber: null,
  491. touchpoint: null,
  492. resistor,
  493. pin: null,
  494. matchedField: "value",
  495. score: notFitted ? score - 200 : score,
  496. assemblyStatus: resistor.assembly_status || "unknown",
  497. notFitted,
  498. });
  499. };
  500. for (const resistor of index.valueTokenIndex.get(parsed.needle) ?? []) {
  501. addResistor(resistor, 1450);
  502. }
  503. for (const resistor of data?.resistors ?? []) {
  504. for (const token of resistor.value_tokens ?? []) {
  505. if (normalized(token) === parsed.needle) addResistor(resistor, 1450);
  506. }
  507. if (normalized(resistor.component_value) === parsed.needle) addResistor(resistor, 1400);
  508. }
  509. return sortResults(results);
  510. }
  511. // Free-text (non-exact-net): touchpoints/pins; value tokens; never bare R# here.
  512. results = searchTouchpoints(data, parsed.needle);
  513. for (const resistor of index.valueTokenIndex.get(parsed.needle) ?? []) {
  514. results.push({
  515. id: resultId("resistor", resistor.reference),
  516. type: "resistor",
  517. reference: resistor.reference,
  518. pinNumber: null,
  519. touchpoint: null,
  520. resistor,
  521. pin: null,
  522. matchedField: "value",
  523. score: resistor.assembly_status === "not_fitted" ? 1100 : 1300,
  524. assemblyStatus: resistor.assembly_status || "unknown",
  525. notFitted: resistor.assembly_status === "not_fitted",
  526. });
  527. }
  528. for (const conflict of index.evidenceConflicts) {
  529. const hay = normalized([
  530. conflict.subject_reference,
  531. conflict.summary,
  532. ...(conflict.claims || []).map((claim) => JSON.stringify(claim)),
  533. ].join(" "));
  534. if (hay.includes(parsed.needle) && conflict.status === "unresolved") {
  535. results.push({
  536. id: resultId("evidence_conflict", conflict.subject_reference || conflict.id),
  537. type: "evidence_conflict",
  538. reference: conflict.subject_reference || conflict.id,
  539. pinNumber: null,
  540. touchpoint: null,
  541. resistor: index.resistorByReference.get(conflict.subject_reference) || null,
  542. pin: null,
  543. matchedField: "evidence_conflict",
  544. score: 200,
  545. evidenceConflict: conflict,
  546. });
  547. }
  548. }
  549. return sortResults(results);
  550. }
  551. /** Compatibility: touchpoint pins only (does not include resistor pads). */
  552. export function sameNetPins(data, net) {
  553. const wanted = text(net);
  554. if (!wanted) return [];
  555. const matches = [];
  556. for (const touchpoint of data?.touchpoints ?? []) {
  557. for (const pin of touchpoint.pins ?? []) {
  558. if (pin.net === wanted) {
  559. matches.push({
  560. kind: "touchpoint",
  561. reference: touchpoint.reference,
  562. pinNumber: text(pin.number),
  563. touchpoint,
  564. resistor: null,
  565. pin,
  566. });
  567. }
  568. }
  569. }
  570. return matches.sort((left, right) => {
  571. const referenceOrder = naturalCompare(left.reference, right.reference);
  572. return referenceOrder || naturalCompare(left.pinNumber, right.pinNumber);
  573. });
  574. }
  575. /** Touchpoint pins + resistor pads sharing the PCB net. */
  576. export function sameNetMembers(data, net) {
  577. const wanted = text(net);
  578. if (!wanted) return [];
  579. const index = buildBoardIndex(data);
  580. const members = index.netMembers.get(wanted) || [];
  581. if (members.length) return members.map((item) => ({...item}));
  582. // Case-insensitive fallback
  583. for (const [name, rows] of index.netMembers.entries()) {
  584. if (normalized(name) === normalized(wanted)) {
  585. return rows.map((item) => ({...item}));
  586. }
  587. }
  588. return [];
  589. }
  590. export function extractPathResistors(data, ...texts) {
  591. const index = new Map((data?.resistors ?? []).map((item) => [text(item.reference), item]));
  592. const ordered = [];
  593. const seen = new Set();
  594. for (const value of texts) {
  595. const chunks = Array.isArray(value) ? value : [value];
  596. for (const chunk of chunks) {
  597. const source = text(chunk);
  598. if (!source) continue;
  599. ANNOTATION_RESISTOR.lastIndex = 0;
  600. let match;
  601. while ((match = ANNOTATION_RESISTOR.exec(source))) {
  602. const reference = `R${match[1]}`;
  603. if (seen.has(reference)) continue;
  604. seen.add(reference);
  605. const resistor = index.get(reference);
  606. if (!resistor) {
  607. throw new Error(`annotation resistor ${reference} missing from resistor index`);
  608. }
  609. ordered.push(resistor);
  610. }
  611. }
  612. }
  613. return ordered;
  614. }
  615. export function findCandidates(data, capability) {
  616. const wanted = normalized(capability);
  617. if (!wanted) return [];
  618. const acceptedCapabilities = new Set(
  619. (CAPABILITY_ALIASES[wanted] ?? [wanted]).map(normalized),
  620. );
  621. const candidates = [];
  622. for (const touchpoint of data?.touchpoints ?? []) {
  623. for (const pin of touchpoint.pins ?? []) {
  624. const pinCapabilities = capabilities(pin).map(normalized);
  625. if (!pinCapabilities.some((item) => acceptedCapabilities.has(item))) continue;
  626. if (wanted === "gpio" && !["gpio", "direct_gpio"].includes(normalized(pin.function_category))) {
  627. continue;
  628. }
  629. if (baseBlockers(pin).length) continue;
  630. const purpose = text(pin.summary).trim();
  631. const polarity = normalized(pin.polarity);
  632. const details = [];
  633. if (purpose) details.push(`用途 ${purpose}`);
  634. if (polarity && polarity !== "unknown") details.push(`极性 ${pin.polarity}`);
  635. candidates.push({
  636. reference: touchpoint.reference,
  637. touchpoint,
  638. pin,
  639. reason: `${details.length ? `${details.join(";")};` : ""}能力 ${capability} 匹配;已验证 FPGA 路径至 ${pin.fpga.ball};外部电平 ${pin.external_level}。`,
  640. warning: "只证明物理可用性,仍需检查当前工程约束冲突。",
  641. });
  642. }
  643. }
  644. return candidates.sort((left, right) => {
  645. const categoryMatchLeft = normalized(left.pin.function_category) === wanted ? 1 : 0;
  646. const categoryMatchRight = normalized(right.pin.function_category) === wanted ? 1 : 0;
  647. if (categoryMatchRight !== categoryMatchLeft) return categoryMatchRight - categoryMatchLeft;
  648. const referenceOrder = naturalCompare(left.reference, right.reference);
  649. return referenceOrder || naturalCompare(left.pin.number, right.pin.number);
  650. });
  651. }
  652. export function isValidRtlPortName(name) {
  653. return RTL_PORT.test(text(name));
  654. }
  655. /** Back SVG export uses KiCad --mirror about the vertical/Y axis (left-right flip). */
  656. export const BACK_MIRROR_AXIS = "y";
  657. export function mirrorBoardX(x, boardWidth) {
  658. const width = Number(boardWidth);
  659. const value = Number(x);
  660. if (!Number.isFinite(width) || !Number.isFinite(value)) return value;
  661. return width - value;
  662. }
  663. export function displayPoint(point, boardWidth, viewingSide) {
  664. const x = Number(point?.x);
  665. const y = Number(point?.y);
  666. if (viewingSide !== "back") return {x, y};
  667. return {x: mirrorBoardX(x, boardWidth), y};
  668. }
  669. export function displayBounds(bounds, boardWidth, viewingSide) {
  670. const x = Number(bounds?.x);
  671. const y = Number(bounds?.y);
  672. const width = Number(bounds?.width);
  673. const height = Number(bounds?.height);
  674. if (viewingSide !== "back") {
  675. return {x, y, width, height};
  676. }
  677. return {
  678. x: mirrorBoardX(x + width, boardWidth),
  679. y,
  680. width,
  681. height,
  682. };
  683. }
  684. export function itemVisibleOnSide(item, viewingSide) {
  685. return (item?.side || "front") === viewingSide;
  686. }
  687. export function generateAdcSnippet(pin, rtlPortName, runtimeStatus = {}) {
  688. if (runtimeStatus.adcCopyEnabled !== true) {
  689. throw new Error("源数据已过期,ADC 复制已关闭。");
  690. }
  691. if (!isValidRtlPortName(rtlPortName)) {
  692. throw new Error("生成 ADC 前请输入合法的 RTL 端口名。");
  693. }
  694. if (baseBlockers(pin).length) {
  695. throw new Error("此针脚不具备 ADC 生成资格。");
  696. }
  697. const ball = text(pin.fpga.ball);
  698. const ioStandard = text(pin.fpga.io_standard);
  699. if (!/^[A-Z]+[0-9]+$/.test(ball) || !/^[A-Za-z0-9_.+-]+$/.test(ioStandard)) {
  700. throw new Error("已验证 FPGA 分配包含不安全的 ADC 值。");
  701. }
  702. const assignments = [`LOCATION = ${ball}`, `IOSTANDARD = ${ioStandard}`];
  703. if (pin.adc_pulltype != null) {
  704. const pulltype = text(pin.adc_pulltype);
  705. if (!/^[A-Z][A-Z0-9_]*$/.test(pulltype)) {
  706. throw new Error("人工注释的 PULLTYPE 包含不安全值。");
  707. }
  708. assignments.push(`PULLTYPE = ${pulltype}`);
  709. }
  710. return `set_pin_assignment { ${rtlPortName} } { ${assignments.join("; ")}; }`;
  711. }