parse-filter.ts 19 KB

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