// Pure ranking logic shared by application and command search. No process execution. function normalize(text) { return String(text || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim(); } function score(text, needle) { if (!needle) return 0; if (text === needle) return 10000; if (text.startsWith(needle)) return 8000 - Math.min(text.length, 500); const inside = text.indexOf(needle); if (inside >= 0) return 6000 - inside * 4 - Math.min(text.length, 500); let cursor = 0, previous = -1, value = 1000; for (const letter of needle) { const index = text.indexOf(letter, cursor); if (index < 0) return -Infinity; value += index === previous + 1 ? 30 : 0; if (index === 0 || /[\s._/-]/.test(text[index - 1])) value += 45; value -= index - cursor; previous = index; cursor = index + 1; } return value - Math.min(text.length, 500); } function index(items) { return items.map(item => ({item:item,fields:item.fields.map(field => ({text:normalize(field.text),penalty:field.penalty || 0}))})); } function rank(indexed, query, limit) { const tokens = normalize(query).split(/\s+/).filter(Boolean); const matches = []; for (const row of indexed) { let total = 0; for (const token of tokens) { const best = Math.max(...row.fields.map(field => score(field.text,token) - field.penalty)); if (!Number.isFinite(best)) {total=-Infinity;break;} total += best; } if (Number.isFinite(total)) matches.push({item:row.item,score:total}); } matches.sort((a,b) => b.score-a.score || a.item.title.localeCompare(b.item.title) || a.item.id.localeCompare(b.item.id)); return matches.slice(0,limit).map(row => row.item); }