Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

providerSkillSearch.ts

104 lines2.6 KB

1import type { ServerProviderSkill } from "@t3tools/contracts";
2import { formatProviderSkillDisplayName } from "@t3tools/client-runtime/providerSkills";
3import {
4 insertRankedSearchResult,
5 normalizeSearchQuery,
6 scoreQueryMatch,
7} from "@t3tools/shared/searchRanking";
8​
9export function scoreProviderSkill(skill: ServerProviderSkill, query: string): number | null {
10 const normalizedName = skill.name.toLowerCase();
11 const normalizedLabel = formatProviderSkillDisplayName(skill).toLowerCase();
12 const normalizedShortDescription = skill.shortDescription?.toLowerCase() ?? "";
13 const normalizedDescription = skill.description?.toLowerCase() ?? "";
14 const normalizedScope = skill.scope?.toLowerCase() ?? "";
15​
16 const scores = [
17 scoreQueryMatch({
18 value: normalizedName,
19 query,
20 exactBase: 0,
21 prefixBase: 2,
22 boundaryBase: 4,
23 includesBase: 6,
24 fuzzyBase: 100,
25 boundaryMarkers: ["-", "_", "/"],
26 }),
27 scoreQueryMatch({
28 value: normalizedLabel,
29 query,
30 exactBase: 1,
31 prefixBase: 3,
32 boundaryBase: 5,
33 includesBase: 7,
34 fuzzyBase: 110,
35 }),
36 scoreQueryMatch({
37 value: normalizedShortDescription,
38 query,
39 exactBase: 20,
40 prefixBase: 22,
41 boundaryBase: 24,
42 includesBase: 26,
43 }),
44 scoreQueryMatch({
45 value: normalizedDescription,
46 query,
47 exactBase: 30,
48 prefixBase: 32,
49 boundaryBase: 34,
50 includesBase: 36,
51 }),
52 scoreQueryMatch({
53 value: normalizedScope,
54 query,
55 exactBase: 40,
56 prefixBase: 42,
57 includesBase: 44,
58 }),
59 ].filter((score): score is number => score !== null);
60​
61 if (scores.length === 0) {
62 return null;
63 }
64​
65 return Math.min(...scores);
67​
68export function searchProviderSkills(
69 skills: ReadonlyArray<ServerProviderSkill>,
70 query: string,
71 limit = Number.POSITIVE_INFINITY,
72): ServerProviderSkill[] {
73 const enabledSkills = skills.filter((skill) => skill.enabled);
74 const normalizedQuery = normalizeSearchQuery(query, { trimLeadingPattern: /^\$+/ });
75​
76 if (!normalizedQuery) {
77 return enabledSkills;
78 }
79​
80 const ranked: Array<{
81 item: ServerProviderSkill;
82 score: number;
83 tieBreaker: string;
84 }> = [];
85​
86 for (const skill of enabledSkills) {
87 const score = scoreProviderSkill(skill, normalizedQuery);
88 if (score === null) {
89 continue;
90 }
91​
92 insertRankedSearchResult(
93 ranked,
94 {
95 item: skill,
96 score,
97 tieBreaker: `${formatProviderSkillDisplayName(skill).toLowerCase()}\u0000${skill.name}`,
98 },
99 limit,
100 );
101 }
102​
103 return ranked.map((entry) => entry.item);