Skip to content

Commit 18953c3

Browse files
committed
Create dnr.ts
1 parent 65e18bb commit 18953c3

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

src/pkg/utils/dnr.ts

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
export const isValidDNRUrlFilter = (text: string) => {
2+
// https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest?hl=en#property-RuleCondition-urlFilter
3+
4+
const domainNameAnchor = text.startsWith("||");
5+
6+
const leftAnchor = !domainNameAnchor && text.startsWith("|");
7+
8+
const rightAnchor = text.endsWith("|");
9+
10+
try {
11+
let s = text;
12+
13+
if (domainNameAnchor) s = s.slice(2);
14+
if (leftAnchor) s = s.slice(1);
15+
if (rightAnchor) s = s.slice(0, -1);
16+
17+
const t = s.replace(/\*/g, "").replace(/^/g, "_");
18+
19+
// eslint-disable-next-line no-control-regex
20+
if (/[^\x00-\xFF]/.test(t)) return false;
21+
22+
new URL(t);
23+
24+
return true;
25+
} catch {
26+
return false;
27+
}
28+
};
29+
30+
export const convertDomainToDNRUrlFilter = (text: string) => {
31+
// will match its domain and subdomain
32+
let ret;
33+
text = text.toLowerCase();
34+
try {
35+
if (text.startsWith("http") && /^http[s*]?:\/\//.test(text)) {
36+
const u = new URL(`${text.replace("http*://", "http-wildcard://")}`);
37+
ret = `|${u.origin.replace("http-wildcard://", "http://")}`;
38+
} else {
39+
const u = new URL(`https://${text}/`);
40+
ret = `||${u.hostname}`;
41+
}
42+
} catch {
43+
throw new Error("invalid domain");
44+
}
45+
return ret;
46+
};

0 commit comments

Comments
 (0)