perf(automod): bundle automod regex patterns for potentially increased performance

This commit is contained in:
Dragory 2021-10-05 21:30:35 +03:00
parent 5e25792734
commit 392e2da2d1
No known key found for this signature in database
GPG key ID: 5F387BA66DF8AAC1

View file

@ -13,6 +13,8 @@ interface MatchResultType {
type: MatchableTextType; type: MatchableTextType;
} }
const combinedRegexCache: WeakMap<any, RegExp> = new WeakMap();
export const MatchRegexTrigger = automodTrigger<MatchResultType>()({ export const MatchRegexTrigger = automodTrigger<MatchResultType>()({
configType: t.type({ configType: t.type({
patterns: t.array(TRegex), patterns: t.array(TRegex),
@ -53,17 +55,21 @@ export const MatchRegexTrigger = automodTrigger<MatchResultType>()({
str = normalizeText(str); str = normalizeText(str);
} }
for (const sourceRegex of trigger.patterns) { if (!combinedRegexCache.has(trigger)) {
const regex = new RegExp(sourceRegex.source, trigger.case_sensitive && !sourceRegex.ignoreCase ? "" : "i"); const combinedPattern = trigger.patterns.map((p) => `(?:${p.source})`).join("|");
const matches = await pluginData.state.regexRunner.exec(regex, str).catch(allowTimeout); const combinedRegex = new RegExp(combinedPattern, trigger.case_sensitive ? "" : "i");
if (matches?.length) { combinedRegexCache.set(trigger, combinedRegex);
return { }
extra: {
pattern: sourceRegex.source, const regex = combinedRegexCache.get(trigger)!;
type, const matches = await pluginData.state.regexRunner.exec(regex, str).catch(allowTimeout);
}, if (matches?.length) {
}; return {
} extra: {
pattern: "<temporarily hidden>",
type,
},
};
} }
} }