parse-filter.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. import { NetworkFilter } from '@ghostery/adblocker';
  2. import { processLine } from './process-line';
  3. import tldts from 'tldts-experimental';
  4. import picocolors from 'picocolors';
  5. import { normalizeDomain } from './normalize-domain';
  6. import { deserializeArray, fsFetchCache, serializeArray, getFileContentHash } from './cache-filesystem';
  7. import type { Span } from '../trace';
  8. import createKeywordFilter from './aho-corasick';
  9. import { looseTldtsOpt } from '../constants/loose-tldts-opt';
  10. import { identity } from './misc';
  11. const DEBUG_DOMAIN_TO_FIND: string | null = null; // example.com | null
  12. let foundDebugDomain = false;
  13. const temporaryBypass = typeof DEBUG_DOMAIN_TO_FIND === 'string';
  14. function domainListLineCb(l: string, set: string[], includeAllSubDomain: boolean, meta: string) {
  15. let line = processLine(l);
  16. if (!line) return;
  17. line = line.toLowerCase();
  18. const domain = normalizeDomain(line);
  19. if (!domain) return;
  20. if (domain !== line) {
  21. console.log(
  22. picocolors.red('[process domain list]'),
  23. picocolors.gray(`line: ${line}`),
  24. picocolors.gray(`domain: ${domain}`),
  25. picocolors.gray(meta)
  26. );
  27. return;
  28. }
  29. if (DEBUG_DOMAIN_TO_FIND && line.includes(DEBUG_DOMAIN_TO_FIND)) {
  30. console.warn(picocolors.red(meta), '(black)', line.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND)));
  31. foundDebugDomain = true;
  32. }
  33. set.push(includeAllSubDomain ? `.${line}` : line);
  34. }
  35. export function processDomainLists(
  36. span: Span,
  37. domainListsUrl: string, mirrors: string[] | null, includeAllSubDomain = false,
  38. ttl: number | null = null, extraCacheKey: (input: string) => string = identity
  39. ) {
  40. return span.traceChild(`process domainlist: ${domainListsUrl}`).traceAsyncFn((childSpan) => fsFetchCache.applyWithHttp304AndMirrors<string[]>(
  41. domainListsUrl,
  42. mirrors ?? [],
  43. extraCacheKey(getFileContentHash(__filename)),
  44. (text) => {
  45. const domainSets: string[] = [];
  46. const filterRules = text.split('\n');
  47. childSpan.traceChild('parse domain list').traceSyncFn(() => {
  48. for (let i = 0, len = filterRules.length; i < len; i++) {
  49. domainListLineCb(filterRules[i], domainSets, includeAllSubDomain, domainListsUrl);
  50. }
  51. });
  52. return domainSets;
  53. },
  54. {
  55. ttl,
  56. temporaryBypass,
  57. serializer: serializeArray,
  58. deserializer: deserializeArray
  59. }
  60. ));
  61. }
  62. function hostsLineCb(l: string, set: string[], includeAllSubDomain: boolean, meta: string) {
  63. const line = processLine(l);
  64. if (!line) {
  65. return;
  66. }
  67. const _domain = line.split(/\s/)[1]?.trim();
  68. if (!_domain) {
  69. return;
  70. }
  71. const domain = normalizeDomain(_domain);
  72. if (!domain) {
  73. return;
  74. }
  75. if (DEBUG_DOMAIN_TO_FIND && domain.includes(DEBUG_DOMAIN_TO_FIND)) {
  76. console.warn(picocolors.red(meta), '(black)', domain.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND)));
  77. foundDebugDomain = true;
  78. }
  79. set.push(includeAllSubDomain ? `.${domain}` : domain);
  80. }
  81. export function processHosts(
  82. span: Span,
  83. hostsUrl: string, mirrors: string[] | null, includeAllSubDomain = false,
  84. ttl: number | null = null, extraCacheKey: (input: string) => string = identity
  85. ) {
  86. return span.traceChild(`processhosts: ${hostsUrl}`).traceAsyncFn((childSpan) => fsFetchCache.applyWithHttp304AndMirrors<string[]>(
  87. hostsUrl,
  88. mirrors ?? [],
  89. extraCacheKey(getFileContentHash(__filename)),
  90. (text) => {
  91. const domainSets: string[] = [];
  92. const filterRules = text.split('\n');
  93. childSpan.traceChild('parse hosts').traceSyncFn(() => {
  94. for (let i = 0, len = filterRules.length; i < len; i++) {
  95. hostsLineCb(filterRules[i], domainSets, includeAllSubDomain, hostsUrl);
  96. }
  97. });
  98. return domainSets;
  99. },
  100. {
  101. ttl,
  102. temporaryBypass,
  103. serializer: serializeArray,
  104. deserializer: deserializeArray
  105. }
  106. ));
  107. }
  108. const enum ParseType {
  109. WhiteIncludeSubdomain = 0,
  110. WhiteAbsolute = -1,
  111. BlackAbsolute = 1,
  112. BlackIncludeSubdomain = 2,
  113. ErrorMessage = 10,
  114. Null = 1000
  115. }
  116. export { type ParseType };
  117. export async function processFilterRules(
  118. parentSpan: Span,
  119. filterRulesUrl: string,
  120. fallbackUrls?: string[] | null,
  121. ttl: number | null = null,
  122. allowThirdParty = false
  123. ): Promise<{ white: string[], black: string[], foundDebugDomain: boolean }> {
  124. const [white, black, warningMessages] = await parentSpan.traceChild(`process filter rules: ${filterRulesUrl}`).traceAsyncFn((span) => fsFetchCache.applyWithHttp304AndMirrors<Readonly<[ white: string[], black: string[], warningMessages: string[] ]>>(
  125. filterRulesUrl,
  126. fallbackUrls ?? [],
  127. getFileContentHash(__filename),
  128. (text) => {
  129. const whitelistDomainSets = new Set<string>();
  130. const blacklistDomainSets = new Set<string>();
  131. const warningMessages: string[] = [];
  132. const MUTABLE_PARSE_LINE_RESULT: [string, ParseType] = ['', 1000];
  133. /**
  134. * @param {string} line
  135. */
  136. const lineCb = (line: string) => {
  137. const result = parse(line, MUTABLE_PARSE_LINE_RESULT, allowThirdParty);
  138. const flag = result[1];
  139. if (flag === ParseType.Null) {
  140. return;
  141. }
  142. const hostname = result[0];
  143. if (DEBUG_DOMAIN_TO_FIND && hostname.includes(DEBUG_DOMAIN_TO_FIND)) {
  144. console.warn(
  145. picocolors.red(filterRulesUrl),
  146. flag === ParseType.WhiteIncludeSubdomain || flag === ParseType.WhiteAbsolute
  147. ? '(white)'
  148. : '(black)',
  149. hostname.replaceAll(DEBUG_DOMAIN_TO_FIND, picocolors.bold(DEBUG_DOMAIN_TO_FIND))
  150. );
  151. foundDebugDomain = true;
  152. }
  153. switch (flag) {
  154. case ParseType.WhiteIncludeSubdomain:
  155. if (hostname[0] === '.') {
  156. whitelistDomainSets.add(hostname);
  157. } else {
  158. whitelistDomainSets.add(`.${hostname}`);
  159. }
  160. break;
  161. case ParseType.WhiteAbsolute:
  162. whitelistDomainSets.add(hostname);
  163. break;
  164. case ParseType.BlackAbsolute:
  165. blacklistDomainSets.add(hostname);
  166. break;
  167. case ParseType.BlackIncludeSubdomain:
  168. if (hostname[0] === '.') {
  169. blacklistDomainSets.add(hostname);
  170. } else {
  171. blacklistDomainSets.add(`.${hostname}`);
  172. }
  173. break;
  174. case ParseType.ErrorMessage:
  175. warningMessages.push(hostname);
  176. break;
  177. default:
  178. break;
  179. }
  180. };
  181. const filterRules = text.split('\n');
  182. span.traceChild('parse adguard filter').traceSyncFn(() => {
  183. for (let i = 0, len = filterRules.length; i < len; i++) {
  184. lineCb(filterRules[i]);
  185. }
  186. });
  187. return [
  188. Array.from(whitelistDomainSets),
  189. Array.from(blacklistDomainSets),
  190. warningMessages
  191. ] as const;
  192. },
  193. {
  194. ttl,
  195. temporaryBypass,
  196. serializer: JSON.stringify,
  197. deserializer: JSON.parse
  198. }
  199. ));
  200. for (let i = 0, len = warningMessages.length; i < len; i++) {
  201. console.warn(
  202. picocolors.yellow(warningMessages[i]),
  203. picocolors.gray(picocolors.underline(filterRulesUrl))
  204. );
  205. }
  206. console.log(
  207. picocolors.gray('[process filter]'),
  208. picocolors.gray(filterRulesUrl),
  209. picocolors.gray(`white: ${white.length}`),
  210. picocolors.gray(`black: ${black.length}`)
  211. );
  212. return {
  213. white,
  214. black,
  215. foundDebugDomain
  216. };
  217. }
  218. // const R_KNOWN_NOT_NETWORK_FILTER_PATTERN_2 = /(\$popup|\$removeparam|\$popunder|\$cname)/;
  219. // cname exceptional filter can not be parsed by NetworkFilter
  220. // Surge / Clash can't handle CNAME either, so we just ignore them
  221. const kwfilter = createKeywordFilter([
  222. '!',
  223. '?',
  224. '*',
  225. '[',
  226. '(',
  227. ']',
  228. ')',
  229. ',',
  230. '#',
  231. '%',
  232. '&',
  233. '=',
  234. '~',
  235. // special modifier
  236. '$popup',
  237. '$removeparam',
  238. '$popunder',
  239. '$cname',
  240. '$frame',
  241. // some bad syntax
  242. '^popup'
  243. ]);
  244. export function parse($line: string, result: [string, ParseType], allowThirdParty: boolean): [hostname: string, flag: ParseType] {
  245. if (
  246. // doesn't include
  247. !$line.includes('.') // rule with out dot can not be a domain
  248. // includes
  249. || kwfilter($line)
  250. ) {
  251. result[1] = ParseType.Null;
  252. return result;
  253. }
  254. let line = $line.trim();
  255. /** @example line.length */
  256. const len = line.length;
  257. if (len === 0) {
  258. result[1] = ParseType.Null;
  259. return result;
  260. }
  261. const firstCharCode = line[0].charCodeAt(0);
  262. const lastCharCode = line[len - 1].charCodeAt(0);
  263. if (
  264. firstCharCode === 47 // 47 `/`
  265. // ends with
  266. || lastCharCode === 46 // 46 `.`, line.endsWith('.')
  267. || lastCharCode === 45 // 45 `-`, line.endsWith('-')
  268. || lastCharCode === 95 // 95 `_`, line.endsWith('_')
  269. // || line.includes('$popup')
  270. // || line.includes('$removeparam')
  271. // || line.includes('$popunder')
  272. ) {
  273. result[1] = ParseType.Null;
  274. return result;
  275. }
  276. if ((line.includes('/') || line.includes(':')) && !line.includes('://')) {
  277. result[1] = ParseType.Null;
  278. return result;
  279. }
  280. const filter = NetworkFilter.parse(line);
  281. if (filter) {
  282. if (
  283. // filter.isCosmeticFilter() // always false
  284. // filter.isNetworkFilter() // always true
  285. filter.isElemHide()
  286. || filter.isGenericHide()
  287. || filter.isSpecificHide()
  288. || filter.isRedirect()
  289. || filter.isRedirectRule()
  290. || filter.hasDomains()
  291. || filter.isCSP() // must not be csp rule
  292. || (!filter.fromAny() && !filter.fromDocument())
  293. ) {
  294. // not supported type
  295. result[1] = ParseType.Null;
  296. return result;
  297. }
  298. if (
  299. filter.hostname // filter.hasHostname() // must have
  300. && filter.isPlain() // isPlain() === !isRegex()
  301. && (!filter.isFullRegex())
  302. ) {
  303. const hostname = normalizeDomain(filter.hostname);
  304. if (!hostname) {
  305. result[1] = ParseType.Null;
  306. return result;
  307. }
  308. // |: filter.isHostnameAnchor(),
  309. // |: filter.isLeftAnchor(),
  310. // |https://: !filter.isHostnameAnchor() && (filter.fromHttps() || filter.fromHttp())
  311. const isIncludeAllSubDomain = filter.isHostnameAnchor();
  312. if (filter.isException() || filter.isBadFilter()) {
  313. result[0] = hostname;
  314. result[1] = isIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute;
  315. return result;
  316. }
  317. const _1p = filter.firstParty();
  318. const _3p = filter.thirdParty();
  319. if (_1p) {
  320. if (_1p === _3p) {
  321. result[0] = hostname;
  322. result[1] = isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  323. return result;
  324. }
  325. result[1] = ParseType.Null;
  326. return result;
  327. }
  328. if (_3p) {
  329. if (allowThirdParty) {
  330. result[0] = hostname;
  331. result[1] = isIncludeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  332. return result;
  333. }
  334. result[1] = ParseType.Null;
  335. return result;
  336. }
  337. }
  338. }
  339. // After NetworkFilter.parse, it means the line can not be parsed by cliqz NetworkFilter
  340. // We now need to "salvage" the line as much as possible
  341. /*
  342. * From now on, we are mostly facing non-standard domain rules (some are regex like)
  343. * We first skip third-party and frame rules, as Surge / Clash can't handle them
  344. *
  345. * `.sharecounter.$third-party`
  346. * `.bbelements.com^$third-party`
  347. * `://o0e.ru^$third-party`
  348. * `.1.1.1.l80.js^$third-party`
  349. */
  350. if (line.includes('$third-party')) {
  351. if (!allowThirdParty) {
  352. result[1] = ParseType.Null;
  353. return result;
  354. }
  355. line = line
  356. .replace('$third-party,', '$')
  357. .replace('$third-party', '');
  358. }
  359. /** @example line.endsWith('^') */
  360. const lineEndsWithCaret = lastCharCode === 94; // lastChar === '^';
  361. /** @example line.endsWith('^|') */
  362. const lineEndsWithCaretVerticalBar = (lastCharCode === 124 /** lastChar === '|' */) && line[len - 2] === '^';
  363. /** @example line.endsWith('^') || line.endsWith('^|') */
  364. const lineEndsWithCaretOrCaretVerticalBar = lineEndsWithCaret || lineEndsWithCaretVerticalBar;
  365. // whitelist (exception)
  366. if (
  367. firstCharCode === 64 // 64 `@`
  368. && line[1] === '@'
  369. ) {
  370. let whiteIncludeAllSubDomain = true;
  371. /**
  372. * Some "malformed" regex-based filters can not be parsed by NetworkFilter
  373. * "$genericblock`" is also not supported by NetworkFilter, see:
  374. * https://github.com/ghostery/adblocker/blob/62caf7786ba10ef03beffecd8cd4eec111bcd5ec/packages/adblocker/test/parsing.test.ts#L950
  375. *
  376. * `@@||cmechina.net^$genericblock`
  377. * `@@|ftp.bmp.ovh^|`
  378. * `@@|adsterra.com^|`
  379. * `@@.atlassian.net$document`
  380. * `@@||ad.alimama.com^$genericblock`
  381. */
  382. let sliceStart = 0;
  383. let sliceEnd: number | undefined;
  384. switch (line[2]) {
  385. case '|':
  386. // line.startsWith('@@|')
  387. sliceStart = 3;
  388. whiteIncludeAllSubDomain = false;
  389. if (line[3] === '|') { // line.startsWith('@@||')
  390. sliceStart = 4;
  391. whiteIncludeAllSubDomain = true;
  392. }
  393. break;
  394. case '.': { // line.startsWith('@@.')
  395. sliceStart = 3;
  396. whiteIncludeAllSubDomain = true;
  397. break;
  398. }
  399. case ':': {
  400. /**
  401. * line.startsWith('@@://')
  402. *
  403. * `@@://googleadservices.com^|`
  404. * `@@://www.googleadservices.com^|`
  405. */
  406. if (line[3] === '/' && line[4] === '/') {
  407. whiteIncludeAllSubDomain = false;
  408. sliceStart = 5;
  409. }
  410. break;
  411. }
  412. default:
  413. break;
  414. }
  415. if (lineEndsWithCaretOrCaretVerticalBar) {
  416. sliceEnd = -2;
  417. } else if (line.endsWith('$genericblock')) {
  418. sliceEnd = -13;
  419. if (line[len - 14] === '^') { // line.endsWith('^$genericblock')
  420. sliceEnd = -14;
  421. }
  422. } else if (line.endsWith('$document')) {
  423. sliceEnd = -9;
  424. if (line[len - 10] === '^') { // line.endsWith('^$document')
  425. sliceEnd = -10;
  426. }
  427. }
  428. if (sliceStart !== 0 || sliceEnd !== undefined) {
  429. const sliced = line.slice(sliceStart, sliceEnd);
  430. const domain = normalizeDomain(sliced);
  431. if (domain) {
  432. result[0] = domain;
  433. result[1] = whiteIncludeAllSubDomain ? ParseType.WhiteIncludeSubdomain : ParseType.WhiteAbsolute;
  434. return result;
  435. }
  436. result[0] = `[parse-filter E0001] (white) invalid domain: ${JSON.stringify({
  437. line, sliced, sliceStart, sliceEnd, domain
  438. })}`;
  439. result[1] = ParseType.ErrorMessage;
  440. return result;
  441. }
  442. result[0] = `[parse-filter E0006] (white) failed to parse: ${JSON.stringify({
  443. line, sliceStart, sliceEnd
  444. })}`;
  445. result[1] = ParseType.ErrorMessage;
  446. return result;
  447. }
  448. if (
  449. // 124 `|`
  450. // line.startsWith('|')
  451. firstCharCode === 124
  452. && lineEndsWithCaretOrCaretVerticalBar
  453. ) {
  454. /**
  455. * Some malformed filters can not be parsed by NetworkFilter:
  456. *
  457. * `||smetrics.teambeachbody.com^.com^`
  458. * `||solutions.|pages.indigovision.com^`
  459. * `||vystar..0rg@client.iebetanialaargentina.edu.co^`
  460. * `app-uat.latrobehealth.com.au^predirect.snapdeal.com`
  461. */
  462. const includeAllSubDomain = line[1] === '|';
  463. const sliceStart = includeAllSubDomain ? 2 : 1;
  464. const sliceEnd = lineEndsWithCaret
  465. ? -1
  466. : (lineEndsWithCaretVerticalBar ? -2 : undefined);
  467. const sliced = line.slice(sliceStart, sliceEnd); // we already make sure line startsWith "|"
  468. const domain = normalizeDomain(sliced);
  469. if (domain) {
  470. result[0] = domain;
  471. result[1] = includeAllSubDomain ? ParseType.BlackIncludeSubdomain : ParseType.BlackAbsolute;
  472. return result;
  473. }
  474. result[0] = `[parse-filter E0002] (black) invalid domain: ${sliced}`;
  475. result[1] = ParseType.ErrorMessage;
  476. return result;
  477. }
  478. const lineStartsWithSingleDot = firstCharCode === 46; // 46 `.`
  479. if (
  480. lineStartsWithSingleDot
  481. && lineEndsWithCaretOrCaretVerticalBar
  482. ) {
  483. /**
  484. * `.ay.delivery^`
  485. * `.m.bookben.com^`
  486. * `.wap.x4399.com^`
  487. */
  488. const sliced = line.slice(
  489. 1, // remove prefix dot
  490. lineEndsWithCaret // replaceAll('^', '')
  491. ? -1
  492. : (lineEndsWithCaretVerticalBar ? -2 : undefined) // replace('^|', '')
  493. );
  494. const suffix = tldts.getPublicSuffix(sliced, looseTldtsOpt);
  495. if (!suffix) {
  496. // This exclude domain-like resource like `1.1.4.514.js`
  497. result[1] = ParseType.Null;
  498. return result;
  499. }
  500. const domain = normalizeDomain(sliced);
  501. if (domain) {
  502. result[0] = domain;
  503. result[1] = ParseType.BlackIncludeSubdomain;
  504. return result;
  505. }
  506. result[0] = `[parse-filter E0003] (black) invalid domain: ${JSON.stringify({ sliced, domain })}`;
  507. result[1] = ParseType.ErrorMessage;
  508. return result;
  509. }
  510. /**
  511. * `|http://x.o2.pl^`
  512. * `://mine.torrent.pw^`
  513. * `://say.ac^`
  514. */
  515. if (lineEndsWithCaretOrCaretVerticalBar) {
  516. let sliceStart = 0;
  517. let sliceEnd;
  518. if (lineEndsWithCaret) { // line.endsWith('^')
  519. sliceEnd = -1;
  520. } else if (lineEndsWithCaretVerticalBar) { // line.endsWith('^|')
  521. sliceEnd = -2;
  522. }
  523. if (line.startsWith('://')) {
  524. sliceStart = 3;
  525. } else if (line.startsWith('http://')) {
  526. sliceStart = 7;
  527. } else if (line.startsWith('https://')) {
  528. sliceStart = 8;
  529. } else if (line.startsWith('|http://')) {
  530. sliceStart = 8;
  531. } else if (line.startsWith('|https://')) {
  532. sliceStart = 9;
  533. }
  534. if (sliceStart !== 0 || sliceEnd !== undefined) {
  535. const sliced = line.slice(sliceStart, sliceEnd);
  536. const domain = normalizeDomain(sliced);
  537. if (domain) {
  538. result[0] = domain;
  539. result[1] = ParseType.BlackIncludeSubdomain;
  540. return result;
  541. }
  542. result[0] = `[parse-filter E0004] (black) invalid domain: ${JSON.stringify({
  543. line, sliced, sliceStart, sliceEnd, domain
  544. })}`;
  545. result[1] = ParseType.ErrorMessage;
  546. return result;
  547. }
  548. }
  549. /**
  550. * `_vmind.qqvideo.tc.qq.com^`
  551. * `arketing.indianadunes.com^`
  552. * `charlestownwyllie.oaklawnnonantum.com^`
  553. * `-telemetry.officeapps.live.com^`
  554. * `-tracker.biliapi.net`
  555. * `-logging.nextmedia.com`
  556. * `_social_tracking.js^`
  557. */
  558. if (
  559. firstCharCode !== 124 // 124 `|`
  560. && lastCharCode === 94 // 94 `^`
  561. ) {
  562. const _domain = line.slice(0, -1);
  563. const suffix = tldts.getPublicSuffix(_domain, looseTldtsOpt);
  564. if (!suffix) {
  565. // This exclude domain-like resource like `_social_tracking.js^`
  566. result[1] = ParseType.Null;
  567. return result;
  568. }
  569. const domain = normalizeDomain(_domain);
  570. if (domain) {
  571. result[0] = domain;
  572. result[1] = ParseType.BlackAbsolute;
  573. return result;
  574. }
  575. result[0] = `[parse-filter E0005] (black) invalid domain: ${_domain}`;
  576. result[1] = ParseType.ErrorMessage;
  577. return result;
  578. }
  579. // Possibly that entire rule is domain
  580. /**
  581. * lineStartsWithSingleDot:
  582. *
  583. * `.cookielaw.js`
  584. * `.content_tracking.js`
  585. * `.ads.css`
  586. *
  587. * else:
  588. *
  589. * `_prebid.js`
  590. * `t.yesware.com`
  591. * `ubmcmm.baidustatic.com`
  592. * `://www.smfg-card.$document`
  593. * `portal.librus.pl$$advertisement-module`
  594. * `@@-ds.metric.gstatic.com^|`
  595. * `://gom.ge/cookie.js`
  596. * `://accout-update-smba.jp.$document`
  597. * `_200x250.png`
  598. * `@@://www.liquidweb.com/kb/wp-content/themes/lw-kb-theme/images/ads/vps-sidebar.jpg`
  599. */
  600. let sliceStart = 0;
  601. let sliceEnd: number | undefined;
  602. if (lineStartsWithSingleDot) {
  603. sliceStart = 1;
  604. }
  605. if (line.endsWith('^$all')) { // This salvage line `thepiratebay3.com^$all`
  606. sliceEnd = -5;
  607. } else if (
  608. // Try to salvage line like `://account.smba.$document`
  609. // For this specific line, it will fail anyway though.
  610. line.endsWith('$document')
  611. ) {
  612. sliceEnd = -9;
  613. } else if (line.endsWith('$badfilter')) {
  614. sliceEnd = -10;
  615. }
  616. const sliced = (sliceStart !== 0 || sliceEnd !== undefined) ? line.slice(sliceStart, sliceEnd) : line;
  617. const tryNormalizeDomain = normalizeDomain(sliced);
  618. if (tryNormalizeDomain === sliced) {
  619. // the entire rule is domain
  620. result[0] = sliced;
  621. result[1] = ParseType.BlackIncludeSubdomain;
  622. return result;
  623. }
  624. result[0] = `[parse-filter ${tryNormalizeDomain === null ? 'E0010' : 'E0011'}] can not parse: ${JSON.stringify({ line, tryNormalizeDomain, sliced })}`;
  625. result[1] = ParseType.ErrorMessage;
  626. return result;
  627. }