diff --git a/src/pkg/utils/match.test.ts b/src/pkg/utils/match.test.ts index 5258c24be..ae89d9b77 100644 --- a/src/pkg/utils/match.test.ts +++ b/src/pkg/utils/match.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { dealPatternMatches, parsePatternMatchesURL, UrlMatch } from "./match"; +import { v4 as uuidv4 } from "uuid"; // https://developer.chrome.com/docs/extensions/mv3/match_patterns/ describe("UrlMatch-google", () => { @@ -132,6 +133,16 @@ describe("UrlMatch-port2", () => { }); }); +describe("UrlMatch-exclude", () => { + it("exclue-port", () => { + const url = new UrlMatch(); + url.add("*://*/*", "ok3"); + url.exclude("*:5244*", "ok3"); + expect(url.match("http://test.list.ggnb.top:5244/search")).toEqual([]); + expect(url.match("http://test.list.ggnb.top:80/search")).toEqual(["ok3"]); + }); +}); + // https://developer.chrome.com/docs/extensions/mv3/match_patterns/ describe("dealPatternMatches", () => { it("https://developer.chrome.com/docs/extensions/develop/concepts/match-patterns?hl=zh-cn#examples", () => { @@ -299,3 +310,50 @@ describe("parsePatternMatchesURL", () => { }); }); }); + +const makeUrlMatcher = (uuid: string, matchesList: string[], excludeMatchesList: string[]) => { + const patternMatches = dealPatternMatches(matchesList); + const matchesResult = patternMatches.result; + const matches = patternMatches.patternResult; + const result = dealPatternMatches(excludeMatchesList, { + exclude: true, + }); + const excludeMatchesResult = result.result; + const excludeMatches = result.patternResult; + + const urlMatcher = new UrlMatch(); + for (const match of matchesResult) { + urlMatcher.add(match, uuid); + } + for (const exclude of excludeMatchesResult) { + urlMatcher.exclude(exclude, uuid); + } + + return { urlMatcher, matches, excludeMatches }; +}; + +describe("UrlMatch-exclusion", () => { + it("exclusion-1", () => { + const matchesList: string[] = ["*://**/*"]; + const excludeMatchesList: string[] = [ + "*://steamcommunity.com/*", + "*.jd.com/*", + "*docs.google.com/*", + "*://*.amazon.tld/*", + "*shop*", + "/.*(? { search: match[5], }; } - // 处理一些特殊情况 - switch (url) { - case "*": - case "http*": - return { - scheme: "*", - host: "*", - path: "*", - search: "*", - }; - default: - // 无*://的情况 - if (!url.includes("://")) { - // 直接转为通配符 - const match = /^(.*?)((\/.*?)(\?.*?|)|)$/.exec(url); - if (match) { - return { - scheme: "*", - host: match[1], - path: match[3] || (url[url.length - 1] === "*" ? "*" : "/"), - search: match[4], - }; - } - } - } return undefined; } protected compileRe(url: string): string { const u = this.parseURL(url); if (!u) { - return ""; + // 直接将*替换为正则 + return url.replace(/\*/g, ".*"); } switch (u.scheme) { case "*": @@ -82,7 +58,7 @@ export default class Match { } // 处理顶域 if (u.host.endsWith("tld")) { - u.host = `${u.host.substr(0, u.host.length - 3)}.*?`; + u.host = `${u.host.substring(0, u.host.length - 3)}.*?`; } // 处理端口 const pos2 = u.host.indexOf(":");