parse-filter.ts 20 KB

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