TypeScript
perf(web): reuse repeated inline skill lookups (#29008)
luked61058debf93
diff --git a/packages/shared/src/inlineSkills.test.ts b/packages/shared/src/inlineSkills.test.tsindex 9413148cee9..dde40480cab 100644--- a/packages/shared/src/inlineSkills.test.ts+++ b/packages/shared/src/inlineSkills.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vite-plus/test";-import { formatProviderSkillDisplayName } from "./inlineSkills.ts";+import { formatProviderSkillDisplayName, matchInlineSkills } from "./inlineSkills.ts";describe("formatProviderSkillDisplayName", () => {it.each([@@ -17,3 +17,26 @@ describe("formatProviderSkillDisplayName", () => {);});});++describe("matchInlineSkills", () => {+ it("preserves offsets, skill identity, first-name precedence, and unknown tokens", () => {+ const first = { name: "design", displayName: "Design" };+ const duplicate = { name: "design", displayName: "Other design" };+ const namespaced = { name: "pdf:pdf" };+ const matches = [+ ...matchInlineSkills("Use $design then $missing and $pdf:pdf, $pdf:pdf $design", [+ first,+ duplicate,+ namespaced,+ ]),+ ];+ expect(matches).toEqual([+ { start: 4, end: 11, skill: first, rawText: "$design" },+ { start: 40, end: 48, skill: namespaced, rawText: "$pdf:pdf" },+ { start: 49, end: 56, skill: first, rawText: "$design" },+ ]);+ expect(matches[0]?.skill).toBe(first);+ expect(matches[1]?.skill).toBe(namespaced);+ expect(matches[2]?.skill).toBe(first);+ });+});diff --git a/packages/shared/src/inlineSkills.ts b/packages/shared/src/inlineSkills.tsindex 7a8c05f4e2b..aacbc38cf65 100644--- a/packages/shared/src/inlineSkills.ts+++ b/packages/shared/src/inlineSkills.ts@@ -15,9 +15,16 @@ export function* matchInlineSkills<Skill extends InlineSkill>(text: string,skills: readonly Skill[],) {+ const byName = new Map<string, Skill | undefined>();for (const match of text.matchAll(SKILL_TOKEN_REGEX)) {const name = match[2] ?? "";- const skill = skills.find((candidate) => candidate.name === name);+ if (!byName.has(name)) {+ byName.set(+ name,+ skills.find((candidate) => candidate.name === name),+ );+ }+ const skill = byName.get(name);if (!skill) continue;const start = match.index + (match[1]?.length ?? 0);yield { start, end: match.index + match[0].length, skill, rawText: `$${name}` };