套壳油猴的广告拦截脚本

将 ABP 中的元素隐藏规则转换为 CSS 使用

目前为 2023-07-03 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name AdBlock Script for WebView
  3. // @name:zh-CN 套壳油猴的广告拦截脚本
  4. // @author Lemon399
  5. // @version 2.6.1
  6. // @description Parse ABP Cosmetic rules to CSS and apply it.
  7. // @description:zh-CN 将 ABP 中的元素隐藏规则转换为 CSS 使用
  8. // @resource jiekouAD https://raw.fastgit.ixmu.net/damengzhu/banad/main/jiekouAD.txt
  9. // @resource CSSRule https://raw.fastgit.ixmu.net/damengzhu/abpmerge/main/CSSRule.txt
  10. // @match *://*/*
  11. // @run-at document-start
  12. // @grant unsafeWindow
  13. // @grant GM_registerMenuCommand
  14. // @grant GM.registerMenuCommand
  15. // @grant GM_unregisterMenuCommand
  16. // @grant GM.unregisterMenuCommand
  17. // @grant GM_getValue
  18. // @grant GM.getValue
  19. // @grant GM_deleteValue
  20. // @grant GM.deleteValue
  21. // @grant GM_setValue
  22. // @grant GM.setValue
  23. // @grant GM_addStyle
  24. // @grant GM.addStyle
  25. // @grant GM_xmlhttpRequest
  26. // @grant GM.xmlHttpRequest
  27. // @grant GM_getResourceText
  28. // @grant GM.getResourceText
  29. // @grant GM_download
  30. // @grant GM.download
  31. // @grant GM_listValues
  32. // @grant GM.listValues
  33. // @namespace https://lemon399-bitbucket-io.vercel.app/
  34. // @source https://gitee.com/lemon399/tampermonkey-cli/tree/master/projects/abp_parse
  35. // @source https://bitbucket.org/lemon399/tampermonkey-cli/src/master/projects/abp_parse/
  36. // @connect raw.fastgit.ixmu.net
  37. // @copyright GPL-3.0
  38. // @license GPL-3.0
  39. // ==/UserScript==
  40.  
  41. (function () {
  42. "use strict";
  43.  
  44. const $presets = {
  45. defaultRules: `
  46. ! 不支持的规则和开头为 ! 的行会忽略
  47. !
  48. ! 由于语法限制,此处规则中
  49. ! 一个反斜杠需要改成两个,像这样 \\
  50. `,
  51. userConfig: {
  52. css: `{
  53. display: none !important;
  54. width: 0 !important;
  55. height: 0 !important;
  56. }`,
  57. timeout: 10000,
  58. headTimeout: 2000,
  59. tryCount: 5,
  60. tryTimeout: 500,
  61. },
  62. onlineRules: [
  63. {
  64. 标识: `jiekouAD`,
  65. 地址: `https://raw.fastgit.ixmu.net/damengzhu/banad/main/jiekouAD.txt`,
  66. 在线更新: true,
  67. 筛选后存储: true,
  68. },
  69. {
  70. 标识: `CSSRule`,
  71. 地址: `https://raw.fastgit.ixmu.net/damengzhu/abpmerge/main/CSSRule.txt`,
  72. 在线更新: true,
  73. 筛选后存储: false,
  74. },
  75. ],
  76. };
  77.  
  78. /* ==UserConfig==
  79. 配置:
  80. css:
  81. title: 隐藏 CSS 规则
  82. description: 隐藏广告使用的 CSS 规则
  83. type: textarea
  84. rows: 7
  85. default: |-
  86. {
  87. display: none !important;
  88. width: 0 !important;
  89. height: 0 !important;
  90. }
  91. timeout:
  92. title: 规则下载超时
  93. description: 更新规则时,规则下载超时时间
  94. type: number
  95. default: 10000
  96. min: 0
  97. unit: 毫秒
  98. headTimeout:
  99. title: 获取规则信息超时
  100. description: 更新规则时,获取规则信息 (HEAD 请求) 超时时间
  101. type: number
  102. default: 2000
  103. min: 0
  104. unit: 毫秒
  105. tryCount:
  106. title: CSS 注入尝试次数
  107. description: 某些框架会重建页面,需要多次注入,只有检测到 CSS 不存在时才会尝试再次注入
  108. type: number
  109. default: 5
  110. min: 0
  111. unit: 次
  112. tryTimeout:
  113. title: CSS 注入尝试间隔
  114. description: 两次注入尝试的间隔时间
  115. type: number
  116. default: 500
  117. min: 100
  118. unit: 毫秒
  119. ==/UserConfig== */
  120.  
  121. /* eslint-disable no-redeclare, no-unused-vars, require-yield */
  122. /* global GM_info, GM, unsafeWindow, GM_registerMenuCommand, GM_unregisterMenuCommand, GM_getValue, GM_deleteValue, GM_setValue, GM_addStyle, GM_xmlhttpRequest, GM_getResourceText, GM_download, GM_listValues */
  123. let $listeners = [],
  124. $hasStorEvListener = false;
  125.  
  126. const $polyfills = {
  127. // 以下 polyfills 修改自 NullMonkey,使用 MPL-2.0 发布
  128. /* This Source Code Form is subject to the terms of the
  129. * Mozilla Public License, v. 2.0. If a copy of the MPL
  130. * was not distributed with this file, You can obtain
  131. * one at https://mozilla.org/MPL/2.0/. */
  132. GM_info:
  133. typeof GM_info == "object"
  134. ? GM_info
  135. : {
  136. script: {
  137. author: "Lemon399",
  138. copyright: "GPL-3.0",
  139. description: "Parse ABP Cosmetic rules to CSS and apply it.",
  140. downloadURL: null,
  141. excludes: [],
  142. excludeMatches: [],
  143. grant: [
  144. "unsafeWindow",
  145. "GM_registerMenuCommand",
  146. "GM.registerMenuCommand",
  147. "GM_unregisterMenuCommand",
  148. "GM.unregisterMenuCommand",
  149. "GM_getValue",
  150. "GM.getValue",
  151. "GM_deleteValue",
  152. "GM.deleteValue",
  153. "GM_setValue",
  154. "GM.setValue",
  155. "GM_addStyle",
  156. "GM.addStyle",
  157. "GM_xmlhttpRequest",
  158. "GM.xmlHttpRequest",
  159. "GM_getResourceText",
  160. "GM.getResourceText",
  161. "GM_download",
  162. "GM.download",
  163. "GM_listValues",
  164. "GM.listValues",
  165. ],
  166. homepage: null,
  167. icon: null,
  168. icon64: null,
  169. includes: [],
  170. matches: ["*://*/*"],
  171. name: "AdBlock Script for WebView",
  172. namespace: "https://lemon399-bitbucket-io.vercel.app/",
  173. noframes: false,
  174. "run-at": "document-start",
  175. resources: [
  176. {
  177. name: "jiekouAD",
  178. url: "https://raw.fastgit.ixmu.net/damengzhu/banad/main/jiekouAD.txt",
  179. },
  180. {
  181. name: "CSSRule",
  182. url: "https://raw.fastgit.ixmu.net/damengzhu/abpmerge/main/CSSRule.txt",
  183. },
  184. ],
  185. supportURL: null,
  186. unwrap: false,
  187. updateURL: null,
  188. version: "2.6.1",
  189. webRequest: null,
  190. },
  191. scriptWillUpdate: false,
  192. },
  193. parseValue: function parseValue(stored) {
  194. const value =
  195. typeof stored == "string" &&
  196. stored.startsWith("[") &&
  197. stored.endsWith("]")
  198. ? JSON.parse(stored)[0]
  199. : void 0;
  200. return value === "__$NaN"
  201. ? NaN
  202. : value === "__$UdF"
  203. ? undefined
  204. : value === "__$FnT"
  205. ? Infinity
  206. : value === "__$XnT"
  207. ? -Infinity
  208. : value;
  209. },
  210. unsafeWindow: typeof unsafeWindow == "object" ? unsafeWindow : window,
  211. GM_registerMenuCommand:
  212. typeof GM_registerMenuCommand == "function"
  213. ? GM_registerMenuCommand
  214. : void 0,
  215. GM_unregisterMenuCommand:
  216. typeof GM_unregisterMenuCommand == "function"
  217. ? GM_unregisterMenuCommand
  218. : void 0,
  219. GM_getValue:
  220. typeof GM_getValue == "function"
  221. ? GM_getValue
  222. : function DM_getValue(key, defaultValue) {
  223. const stor = window.localStorage.getItem(
  224. "$DMValue$AdBlock Script for WebView$" + key
  225. );
  226. return typeof stor == "string" &&
  227. stor.startsWith("[") &&
  228. stor.endsWith("]")
  229. ? $polyfills.parseValue(stor)
  230. : defaultValue;
  231. },
  232. GM_deleteValue:
  233. typeof GM_deleteValue == "function"
  234. ? GM_deleteValue
  235. : function DM_deleteValue(k) {
  236. window.localStorage.removeItem(
  237. "$DMValue$AdBlock Script for WebView$" + k
  238. );
  239. },
  240. GM_setValue:
  241. typeof GM_setValue == "function"
  242. ? GM_setValue
  243. : function DM_setValue(key, value) {
  244. const packed = JSON.stringify([
  245. typeof value == "function"
  246. ? value.toString()
  247. : typeof value == "number" && isNaN(value)
  248. ? "__$NaN"
  249. : typeof value == "number" && !isFinite(value)
  250. ? value > 0
  251. ? "__$FnT"
  252. : "__$XnT"
  253. : typeof value == "undefined"
  254. ? "__$UdF"
  255. : typeof value == "bigint"
  256. ? value.toString()
  257. : value,
  258. ]);
  259. $listeners.forEach((listenerArray, id) => {
  260. if (listenerArray[0] === key) {
  261. const oldValue = $polyfills.GM_getValue(key);
  262. listenerArray[1].call(
  263. {
  264. id,
  265. key,
  266. cb: listenerArray[1],
  267. },
  268. key,
  269. oldValue,
  270. value,
  271. false
  272. );
  273. }
  274. });
  275. window.localStorage.setItem(
  276. "$DMValue$AdBlock Script for WebView$" + key,
  277. packed
  278. );
  279. },
  280. GM_addStyle:
  281. typeof GM_addStyle == "function"
  282. ? GM_addStyle
  283. : function DM_addStyle(css) {
  284. const styleEl = document.createElement("style");
  285. styleEl.innerText = css;
  286. (
  287. document.head ||
  288. document.body ||
  289. document.documentElement
  290. ).appendChild(styleEl);
  291. return styleEl;
  292. },
  293. GM_xmlhttpRequest:
  294. typeof GM_xmlhttpRequest == "function" ? GM_xmlhttpRequest : void 0,
  295. GM_getResourceText:
  296. typeof GM_getResourceText == "function" ? GM_getResourceText : void 0,
  297. GM_download:
  298. // 以下浏览器的 GM_download 不支持 blob: 需要使用 Polyfill
  299. typeof GM_download == "function" &&
  300. // X 浏览器
  301. !GM_download.toString().includes("mbrowser.GM_download") &&
  302. // Via 浏览器
  303. !GM_download.toString().includes("via_gm.download") &&
  304. // MDM 浏览器
  305. !(
  306. typeof window.moe == "object" &&
  307. typeof window.moe.download == "function"
  308. ) &&
  309. // 海阔世界 / 嗅觉
  310. !GM_download.toString().includes("window.open") &&
  311. // Rains 浏览器
  312. !Array.isArray(GM_download.toString().match(/load\(\) {};$/))
  313. ? GM_download
  314. : function DM_download(objOrURL, filename) {
  315. var _a;
  316. const linkEl = document.createElement("a");
  317. if (typeof objOrURL == "object") {
  318. linkEl.href = objOrURL.url;
  319. linkEl.download = objOrURL.name;
  320. linkEl.onclick =
  321. (_a = objOrURL.onload) !== null && _a !== void 0 ? _a : null;
  322. } else {
  323. linkEl.href = objOrURL;
  324. linkEl.download =
  325. filename !== null && filename !== void 0 ? filename : "";
  326. }
  327. linkEl.style.cssText = "position:absolute;top:-100%";
  328. document.body.appendChild(linkEl);
  329. setTimeout(() => {
  330. linkEl.click();
  331. linkEl.remove();
  332. }, 0);
  333. return {
  334. abort: () => void 0,
  335. };
  336. },
  337. GM_listValues:
  338. typeof GM_listValues == "function"
  339. ? GM_listValues
  340. : function DM_listValues() {
  341. const keysArray = [];
  342. for (let i = 0; i < window.localStorage.length; i++) {
  343. const key = window.localStorage.key(i);
  344. if (
  345. key === null || key === void 0
  346. ? void 0
  347. : key.startsWith("$DMValue$AdBlock Script for WebView$")
  348. )
  349. keysArray.push(
  350. key.replace("$DMValue$AdBlock Script for WebView$", "")
  351. );
  352. }
  353. return keysArray;
  354. },
  355. GM:
  356. typeof GM == "object"
  357. ? GM
  358. : {
  359. getValue: function DM_getValue4(...args) {
  360. return Promise.resolve($polyfills.GM_getValue(...args));
  361. },
  362. deleteValue: function DM_deleteValue4(...args) {
  363. return Promise.resolve($polyfills.GM_deleteValue(...args));
  364. },
  365. setValue: function DM_setValue4(...args) {
  366. return Promise.resolve($polyfills.GM_setValue(...args));
  367. },
  368. addStyle: function DM_addStyle4(...args) {
  369. return Promise.resolve($polyfills.GM_addStyle(...args));
  370. },
  371. download: function DM_download4(...args) {
  372. return Promise.resolve($polyfills.GM_download(...args));
  373. },
  374. listValues: function DM_listValues4(...args) {
  375. return Promise.resolve($polyfills.GM_listValues(...args));
  376. },
  377. },
  378. // polyfills 结束
  379. };
  380.  
  381. (function (preset, tm) {
  382. "use strict";
  383.  
  384. /******************************************************************************
  385. Copyright (c) Microsoft Corporation.
  386. Permission to use, copy, modify, and/or distribute this software for any
  387. purpose with or without fee is hereby granted.
  388. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  389. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  390. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  391. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  392. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  393. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  394. PERFORMANCE OF THIS SOFTWARE.
  395. ***************************************************************************** */
  396. /* global Reflect, Promise, SuppressedError, Symbol */
  397. function __awaiter(thisArg, _arguments, P, generator) {
  398. function adopt(value) {
  399. return value instanceof P
  400. ? value
  401. : new P(function (resolve) {
  402. resolve(value);
  403. });
  404. }
  405. return new (P || (P = Promise))(function (resolve, reject) {
  406. function fulfilled(value) {
  407. try {
  408. step(generator.next(value));
  409. } catch (e) {
  410. reject(e);
  411. }
  412. }
  413. function rejected(value) {
  414. try {
  415. step(generator["throw"](value));
  416. } catch (e) {
  417. reject(e);
  418. }
  419. }
  420. function step(result) {
  421. result.done
  422. ? resolve(result.value)
  423. : adopt(result.value).then(fulfilled, rejected);
  424. }
  425. step((generator = generator.apply(thisArg, _arguments || [])).next());
  426. });
  427. }
  428. typeof SuppressedError === "function"
  429. ? SuppressedError
  430. : function (error, suppressed, message) {
  431. var e = new Error(message);
  432. return (
  433. (e.name = "SuppressedError"),
  434. (e.error = error),
  435. (e.suppressed = suppressed),
  436. e
  437. );
  438. };
  439. var _a, _b, _c;
  440. function makeRuleBox() {
  441. return {
  442. black: [],
  443. white: [],
  444. };
  445. }
  446. const data = {
  447. isFrame: tm.unsafeWindow.self !== tm.unsafeWindow.top,
  448. isClean: false,
  449. disabled: false,
  450. saved: false,
  451. update: true,
  452. updating: false,
  453. alertLog: false,
  454. receivedRules: "",
  455. customRules:
  456. preset.defaultRules +
  457. ("\n" +
  458. ((_c =
  459. (_b =
  460. (_a = tm.GM_info.script) === null || _a === void 0
  461. ? void 0
  462. : _a.options) === null || _b === void 0
  463. ? void 0
  464. : _b.comment) !== null && _c !== void 0
  465. ? _c
  466. : "")),
  467. allRules: "",
  468. genHideCss: "",
  469. genExtraCss: "",
  470. spcHideCss: "",
  471. spcExtraCss: "",
  472. selectors: makeRuleBox(),
  473. extSelectors: makeRuleBox(),
  474. styles: makeRuleBox(),
  475. extStyles: makeRuleBox(),
  476. bRules: [],
  477. appliedLevel: 0,
  478. appliedCount: 0,
  479. mutex: "__lemon__abp__parser__$__",
  480. preset: preset.userConfig.css,
  481. timeout: preset.userConfig.timeout,
  482. headTimeout: preset.userConfig.headTimeout,
  483. tryCount: preset.userConfig.tryCount,
  484. tryTimeout: preset.userConfig.tryTimeout,
  485. };
  486. const defaultValues = {
  487. get black() {
  488. return "";
  489. },
  490. get rules() {
  491. return {};
  492. },
  493. get css() {
  494. return {
  495. needUpdate: true,
  496. genHideCss: "",
  497. genExtraCss: "",
  498. spcHideCss: "",
  499. spcExtraCss: "",
  500. };
  501. },
  502. get time() {
  503. return "0/0/0 0:0:0";
  504. },
  505. get etags() {
  506. return {};
  507. },
  508. get brules() {
  509. return [];
  510. },
  511. get hash() {
  512. return "";
  513. },
  514. };
  515. const values = {
  516. black(value) {
  517. var _a;
  518. return __awaiter(this, void 0, void 0, function* () {
  519. if (typeof value == "undefined") {
  520. const arrStr = yield gmValue(
  521. "get",
  522. false,
  523. "ajs_disabled_domains",
  524. defaultValues.black
  525. );
  526. return typeof arrStr == "string" && arrStr.length > 0
  527. ? arrStr.split(",")
  528. : [];
  529. } else {
  530. return yield gmValue(
  531. "set",
  532. false,
  533. "ajs_disabled_domains",
  534. (_a =
  535. value === null || value === void 0
  536. ? void 0
  537. : value.join()) !== null && _a !== void 0
  538. ? _a
  539. : defaultValues.black
  540. );
  541. }
  542. });
  543. },
  544. rules(value) {
  545. return __awaiter(this, void 0, void 0, function* () {
  546. return typeof value == "undefined"
  547. ? yield gmValue(
  548. "get",
  549. true,
  550. "ajs_saved_abprules",
  551. defaultValues.rules
  552. )
  553. : yield gmValue(
  554. "set",
  555. true,
  556. "ajs_saved_abprules",
  557. value !== null && value !== void 0
  558. ? value
  559. : defaultValues.rules
  560. );
  561. });
  562. },
  563. css(value, host = location.hostname) {
  564. return __awaiter(this, void 0, void 0, function* () {
  565. return typeof value == "undefined"
  566. ? yield gmValue(
  567. "get",
  568. true,
  569. `ajs_saved_styles_${host}`,
  570. defaultValues.css
  571. )
  572. : yield gmValue(
  573. "set",
  574. true,
  575. `ajs_saved_styles_${host}`,
  576. value !== null && value !== void 0 ? value : defaultValues.css
  577. );
  578. });
  579. },
  580. time(value) {
  581. return __awaiter(this, void 0, void 0, function* () {
  582. return typeof value == "undefined"
  583. ? yield gmValue("get", false, "ajs_rules_ver", defaultValues.time)
  584. : yield gmValue(
  585. "set",
  586. false,
  587. "ajs_rules_ver",
  588. value !== null && value !== void 0
  589. ? value
  590. : defaultValues.time
  591. );
  592. });
  593. },
  594. etags(value) {
  595. return __awaiter(this, void 0, void 0, function* () {
  596. return typeof value == "undefined"
  597. ? yield gmValue(
  598. "get",
  599. true,
  600. "ajs_rules_etags",
  601. defaultValues.etags
  602. )
  603. : yield gmValue(
  604. "set",
  605. true,
  606. "ajs_rules_etags",
  607. value !== null && value !== void 0
  608. ? value
  609. : defaultValues.etags
  610. );
  611. });
  612. },
  613. brules(value) {
  614. return __awaiter(this, void 0, void 0, function* () {
  615. return typeof value == "undefined"
  616. ? yield gmValue(
  617. "get",
  618. true,
  619. "ajs_modifier_rules",
  620. defaultValues.brules
  621. )
  622. : yield gmValue(
  623. "set",
  624. true,
  625. "ajs_modifier_rules",
  626. value !== null && value !== void 0
  627. ? value
  628. : defaultValues.brules
  629. );
  630. });
  631. },
  632. hash(value) {
  633. return __awaiter(this, void 0, void 0, function* () {
  634. return typeof value == "undefined"
  635. ? yield gmValue(
  636. "get",
  637. false,
  638. "ajs_custom_hash",
  639. defaultValues.hash
  640. )
  641. : yield gmValue(
  642. "set",
  643. false,
  644. "ajs_custom_hash",
  645. value !== null && value !== void 0
  646. ? value
  647. : defaultValues.hash
  648. );
  649. });
  650. },
  651. },
  652. menus = {
  653. disable: {
  654. id: undefined,
  655. text() {
  656. return __awaiter(this, void 0, void 0, function* () {
  657. return `在此域名${data.disabled ? "启用" : "禁用"}拦截`;
  658. });
  659. },
  660. },
  661. update: {
  662. id: undefined,
  663. text() {
  664. return __awaiter(this, void 0, void 0, function* () {
  665. const time = yield values.time();
  666. return data.updating
  667. ? "正在更新..."
  668. : `点击更新 ${
  669. (time === null || time === void 0
  670. ? void 0
  671. : time.slice(0, 1)) === "0"
  672. ? "未知时间"
  673. : time
  674. }`;
  675. });
  676. },
  677. },
  678. count: {
  679. id: undefined,
  680. text() {
  681. var _a, _b;
  682. return __awaiter(this, void 0, void 0, function* () {
  683. let cssCount = "";
  684. if (!data.disabled) {
  685. if ((data.appliedLevel & 1) == 0)
  686. cssCount += data.genHideCss + data.genExtraCss;
  687. if ((data.appliedLevel & 2) == 0)
  688. cssCount += data.spcHideCss + data.spcExtraCss;
  689. }
  690. return data.isClean
  691. ? `已清空,点击刷新${data.disabled ? "网页" : "重新加载规则"}`
  692. : data.disabled
  693. ? "点击清空存储规则"
  694. : `点击清空 ${
  695. data.saved
  696. ? (_b =
  697. "CSS " +
  698. ((_a = cssCount.match(/{/g)) === null || _a === void 0
  699. ? void 0
  700. : _a.length)) !== null && _b !== void 0
  701. ? _b
  702. : "未知"
  703. : "规则 " +
  704. data.appliedCount +
  705. "/" +
  706. data.allRules.split("\n").length
  707. }`;
  708. });
  709. },
  710. },
  711. export: {
  712. id: undefined,
  713. text() {
  714. return __awaiter(this, void 0, void 0, function* () {
  715. return "下载统计报告";
  716. });
  717. },
  718. },
  719. };
  720. function gmChooser(gm1, gm4) {
  721. const gm1dm =
  722. gm1 === null || gm1 === void 0 ? void 0 : gm1.name.startsWith("DM_");
  723. const gm4dm =
  724. gm4 === null || gm4 === void 0 ? void 0 : gm4.name.startsWith("DM_");
  725. if (gm1dm !== gm4dm) {
  726. return gm1dm ? gm4 : gm1;
  727. } else {
  728. return gm1;
  729. }
  730. }
  731. function gmMenu(name, cb) {
  732. var _a;
  733. return __awaiter(this, void 0, void 0, function* () {
  734. const id =
  735. (_a = menus[name].id) !== null && _a !== void 0 ? _a : undefined;
  736. const gmr = gmChooser(
  737. tm.GM_registerMenuCommand,
  738. tm.GM === null || tm.GM === void 0
  739. ? void 0
  740. : tm.GM.registerMenuCommand
  741. );
  742. const gmu = gmChooser(
  743. tm.GM_unregisterMenuCommand,
  744. tm.GM === null || tm.GM === void 0
  745. ? void 0
  746. : tm.GM.unregisterMenuCommand
  747. );
  748. if (typeof gmr != "function" || data.isFrame) return;
  749. if (typeof id != "undefined" && typeof gmu == "function") {
  750. menus[name].id = undefined;
  751. yield gmu(id);
  752. }
  753. if (typeof cb == "function") {
  754. menus[name].id = yield gmr(yield menus[name].text(), cb);
  755. }
  756. });
  757. }
  758. function gmValue(action, json, key, value) {
  759. var _a, _b, _c, _d;
  760. return __awaiter(this, void 0, void 0, function* () {
  761. switch (action) {
  762. case "get":
  763. try {
  764. let v =
  765. (_a = gmChooser(
  766. tm.GM_getValue,
  767. tm.GM === null || tm.GM === void 0 ? void 0 : tm.GM.getValue
  768. )) === null || _a === void 0
  769. ? void 0
  770. : _a(key, json ? JSON.stringify(value) : value);
  771. v = v instanceof Promise ? yield v : v;
  772. return Promise.resolve(
  773. json && typeof v == "string" ? JSON.parse(v) : v
  774. );
  775. } catch (error) {
  776. return Promise.resolve(value);
  777. }
  778. case "set":
  779. try {
  780. return value === null || value === undefined
  781. ? Promise.resolve(
  782. (_b = gmChooser(
  783. tm.GM_deleteValue,
  784. tm.GM === null || tm.GM === void 0
  785. ? void 0
  786. : tm.GM.deleteValue
  787. )) === null || _b === void 0
  788. ? void 0
  789. : _b(key)
  790. )
  791. : Promise.resolve(
  792. (_c = gmChooser(
  793. tm.GM_setValue,
  794. tm.GM === null || tm.GM === void 0
  795. ? void 0
  796. : tm.GM.setValue
  797. )) === null || _c === void 0
  798. ? void 0
  799. : _c(key, json ? JSON.stringify(value) : value)
  800. );
  801. } catch (error) {
  802. Promise.reject(
  803. (_d = gmChooser(
  804. tm.GM_deleteValue,
  805. tm.GM === null || tm.GM === void 0
  806. ? void 0
  807. : tm.GM.deleteValue
  808. )) === null || _d === void 0
  809. ? void 0
  810. : _d(key)
  811. );
  812. }
  813. break;
  814. }
  815. });
  816. }
  817. function getUserConfig(prop) {
  818. var _a;
  819. return __awaiter(this, void 0, void 0, function* () {
  820. {
  821. return (_a = yield gmValue("get", false, `配置.${prop}`)) !== null &&
  822. _a !== void 0
  823. ? _a
  824. : preset.userConfig[prop];
  825. }
  826. });
  827. }
  828. function addStyle(css, pass = 0) {
  829. var _a;
  830. return __awaiter(this, void 0, void 0, function* () {
  831. if (pass >= data.tryCount) return;
  832. const el = yield (_a = gmChooser(
  833. tm.GM_addStyle,
  834. tm.GM === null || tm.GM === void 0 ? void 0 : tm.GM.addStyle
  835. )) === null || _a === void 0
  836. ? void 0
  837. : _a(css);
  838. if (!el || !document.documentElement.contains(el)) {
  839. setTimeout(() => {
  840. addStyle(css, pass + 1);
  841. }, data.tryTimeout);
  842. }
  843. });
  844. }
  845. function promiseXhr(details) {
  846. return __awaiter(this, void 0, void 0, function* () {
  847. let loaded = false;
  848. const gmXhr = gmChooser(
  849. tm.GM_xmlhttpRequest,
  850. tm.GM === null || tm.GM === void 0 ? void 0 : tm.GM.xmlHttpRequest
  851. );
  852. if (typeof gmXhr != "function")
  853. return Promise.reject({
  854. error: "noxhr",
  855. });
  856. return yield new Promise((resolve, reject) => {
  857. gmXhr(
  858. Object.assign(
  859. {
  860. onload(e) {
  861. loaded = true;
  862. resolve(e);
  863. },
  864. onabort(e) {
  865. loaded = true;
  866. reject({
  867. error: "abort",
  868. resp: e,
  869. });
  870. },
  871. onerror(e) {
  872. loaded = true;
  873. reject({
  874. error: "error",
  875. resp: e,
  876. });
  877. },
  878. ontimeout(e) {
  879. loaded = true;
  880. reject({
  881. error: "timeout",
  882. resp: e,
  883. });
  884. },
  885. onreadystatechange(e) {
  886. // Via 浏览器超时中断,不给成功状态...
  887. if (
  888. (e === null || e === void 0 ? void 0 : e.readyState) === 3
  889. ) {
  890. setTimeout(
  891. () => {
  892. if (!loaded)
  893. reject({
  894. error: "Via timeout",
  895. resp: e,
  896. });
  897. },
  898. details.method === "HEAD"
  899. ? data.headTimeout
  900. : data.timeout
  901. );
  902. }
  903. },
  904. timeout:
  905. details.method === "HEAD" ? data.headTimeout : data.timeout,
  906. },
  907. details
  908. )
  909. );
  910. });
  911. });
  912. }
  913. function getRuleFromResource(key) {
  914. var _a;
  915. return __awaiter(this, void 0, void 0, function* () {
  916. try {
  917. return yield (_a = gmChooser(
  918. tm.GM_getResourceText,
  919. tm.GM === null || tm.GM === void 0 ? void 0 : tm.GM.getResourceText
  920. )) === null || _a === void 0
  921. ? void 0
  922. : _a(key);
  923. } catch (error) {
  924. return null;
  925. }
  926. });
  927. }
  928. function runOnce(key, func) {
  929. if (key in tm.unsafeWindow) return Promise.reject();
  930. tm.unsafeWindow[key] = true;
  931. return func();
  932. }
  933. const downUrl = tm.GM_download;
  934. function getSavedHosts(host) {
  935. var _a, _b;
  936. return __awaiter(this, void 0, void 0, function* () {
  937. const keys =
  938. (_b = yield (_a = gmChooser(
  939. tm.GM_listValues,
  940. tm.GM === null || tm.GM === void 0 ? void 0 : tm.GM.listValues
  941. )) === null || _a === void 0
  942. ? void 0
  943. : _a()) !== null && _b !== void 0
  944. ? _b
  945. : [];
  946. const domains = (
  947. Array.isArray(keys)
  948. ? keys
  949. : // Rains
  950. Object.keys(keys)
  951. )
  952. .filter((key) => key.startsWith("ajs_saved_styles_"))
  953. .map((key) => key.replace("ajs_saved_styles_", ""));
  954. return host ? domains.includes(host) : domains;
  955. });
  956. }
  957. const CRRE =
  958. /^(\[\$domain=)?(~?[\w-]+(?:\.[\w-]+)*(?:\.[\w-]+|\.\*)(?:(?:,|\|)~?[\w-]+(?:\.[\w-]+)*(?:\.[\w-]+|\.\*))*)?(?:])?(#@?\$?\??#)([^\s^+].*)/,
  959. BRRE =
  960. /^(?:@@?)(?:\/(.*[^\\])\/|(\|\|?)?(https?:\/\/)?([^\s"<>`]+?[|^]?))?\$((?:(?:~?[\w-]+(?:=[^$]+)?|_+)(?:[^\\],|$))+)/,
  961. CCRE =
  962. /^\/\*\s(\d)(\|)?(.+?)\s\*\/\s((.+?)\s*(?:\{\s*[a-zA-Z-]+\s*:\s*.+\}|,))\s*$/,
  963. BROpts = [
  964. "elemhide",
  965. "ehide",
  966. "specifichide",
  967. "shide",
  968. "generichide",
  969. "ghide",
  970. ],
  971. CRFlags = ["##", "#@#", "#?#", "#@?#", "#$#", "#@$#", "#$?#", "#@$?#"],
  972. styleBoxes = ["genHideCss", "genExtraCss", "spcHideCss", "spcExtraCss"],
  973. dataBoxes = ["selectors", "extSelectors", "styles", "extStyles"];
  974. function bRuleSpliter(rule) {
  975. const group = rule.match(BRRE);
  976. if (!group) return null;
  977. const [, regex, pipe, proto, body, option] = group,
  978. options = option.split(","),
  979. sepChar = "[^\\w\\.%-]",
  980. anyChar = '(?:[^\\s"<>`]*)',
  981. eh = hasSome(options, ["elemhide", "ehide"]),
  982. sh = hasSome(options, ["specifichide", "shide"]),
  983. gh = hasSome(options, ["generichide", "ghide"]);
  984. let domains = [];
  985. options.forEach((opt) => {
  986. if (opt.startsWith("domain=")) {
  987. domains = opt.split("=")[1].split("|");
  988. }
  989. });
  990. let match = "";
  991. if (regex) {
  992. match = regex;
  993. } else if (body) {
  994. match += pipe
  995. ? proto
  996. ? `^${proto}`
  997. : `^https?://(?:[\\w-]+\\.)*?`
  998. : `^${anyChar}`;
  999. match += body
  1000. .replace(/[-\\$+.()[\]{}]/g, "\\$&")
  1001. .replace(/\^/g, "$^")
  1002. .replace(/\|$/, "$")
  1003. .replace(/\|/g, "\\|")
  1004. .replace(/\*$/g, "")
  1005. .replace(/\*/g, anyChar)
  1006. .replace(/\$\^$/, `(?:${sepChar}.*|$)`)
  1007. .replace(/\$\^/g, sepChar);
  1008. } else if (domains.length > 0) {
  1009. match = domains;
  1010. }
  1011. return {
  1012. rule,
  1013. match,
  1014. level: eh || (gh && sh) ? 3 : sh ? 2 : gh ? 1 : 0,
  1015. };
  1016. }
  1017. function isBasicRule(rule) {
  1018. return BRRE.test(rule) && hasSome(rule, BROpts);
  1019. }
  1020. function bRuleParser(rule, url = location.href) {
  1021. return rule
  1022. ? (Array.isArray(rule.match) && domainChecker(rule.match)[0]) ||
  1023. (!Array.isArray(rule.match) && new RegExp(rule.match).test(url))
  1024. ? rule.level
  1025. : 0
  1026. : 0;
  1027. }
  1028. function getEtag(header) {
  1029. var _a;
  1030. let result = null;
  1031. if (!header) return null;
  1032. [
  1033. /[e|E][t|T]ag:\s(?:W\/)?"(\w+)"/,
  1034. // WebMonkey 系
  1035. /[e|E][t|T]ag:\s\[(?:W\/)?"(\w+)"\]/,
  1036. // 书签地球
  1037. /[e|E][t|T]ag=(?:W\/)?"(\w+)"/,
  1038. // 海阔世界
  1039. /^(?:W\/)?"(\w+)"/,
  1040. ].forEach((re) => {
  1041. result !== null && result !== void 0
  1042. ? result
  1043. : (result = header.match(re));
  1044. });
  1045. return (_a =
  1046. result === null || result === void 0 ? void 0 : result[1]) !== null &&
  1047. _a !== void 0
  1048. ? _a
  1049. : null;
  1050. }
  1051. function domainChecker(domains) {
  1052. const results = [],
  1053. invResults = [],
  1054. currDomain = location.hostname,
  1055. urlSuffix = /\.+?[\w-]+$/.exec(currDomain);
  1056. let totalResult = [0, false],
  1057. black = false,
  1058. white = false,
  1059. match = false;
  1060. domains.forEach((domain) => {
  1061. const invert = domain[0] === "~";
  1062. if (invert) domain = domain.slice(1);
  1063. if (domain.endsWith(".*") && Array.isArray(urlSuffix)) {
  1064. domain = domain.replace(".*", urlSuffix[0]);
  1065. }
  1066. const result = currDomain.endsWith(domain);
  1067. if (invert) {
  1068. if (result) white = true;
  1069. invResults.push([domain.length, !result]);
  1070. } else {
  1071. if (result) black = true;
  1072. results.push([domain.length, result]);
  1073. }
  1074. });
  1075. if (results.length > 0 && !black) {
  1076. match = false;
  1077. } else if (invResults.length > 0 && !white) {
  1078. match = true;
  1079. } else {
  1080. results.forEach((r) => {
  1081. if (r[0] >= totalResult[0] && r[1]) {
  1082. totalResult = r;
  1083. }
  1084. });
  1085. invResults.forEach((r) => {
  1086. if (r[0] >= totalResult[0] && !r[1]) {
  1087. totalResult = r;
  1088. }
  1089. });
  1090. match = totalResult[1];
  1091. }
  1092. return [match, results.length === 0];
  1093. }
  1094. function hasSome(str, arr) {
  1095. return arr.some((word) => str.includes(word));
  1096. }
  1097. function ruleSpliter(rule) {
  1098. const group = rule.match(CRRE);
  1099. if (group) {
  1100. const [, isDomain, place = "*", flag, sel] = group,
  1101. type = CRFlags.indexOf(flag),
  1102. matchResult =
  1103. place === "*"
  1104. ? [true, true]
  1105. : domainChecker(place.split(isDomain ? "|" : ","));
  1106. if (sel && matchResult[0]) {
  1107. return {
  1108. black: type % 2 ? "white" : "black",
  1109. type: Math.floor(type / 2),
  1110. place: (isDomain ? "|" : "") + place,
  1111. generic: matchResult[1],
  1112. sel,
  1113. };
  1114. }
  1115. }
  1116. }
  1117. function ruleLoader(rule) {
  1118. if (
  1119. hasSome(rule, [
  1120. ":matches-path(",
  1121. ":min-text-length(",
  1122. ":watch-attr(",
  1123. ":-abp-properties(",
  1124. ":matches-property(",
  1125. ])
  1126. )
  1127. return;
  1128. // 去掉开头末尾空格
  1129. rule = rule.trim();
  1130. // 如果 #$# 不包含 {} 就排除
  1131. // 可以尽量排除 Snippet Filters
  1132. if (
  1133. /(?:\w|\*|]|^)#\$#/.test(rule) &&
  1134. !/{\s*[a-zA-Z-]+\s*:\s*.+}\s*$/.test(rule)
  1135. )
  1136. return;
  1137. // ## -> #?#
  1138. if (
  1139. /(?:\w|\*|]|^)#@?\$?#/.test(rule) &&
  1140. hasSome(rule, [
  1141. ":has(",
  1142. ":-abp-has(",
  1143. "[-ext-has=",
  1144. ":has-text(",
  1145. ":contains(",
  1146. ":-abp-contains(",
  1147. "[-ext-contains=",
  1148. ":matches-css(",
  1149. "[-ext-matches-css=",
  1150. ":matches-css-before(",
  1151. "[-ext-matches-css-before=",
  1152. ":matches-css-after(",
  1153. "[-ext-matches-css-after=",
  1154. ":matches-attr(",
  1155. ":nth-ancestor(",
  1156. ":upward(",
  1157. ":xpath(",
  1158. ":remove()",
  1159. ":not(",
  1160. ])
  1161. ) {
  1162. rule = rule.replace(/(\w|\*|]|^)#(@?\$?)#/, "$1#$2?#");
  1163. }
  1164. // :style(...) 转换
  1165. // example.com#?##id:style(color: red)
  1166. // example.com#$?##id { color: red }
  1167. if (rule.includes(":style(")) {
  1168. rule = rule
  1169. .replace(/(\w|\*|]|^)#(@?)(\??)#/, "$1#$2$$$3#")
  1170. .replace(/:style\(\s*/, " { ")
  1171. .replace(/\s*\)$/, " }");
  1172. }
  1173. return ruleSpliter(rule);
  1174. }
  1175. function ruleToCss(rule, preset, full) {
  1176. var _a, _b;
  1177. const isStyle = /}\s*$/.test(rule.sel);
  1178. return [
  1179. `/* ${rule.type}${rule.place} */ ${
  1180. rule.sel +
  1181. (!isStyle
  1182. ? full
  1183. ? " " + preset.replace(/\s{2,}/g, " ").replace(/\n/g, "")
  1184. : ","
  1185. : "")
  1186. } \n`,
  1187. isStyle
  1188. ? (_b =
  1189. (_a = rule.sel.match(/^(.+?)\s*{\s*[a-zA-Z-]+\s*:\s*.+}\s*$/)) ===
  1190. null || _a === void 0
  1191. ? void 0
  1192. : _a[1]) !== null && _b !== void 0
  1193. ? _b
  1194. : rule.sel
  1195. : rule.sel,
  1196. isStyle,
  1197. ];
  1198. }
  1199. function cssToAbp(css) {
  1200. var _a;
  1201. const flags = ["##", "#?#", "#$#", "#$?#"];
  1202. const [, typeStr, isDomain, place, style, sel] =
  1203. (_a = css.match(CCRE)) !== null && _a !== void 0 ? _a : [];
  1204. if (typeStr === undefined) return null;
  1205. const type = parseInt(typeStr);
  1206. return [
  1207. `${place === "*" ? "" : isDomain ? `[$domain=${place}]` : place}${
  1208. flags[type]
  1209. }${type >= 2 ? style : sel}`,
  1210. type,
  1211. sel,
  1212. ];
  1213. }
  1214. // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#bypassing_the_cache
  1215. function addTimeParam(url) {
  1216. return url + (url.includes("?") ? "&" : "?") + new Date().getTime();
  1217. }
  1218. function saveCss() {
  1219. return __awaiter(this, void 0, void 0, function* () {
  1220. const styles = {
  1221. needUpdate: false,
  1222. genHideCss: data.genHideCss,
  1223. genExtraCss: data.genExtraCss,
  1224. spcHideCss: data.spcHideCss,
  1225. spcExtraCss: data.spcExtraCss,
  1226. };
  1227. yield values.css(styles);
  1228. });
  1229. }
  1230. function readCss() {
  1231. var _a;
  1232. return __awaiter(this, void 0, void 0, function* () {
  1233. const styles =
  1234. (_a = yield values.css()) !== null && _a !== void 0
  1235. ? _a
  1236. : defaultValues.css;
  1237. if (!hasSome(Object.keys(styles), styleBoxes)) {
  1238. yield values.css(defaultValues.css);
  1239. return;
  1240. }
  1241. styleBoxes.forEach((sname) => {
  1242. var _a;
  1243. if (styles[sname].length > 0) {
  1244. data.saved = true;
  1245. data.update =
  1246. (_a = styles.needUpdate) !== null && _a !== void 0 ? _a : true;
  1247. data[sname] = styles[sname];
  1248. }
  1249. });
  1250. });
  1251. }
  1252.  
  1253. /**
  1254. * @adguard/extended-css - v2.0.52 - Fri Apr 14 2023
  1255. * https://github.com/AdguardTeam/ExtendedCss#homepage
  1256. * Copyright (c) 2023 AdGuard. Licensed GPL-3.0
  1257. */
  1258. function _defineProperty(obj, key, value) {
  1259. if (key in obj) {
  1260. Object.defineProperty(obj, key, {
  1261. value: value,
  1262. enumerable: true,
  1263. configurable: true,
  1264. writable: true,
  1265. });
  1266. } else {
  1267. obj[key] = value;
  1268. }
  1269. return obj;
  1270. }
  1271. /**
  1272. * Possible ast node types.
  1273. *
  1274. * IMPORTANT: it is used as 'const' instead of 'enum' to avoid side effects
  1275. * during ExtendedCss import into other libraries.
  1276. */
  1277. const NODE = {
  1278. SELECTOR_LIST: "SelectorList",
  1279. SELECTOR: "Selector",
  1280. REGULAR_SELECTOR: "RegularSelector",
  1281. EXTENDED_SELECTOR: "ExtendedSelector",
  1282. ABSOLUTE_PSEUDO_CLASS: "AbsolutePseudoClass",
  1283. RELATIVE_PSEUDO_CLASS: "RelativePseudoClass",
  1284. };
  1285. /**
  1286. * Class needed for creating ast nodes while selector parsing.
  1287. * Used for SelectorList, Selector, ExtendedSelector.
  1288. */
  1289. class AnySelectorNode {
  1290. /**
  1291. * Creates new ast node.
  1292. *
  1293. * @param type Ast node type.
  1294. */
  1295. constructor(type) {
  1296. _defineProperty(this, "children", []);
  1297. this.type = type;
  1298. }
  1299. /**
  1300. * Adds child node to children array.
  1301. *
  1302. * @param child Ast node.
  1303. */
  1304. addChild(child) {
  1305. this.children.push(child);
  1306. }
  1307. }
  1308. /**
  1309. * Class needed for creating RegularSelector ast node while selector parsing.
  1310. */
  1311. class RegularSelectorNode extends AnySelectorNode {
  1312. /**
  1313. * Creates RegularSelector ast node.
  1314. *
  1315. * @param value Value of RegularSelector node.
  1316. */
  1317. constructor(value) {
  1318. super(NODE.REGULAR_SELECTOR);
  1319. this.value = value;
  1320. }
  1321. }
  1322. /**
  1323. * Class needed for creating RelativePseudoClass ast node while selector parsing.
  1324. */
  1325. class RelativePseudoClassNode extends AnySelectorNode {
  1326. /**
  1327. * Creates RegularSelector ast node.
  1328. *
  1329. * @param name Name of RelativePseudoClass node.
  1330. */
  1331. constructor(name) {
  1332. super(NODE.RELATIVE_PSEUDO_CLASS);
  1333. this.name = name;
  1334. }
  1335. }
  1336. /**
  1337. * Class needed for creating AbsolutePseudoClass ast node while selector parsing.
  1338. */
  1339. class AbsolutePseudoClassNode extends AnySelectorNode {
  1340. /**
  1341. * Creates AbsolutePseudoClass ast node.
  1342. *
  1343. * @param name Name of AbsolutePseudoClass node.
  1344. */
  1345. constructor(name) {
  1346. super(NODE.ABSOLUTE_PSEUDO_CLASS);
  1347. _defineProperty(this, "value", "");
  1348. this.name = name;
  1349. }
  1350. }
  1351. /* eslint-disable jsdoc/require-description-complete-sentence */
  1352. /**
  1353. * Root node.
  1354. *
  1355. * SelectorList
  1356. * : Selector
  1357. * ...
  1358. * ;
  1359. */
  1360. /**
  1361. * Selector node.
  1362. *
  1363. * Selector
  1364. * : RegularSelector
  1365. * | ExtendedSelector
  1366. * ...
  1367. * ;
  1368. */
  1369. /**
  1370. * Regular selector node.
  1371. * It can be selected by querySelectorAll().
  1372. *
  1373. * RegularSelector
  1374. * : type
  1375. * : value
  1376. * ;
  1377. */
  1378. /**
  1379. * Extended selector node.
  1380. *
  1381. * ExtendedSelector
  1382. * : AbsolutePseudoClass
  1383. * | RelativePseudoClass
  1384. * ;
  1385. */
  1386. /**
  1387. * Absolute extended pseudo-class node,
  1388. * i.e. none-selector args.
  1389. *
  1390. * AbsolutePseudoClass
  1391. * : type
  1392. * : name
  1393. * : value
  1394. * ;
  1395. */
  1396. /**
  1397. * Relative extended pseudo-class node
  1398. * i.e. selector as arg.
  1399. *
  1400. * RelativePseudoClass
  1401. * : type
  1402. * : name
  1403. * : SelectorList
  1404. * ;
  1405. */
  1406. //
  1407. // ast example
  1408. //
  1409. // div.banner > div:has(span, p), a img.ad
  1410. //
  1411. // SelectorList - div.banner > div:has(span, p), a img.ad
  1412. // Selector - div.banner > div:has(span, p)
  1413. // RegularSelector - div.banner > div
  1414. // ExtendedSelector - :has(span, p)
  1415. // PseudoClassSelector - :has
  1416. // SelectorList - span, p
  1417. // Selector - span
  1418. // RegularSelector - span
  1419. // Selector - p
  1420. // RegularSelector - p
  1421. // Selector - a img.ad
  1422. // RegularSelector - a img.ad
  1423. //
  1424. const LEFT_SQUARE_BRACKET = "[";
  1425. const RIGHT_SQUARE_BRACKET = "]";
  1426. const LEFT_PARENTHESIS = "(";
  1427. const RIGHT_PARENTHESIS = ")";
  1428. const LEFT_CURLY_BRACKET = "{";
  1429. const RIGHT_CURLY_BRACKET = "}";
  1430. const BRACKET = {
  1431. SQUARE: {
  1432. LEFT: LEFT_SQUARE_BRACKET,
  1433. RIGHT: RIGHT_SQUARE_BRACKET,
  1434. },
  1435. PARENTHESES: {
  1436. LEFT: LEFT_PARENTHESIS,
  1437. RIGHT: RIGHT_PARENTHESIS,
  1438. },
  1439. CURLY: {
  1440. LEFT: LEFT_CURLY_BRACKET,
  1441. RIGHT: RIGHT_CURLY_BRACKET,
  1442. },
  1443. };
  1444. const SLASH = "/";
  1445. const BACKSLASH = "\\";
  1446. const SPACE = " ";
  1447. const COMMA = ",";
  1448. const DOT = ".";
  1449. const SEMICOLON = ";";
  1450. const COLON = ":";
  1451. const SINGLE_QUOTE = "'";
  1452. const DOUBLE_QUOTE = '"'; // do not consider hyphen `-` as separated mark
  1453. // to avoid pseudo-class names splitting
  1454. // e.g. 'matches-css' or 'if-not'
  1455. const CARET = "^";
  1456. const DOLLAR_SIGN = "$";
  1457. const EQUAL_SIGN = "=";
  1458. const TAB = "\t";
  1459. const CARRIAGE_RETURN = "\r";
  1460. const LINE_FEED = "\n";
  1461. const FORM_FEED = "\f";
  1462. const WHITE_SPACE_CHARACTERS = [
  1463. SPACE,
  1464. TAB,
  1465. CARRIAGE_RETURN,
  1466. LINE_FEED,
  1467. FORM_FEED,
  1468. ]; // for universal selector and attributes
  1469. const ASTERISK = "*";
  1470. const ID_MARKER = "#";
  1471. const CLASS_MARKER = DOT;
  1472. const DESCENDANT_COMBINATOR = SPACE;
  1473. const CHILD_COMBINATOR = ">";
  1474. const NEXT_SIBLING_COMBINATOR = "+";
  1475. const SUBSEQUENT_SIBLING_COMBINATOR = "~";
  1476. const COMBINATORS = [
  1477. DESCENDANT_COMBINATOR,
  1478. CHILD_COMBINATOR,
  1479. NEXT_SIBLING_COMBINATOR,
  1480. SUBSEQUENT_SIBLING_COMBINATOR,
  1481. ];
  1482. const SUPPORTED_SELECTOR_MARKS = [
  1483. LEFT_SQUARE_BRACKET,
  1484. RIGHT_SQUARE_BRACKET,
  1485. LEFT_PARENTHESIS,
  1486. RIGHT_PARENTHESIS,
  1487. LEFT_CURLY_BRACKET,
  1488. RIGHT_CURLY_BRACKET,
  1489. SLASH,
  1490. BACKSLASH,
  1491. SEMICOLON,
  1492. COLON,
  1493. COMMA,
  1494. SINGLE_QUOTE,
  1495. DOUBLE_QUOTE,
  1496. CARET,
  1497. DOLLAR_SIGN,
  1498. ASTERISK,
  1499. ID_MARKER,
  1500. CLASS_MARKER,
  1501. DESCENDANT_COMBINATOR,
  1502. CHILD_COMBINATOR,
  1503. NEXT_SIBLING_COMBINATOR,
  1504. SUBSEQUENT_SIBLING_COMBINATOR,
  1505. TAB,
  1506. CARRIAGE_RETURN,
  1507. LINE_FEED,
  1508. FORM_FEED,
  1509. ];
  1510. const SUPPORTED_STYLE_DECLARATION_MARKS = [
  1511. // divider between property and value in declaration
  1512. COLON,
  1513. // divider between declarations
  1514. SEMICOLON,
  1515. // sometimes is needed for value wrapping
  1516. // e.g. 'content: "-"'
  1517. SINGLE_QUOTE,
  1518. DOUBLE_QUOTE,
  1519. // needed for quote escaping inside the same-type quotes
  1520. BACKSLASH,
  1521. // whitespaces
  1522. SPACE,
  1523. TAB,
  1524. CARRIAGE_RETURN,
  1525. LINE_FEED,
  1526. FORM_FEED,
  1527. ]; // absolute:
  1528. const CONTAINS_PSEUDO = "contains";
  1529. const HAS_TEXT_PSEUDO = "has-text";
  1530. const ABP_CONTAINS_PSEUDO = "-abp-contains";
  1531. const MATCHES_CSS_PSEUDO = "matches-css";
  1532. const MATCHES_CSS_BEFORE_PSEUDO = "matches-css-before";
  1533. const MATCHES_CSS_AFTER_PSEUDO = "matches-css-after";
  1534. const MATCHES_ATTR_PSEUDO_CLASS_MARKER = "matches-attr";
  1535. const MATCHES_PROPERTY_PSEUDO_CLASS_MARKER = "matches-property";
  1536. const XPATH_PSEUDO_CLASS_MARKER = "xpath";
  1537. const NTH_ANCESTOR_PSEUDO_CLASS_MARKER = "nth-ancestor";
  1538. const CONTAINS_PSEUDO_NAMES = [
  1539. CONTAINS_PSEUDO,
  1540. HAS_TEXT_PSEUDO,
  1541. ABP_CONTAINS_PSEUDO,
  1542. ];
  1543. /**
  1544. * Pseudo-class :upward() can get number or selector arg
  1545. * and if the arg is selector it should be standard, not extended
  1546. * so :upward pseudo-class is always absolute.
  1547. */
  1548. const UPWARD_PSEUDO_CLASS_MARKER = "upward";
  1549. /**
  1550. * Pseudo-class `:remove()` and pseudo-property `remove`
  1551. * are used for element actions, not for element selecting.
  1552. *
  1553. * Selector text should not contain the pseudo-class
  1554. * so selector parser should consider it as invalid
  1555. * and both are handled by stylesheet parser.
  1556. */
  1557. const REMOVE_PSEUDO_MARKER = "remove"; // relative:
  1558. const HAS_PSEUDO_CLASS_MARKER = "has";
  1559. const ABP_HAS_PSEUDO_CLASS_MARKER = "-abp-has";
  1560. const HAS_PSEUDO_CLASS_MARKERS = [
  1561. HAS_PSEUDO_CLASS_MARKER,
  1562. ABP_HAS_PSEUDO_CLASS_MARKER,
  1563. ];
  1564. const IS_PSEUDO_CLASS_MARKER = "is";
  1565. const NOT_PSEUDO_CLASS_MARKER = "not";
  1566. const ABSOLUTE_PSEUDO_CLASSES = [
  1567. CONTAINS_PSEUDO,
  1568. HAS_TEXT_PSEUDO,
  1569. ABP_CONTAINS_PSEUDO,
  1570. MATCHES_CSS_PSEUDO,
  1571. MATCHES_CSS_BEFORE_PSEUDO,
  1572. MATCHES_CSS_AFTER_PSEUDO,
  1573. MATCHES_ATTR_PSEUDO_CLASS_MARKER,
  1574. MATCHES_PROPERTY_PSEUDO_CLASS_MARKER,
  1575. XPATH_PSEUDO_CLASS_MARKER,
  1576. NTH_ANCESTOR_PSEUDO_CLASS_MARKER,
  1577. UPWARD_PSEUDO_CLASS_MARKER,
  1578. ];
  1579. const RELATIVE_PSEUDO_CLASSES = [
  1580. ...HAS_PSEUDO_CLASS_MARKERS,
  1581. IS_PSEUDO_CLASS_MARKER,
  1582. NOT_PSEUDO_CLASS_MARKER,
  1583. ];
  1584. const SUPPORTED_PSEUDO_CLASSES = [
  1585. ...ABSOLUTE_PSEUDO_CLASSES,
  1586. ...RELATIVE_PSEUDO_CLASSES,
  1587. ]; // these pseudo-classes should be part of RegularSelector value
  1588. // if its arg does not contain extended selectors.
  1589. // the ast will be checked after the selector is completely parsed
  1590. const OPTIMIZATION_PSEUDO_CLASSES = [
  1591. NOT_PSEUDO_CLASS_MARKER,
  1592. IS_PSEUDO_CLASS_MARKER,
  1593. ];
  1594. /**
  1595. * ':scope' is used for extended pseudo-class :has(), if-not(), :is() and :not().
  1596. */
  1597. const SCOPE_CSS_PSEUDO_CLASS = ":scope";
  1598. /**
  1599. * ':after' and ':before' are needed for :matches-css() pseudo-class
  1600. * all other are needed for :has() limitation after regular pseudo-elements.
  1601. *
  1602. * @see {@link https://bugs.chromium.org/p/chromium/issues/detail?id=669058#c54} [case 3]
  1603. */
  1604. const REGULAR_PSEUDO_ELEMENTS = {
  1605. AFTER: "after",
  1606. BACKDROP: "backdrop",
  1607. BEFORE: "before",
  1608. CUE: "cue",
  1609. CUE_REGION: "cue-region",
  1610. FIRST_LETTER: "first-letter",
  1611. FIRST_LINE: "first-line",
  1612. FILE_SELECTION_BUTTON: "file-selector-button",
  1613. GRAMMAR_ERROR: "grammar-error",
  1614. MARKER: "marker",
  1615. PART: "part",
  1616. PLACEHOLDER: "placeholder",
  1617. SELECTION: "selection",
  1618. SLOTTED: "slotted",
  1619. SPELLING_ERROR: "spelling-error",
  1620. TARGET_TEXT: "target-text",
  1621. }; // ExtendedCss does not support at-rules
  1622. // https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule
  1623. const AT_RULE_MARKER = "@";
  1624. const CONTENT_CSS_PROPERTY = "content";
  1625. const PSEUDO_PROPERTY_POSITIVE_VALUE = "true";
  1626. const DEBUG_PSEUDO_PROPERTY_GLOBAL_VALUE = "global";
  1627. const NO_SELECTOR_ERROR_PREFIX = "Selector should be defined";
  1628. const STYLE_ERROR_PREFIX = {
  1629. NO_STYLE: "No style declaration found",
  1630. NO_SELECTOR: `${NO_SELECTOR_ERROR_PREFIX} before style declaration in stylesheet`,
  1631. INVALID_STYLE: "Invalid style declaration",
  1632. UNCLOSED_STYLE: "Unclosed style declaration",
  1633. NO_PROPERTY: "Missing style property in declaration",
  1634. NO_VALUE: "Missing style value in declaration",
  1635. NO_STYLE_OR_REMOVE:
  1636. "Style should be declared or :remove() pseudo-class should used",
  1637. NO_COMMENT: "Comments are not supported",
  1638. };
  1639. const NO_AT_RULE_ERROR_PREFIX = "At-rules are not supported";
  1640. const REMOVE_ERROR_PREFIX = {
  1641. INVALID_REMOVE: "Invalid :remove() pseudo-class in selector",
  1642. NO_TARGET_SELECTOR: `${NO_SELECTOR_ERROR_PREFIX} before :remove() pseudo-class`,
  1643. MULTIPLE_USAGE:
  1644. "Pseudo-class :remove() appears more than once in selector",
  1645. INVALID_POSITION:
  1646. "Pseudo-class :remove() should be at the end of selector",
  1647. };
  1648. const MATCHING_ELEMENT_ERROR_PREFIX = "Error while matching element";
  1649. const MAX_STYLE_PROTECTION_COUNT = 50;
  1650. /**
  1651. * Regexp that matches backward compatible syntaxes.
  1652. */
  1653. const REGEXP_VALID_OLD_SYNTAX =
  1654. /\[-(?:ext)-([a-z-_]+)=(["'])((?:(?=(\\?))\4.)*?)\2\]/g;
  1655. /**
  1656. * Marker for checking invalid selector after old-syntax normalizing by selector converter.
  1657. */
  1658. const INVALID_OLD_SYNTAX_MARKER = "[-ext-";
  1659. /**
  1660. * Complex replacement function.
  1661. * Undo quote escaping inside of an extended selector.
  1662. *
  1663. * @param match Whole matched string.
  1664. * @param name Group 1.
  1665. * @param quoteChar Group 2.
  1666. * @param rawValue Group 3.
  1667. *
  1668. * @returns Converted string.
  1669. */
  1670. const evaluateMatch = (match, name, quoteChar, rawValue) => {
  1671. // Unescape quotes
  1672. const re = new RegExp(`([^\\\\]|^)\\\\${quoteChar}`, "g");
  1673. const value = rawValue.replace(re, `$1${quoteChar}`);
  1674. return `:${name}(${value})`;
  1675. }; // ':scope' pseudo may be at start of :has() argument
  1676. // but ExtCssDocument.querySelectorAll() already use it for selecting exact element descendants
  1677. const SCOPE_MARKER_REGEXP = /\(:scope >/g;
  1678. const SCOPE_REPLACER = "(>";
  1679. const MATCHES_CSS_PSEUDO_ELEMENT_REGEXP =
  1680. /(:matches-css)-(before|after)\(/g;
  1681. const convertMatchesCss = (
  1682. match,
  1683. extendedPseudoClass,
  1684. regularPseudoElement
  1685. ) => {
  1686. // ':matches-css-before(' --> ':matches-css(before, '
  1687. // ':matches-css-after(' --> ':matches-css(after, '
  1688. return `${extendedPseudoClass}${BRACKET.PARENTHESES.LEFT}${regularPseudoElement}${COMMA}`;
  1689. };
  1690. /**
  1691. * Handles old syntax and :scope inside :has().
  1692. *
  1693. * @param selector Trimmed selector to normalize.
  1694. *
  1695. * @returns Normalized selector.
  1696. * @throws An error on invalid old extended syntax selector.
  1697. */
  1698. const normalize = (selector) => {
  1699. const normalizedSelector = selector
  1700. .replace(REGEXP_VALID_OLD_SYNTAX, evaluateMatch)
  1701. .replace(SCOPE_MARKER_REGEXP, SCOPE_REPLACER)
  1702. .replace(MATCHES_CSS_PSEUDO_ELEMENT_REGEXP, convertMatchesCss); // validate old syntax after normalizing
  1703. // e.g. '[-ext-matches-css-before=\'content: /^[A-Z][a-z]'
  1704. if (normalizedSelector.includes(INVALID_OLD_SYNTAX_MARKER)) {
  1705. throw new Error(
  1706. `Invalid extended-css old syntax selector: '${selector}'`
  1707. );
  1708. }
  1709. return normalizedSelector;
  1710. };
  1711. /**
  1712. * Prepares the rawSelector before tokenization:
  1713. * 1. Trims it.
  1714. * 2. Converts old syntax `[-ext-pseudo-class="..."]` to new one `:pseudo-class(...)`.
  1715. * 3. Handles :scope pseudo inside :has() pseudo-class arg.
  1716. *
  1717. * @param rawSelector Selector with no style declaration.
  1718. * @returns Prepared selector with no style declaration.
  1719. */
  1720. const convert = (rawSelector) => {
  1721. const trimmedSelector = rawSelector.trim();
  1722. return normalize(trimmedSelector);
  1723. };
  1724. /**
  1725. * Possible token types.
  1726. *
  1727. * IMPORTANT: it is used as 'const' instead of 'enum' to avoid side effects
  1728. * during ExtendedCss import into other libraries.
  1729. */
  1730. const TOKEN_TYPE = {
  1731. MARK: "mark",
  1732. WORD: "word",
  1733. };
  1734. /**
  1735. * Splits `input` string into tokens.
  1736. *
  1737. * @param input Input string to tokenize.
  1738. * @param supportedMarks Array of supported marks to considered as `TOKEN_TYPE.MARK`;
  1739. * all other will be considered as `TOKEN_TYPE.WORD`.
  1740. *
  1741. * @returns Array of tokens.
  1742. */
  1743. const tokenize = (input, supportedMarks) => {
  1744. // buffer is needed for words collecting while iterating
  1745. let wordBuffer = ""; // result collection
  1746. const tokens = [];
  1747. const selectorSymbols = input.split(""); // iterate through selector chars and collect tokens
  1748. selectorSymbols.forEach((symbol) => {
  1749. if (supportedMarks.includes(symbol)) {
  1750. // if anything was collected to the buffer before
  1751. if (wordBuffer.length > 0) {
  1752. // now it is time to stop buffer collecting and save is as "word"
  1753. tokens.push({
  1754. type: TOKEN_TYPE.WORD,
  1755. value: wordBuffer,
  1756. }); // reset the buffer
  1757. wordBuffer = "";
  1758. } // save current symbol as "mark"
  1759. tokens.push({
  1760. type: TOKEN_TYPE.MARK,
  1761. value: symbol,
  1762. });
  1763. return;
  1764. } // otherwise collect symbol to the buffer
  1765. wordBuffer += symbol;
  1766. }); // save the last collected word
  1767. if (wordBuffer.length > 0) {
  1768. tokens.push({
  1769. type: TOKEN_TYPE.WORD,
  1770. value: wordBuffer,
  1771. });
  1772. }
  1773. return tokens;
  1774. };
  1775. /**
  1776. * Prepares `rawSelector` and splits it into tokens.
  1777. *
  1778. * @param rawSelector Raw css selector.
  1779. *
  1780. * @returns Array of tokens supported for selector.
  1781. */
  1782. const tokenizeSelector = (rawSelector) => {
  1783. const selector = convert(rawSelector);
  1784. return tokenize(selector, SUPPORTED_SELECTOR_MARKS);
  1785. };
  1786. /**
  1787. * Splits `attribute` into tokens.
  1788. *
  1789. * @param attribute Input attribute.
  1790. *
  1791. * @returns Array of tokens supported for attribute.
  1792. */
  1793. const tokenizeAttribute = (attribute) => {
  1794. // equal sigh `=` in attribute is considered as `TOKEN_TYPE.MARK`
  1795. return tokenize(attribute, [...SUPPORTED_SELECTOR_MARKS, EQUAL_SIGN]);
  1796. };
  1797. /**
  1798. * Some browsers do not support Array.prototype.flat()
  1799. * e.g. Opera 42 which is used for browserstack tests.
  1800. *
  1801. * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat}
  1802. *
  1803. * @param input Array needed to be flatten.
  1804. *
  1805. * @returns Flatten array.
  1806. * @throws An error if array cannot be flatten.
  1807. */
  1808. const flatten = (input) => {
  1809. const stack = [];
  1810. input.forEach((el) => stack.push(el));
  1811. const res = [];
  1812. while (stack.length) {
  1813. // pop value from stack
  1814. const next = stack.pop();
  1815. if (!next) {
  1816. throw new Error("Unable to make array flat");
  1817. }
  1818. if (Array.isArray(next)) {
  1819. // push back array items, won't modify the original input
  1820. next.forEach((el) => stack.push(el));
  1821. } else {
  1822. res.push(next);
  1823. }
  1824. } // reverse to restore input order
  1825. return res.reverse();
  1826. };
  1827. /**
  1828. * Returns first item from `array`.
  1829. *
  1830. * @param array Input array.
  1831. *
  1832. * @returns First array item, or `undefined` if there is no such item.
  1833. */
  1834. const getFirst = (array) => {
  1835. return array[0];
  1836. };
  1837. /**
  1838. * Returns last item from array.
  1839. *
  1840. * @param array Input array.
  1841. *
  1842. * @returns Last array item, or `undefined` if there is no such item.
  1843. */
  1844. const getLast = (array) => {
  1845. return array[array.length - 1];
  1846. };
  1847. /**
  1848. * Returns array item which is previous to the last one
  1849. * e.g. for `[5, 6, 7, 8]` returns `7`.
  1850. *
  1851. * @param array Input array.
  1852. *
  1853. * @returns Previous to last array item, or `undefined` if there is no such item.
  1854. */
  1855. const getPrevToLast = (array) => {
  1856. return array[array.length - 2];
  1857. };
  1858. /**
  1859. * Takes array of ast node `children` and returns the child by the `index`.
  1860. *
  1861. * @param array Array of ast node children.
  1862. * @param index Index of needed child in the array.
  1863. * @param errorMessage Optional error message to throw.
  1864. *
  1865. * @returns Array item at `index` position.
  1866. * @throws An error if there is no child with specified `index` in array.
  1867. */
  1868. const getItemByIndex = (array, index, errorMessage) => {
  1869. const indexChild = array[index];
  1870. if (!indexChild) {
  1871. throw new Error(
  1872. errorMessage || `No array item found by index ${index}`
  1873. );
  1874. }
  1875. return indexChild;
  1876. };
  1877. const NO_REGULAR_SELECTOR_ERROR =
  1878. "At least one of Selector node children should be RegularSelector";
  1879. /**
  1880. * Checks whether the type of `astNode` is SelectorList.
  1881. *
  1882. * @param astNode Ast node.
  1883. *
  1884. * @returns True if astNode.type === SelectorList.
  1885. */
  1886. const isSelectorListNode = (astNode) => {
  1887. return (
  1888. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  1889. NODE.SELECTOR_LIST
  1890. );
  1891. };
  1892. /**
  1893. * Checks whether the type of `astNode` is Selector.
  1894. *
  1895. * @param astNode Ast node.
  1896. *
  1897. * @returns True if astNode.type === Selector.
  1898. */
  1899. const isSelectorNode = (astNode) => {
  1900. return (
  1901. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  1902. NODE.SELECTOR
  1903. );
  1904. };
  1905. /**
  1906. * Checks whether the type of `astNode` is RegularSelector.
  1907. *
  1908. * @param astNode Ast node.
  1909. *
  1910. * @returns True if astNode.type === RegularSelector.
  1911. */
  1912. const isRegularSelectorNode = (astNode) => {
  1913. return (
  1914. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  1915. NODE.REGULAR_SELECTOR
  1916. );
  1917. };
  1918. /**
  1919. * Checks whether the type of `astNode` is ExtendedSelector.
  1920. *
  1921. * @param astNode Ast node.
  1922. *
  1923. * @returns True if astNode.type === ExtendedSelector.
  1924. */
  1925. const isExtendedSelectorNode = (astNode) => {
  1926. return astNode.type === NODE.EXTENDED_SELECTOR;
  1927. };
  1928. /**
  1929. * Checks whether the type of `astNode` is AbsolutePseudoClass.
  1930. *
  1931. * @param astNode Ast node.
  1932. *
  1933. * @returns True if astNode.type === AbsolutePseudoClass.
  1934. */
  1935. const isAbsolutePseudoClassNode = (astNode) => {
  1936. return (
  1937. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  1938. NODE.ABSOLUTE_PSEUDO_CLASS
  1939. );
  1940. };
  1941. /**
  1942. * Checks whether the type of `astNode` is RelativePseudoClass.
  1943. *
  1944. * @param astNode Ast node.
  1945. *
  1946. * @returns True if astNode.type === RelativePseudoClass.
  1947. */
  1948. const isRelativePseudoClassNode = (astNode) => {
  1949. return (
  1950. (astNode === null || astNode === void 0 ? void 0 : astNode.type) ===
  1951. NODE.RELATIVE_PSEUDO_CLASS
  1952. );
  1953. };
  1954. /**
  1955. * Returns name of `astNode`.
  1956. *
  1957. * @param astNode AbsolutePseudoClass or RelativePseudoClass node.
  1958. *
  1959. * @returns Name of `astNode`.
  1960. * @throws An error on unsupported ast node or no name found.
  1961. */
  1962. const getNodeName = (astNode) => {
  1963. if (astNode === null) {
  1964. throw new Error("Ast node should be defined");
  1965. }
  1966. if (
  1967. !isAbsolutePseudoClassNode(astNode) &&
  1968. !isRelativePseudoClassNode(astNode)
  1969. ) {
  1970. throw new Error(
  1971. "Only AbsolutePseudoClass or RelativePseudoClass ast node can have a name"
  1972. );
  1973. }
  1974. if (!astNode.name) {
  1975. throw new Error("Extended pseudo-class should have a name");
  1976. }
  1977. return astNode.name;
  1978. };
  1979. /**
  1980. * Returns value of `astNode`.
  1981. *
  1982. * @param astNode RegularSelector or AbsolutePseudoClass node.
  1983. * @param errorMessage Optional error message if no value found.
  1984. *
  1985. * @returns Value of `astNode`.
  1986. * @throws An error on unsupported ast node or no value found.
  1987. */
  1988. const getNodeValue = (astNode, errorMessage) => {
  1989. if (astNode === null) {
  1990. throw new Error("Ast node should be defined");
  1991. }
  1992. if (
  1993. !isRegularSelectorNode(astNode) &&
  1994. !isAbsolutePseudoClassNode(astNode)
  1995. ) {
  1996. throw new Error(
  1997. "Only RegularSelector ot AbsolutePseudoClass ast node can have a value"
  1998. );
  1999. }
  2000. if (!astNode.value) {
  2001. throw new Error(
  2002. errorMessage ||
  2003. "Ast RegularSelector ot AbsolutePseudoClass node should have a value"
  2004. );
  2005. }
  2006. return astNode.value;
  2007. };
  2008. /**
  2009. * Returns only RegularSelector nodes from `children`.
  2010. *
  2011. * @param children Array of ast node children.
  2012. *
  2013. * @returns Array of RegularSelector nodes.
  2014. */
  2015. const getRegularSelectorNodes = (children) => {
  2016. return children.filter(isRegularSelectorNode);
  2017. };
  2018. /**
  2019. * Returns the first RegularSelector node from `children`.
  2020. *
  2021. * @param children Array of ast node children.
  2022. * @param errorMessage Optional error message if no value found.
  2023. *
  2024. * @returns Ast RegularSelector node.
  2025. * @throws An error if no RegularSelector node found.
  2026. */
  2027. const getFirstRegularChild = (children, errorMessage) => {
  2028. const regularSelectorNodes = getRegularSelectorNodes(children);
  2029. const firstRegularSelectorNode = getFirst(regularSelectorNodes);
  2030. if (!firstRegularSelectorNode) {
  2031. throw new Error(errorMessage || NO_REGULAR_SELECTOR_ERROR);
  2032. }
  2033. return firstRegularSelectorNode;
  2034. };
  2035. /**
  2036. * Returns the last RegularSelector node from `children`.
  2037. *
  2038. * @param children Array of ast node children.
  2039. *
  2040. * @returns Ast RegularSelector node.
  2041. * @throws An error if no RegularSelector node found.
  2042. */
  2043. const getLastRegularChild = (children) => {
  2044. const regularSelectorNodes = getRegularSelectorNodes(children);
  2045. const lastRegularSelectorNode = getLast(regularSelectorNodes);
  2046. if (!lastRegularSelectorNode) {
  2047. throw new Error(NO_REGULAR_SELECTOR_ERROR);
  2048. }
  2049. return lastRegularSelectorNode;
  2050. };
  2051. /**
  2052. * Returns the only child of `node`.
  2053. *
  2054. * @param node Ast node.
  2055. * @param errorMessage Error message.
  2056. *
  2057. * @returns The only child of ast node.
  2058. * @throws An error if none or more than one child found.
  2059. */
  2060. const getNodeOnlyChild = (node, errorMessage) => {
  2061. if (node.children.length !== 1) {
  2062. throw new Error(errorMessage);
  2063. }
  2064. const onlyChild = getFirst(node.children);
  2065. if (!onlyChild) {
  2066. throw new Error(errorMessage);
  2067. }
  2068. return onlyChild;
  2069. };
  2070. /**
  2071. * Takes ExtendedSelector node and returns its only child.
  2072. *
  2073. * @param extendedSelectorNode ExtendedSelector ast node.
  2074. *
  2075. * @returns AbsolutePseudoClass or RelativePseudoClass.
  2076. * @throws An error if there is no specific pseudo-class ast node.
  2077. */
  2078. const getPseudoClassNode = (extendedSelectorNode) => {
  2079. return getNodeOnlyChild(
  2080. extendedSelectorNode,
  2081. "Extended selector should be specified"
  2082. );
  2083. };
  2084. /**
  2085. * Takes RelativePseudoClass node and returns its only child
  2086. * which is relative SelectorList node.
  2087. *
  2088. * @param pseudoClassNode RelativePseudoClass.
  2089. *
  2090. * @returns Relative SelectorList node.
  2091. * @throws An error if no selector list found.
  2092. */
  2093. const getRelativeSelectorListNode = (pseudoClassNode) => {
  2094. if (!isRelativePseudoClassNode(pseudoClassNode)) {
  2095. throw new Error(
  2096. "Only RelativePseudoClass node can have relative SelectorList node as child"
  2097. );
  2098. }
  2099. return getNodeOnlyChild(
  2100. pseudoClassNode,
  2101. `Missing arg for :${getNodeName(pseudoClassNode)}() pseudo-class`
  2102. );
  2103. };
  2104. const ATTRIBUTE_CASE_INSENSITIVE_FLAG = "i";
  2105. /**
  2106. * Limited list of available symbols before slash `/`
  2107. * to check whether it is valid regexp pattern opening.
  2108. */
  2109. const POSSIBLE_MARKS_BEFORE_REGEXP = {
  2110. COMMON: [
  2111. // e.g. ':matches-attr(/data-/)'
  2112. BRACKET.PARENTHESES.LEFT,
  2113. // e.g. `:matches-attr('/data-/')`
  2114. SINGLE_QUOTE,
  2115. // e.g. ':matches-attr("/data-/")'
  2116. DOUBLE_QUOTE,
  2117. // e.g. ':matches-attr(check=/data-v-/)'
  2118. EQUAL_SIGN,
  2119. // e.g. ':matches-property(inner./_test/=null)'
  2120. DOT,
  2121. // e.g. ':matches-css(height:/20px/)'
  2122. COLON,
  2123. // ':matches-css-after( content : /(\\d+\\s)*me/ )'
  2124. SPACE,
  2125. ],
  2126. CONTAINS: [
  2127. // e.g. ':contains(/text/)'
  2128. BRACKET.PARENTHESES.LEFT,
  2129. // e.g. `:contains('/text/')`
  2130. SINGLE_QUOTE,
  2131. // e.g. ':contains("/text/")'
  2132. DOUBLE_QUOTE,
  2133. ],
  2134. };
  2135. /**
  2136. * Checks whether the passed token is supported extended pseudo-class.
  2137. *
  2138. * @param tokenValue Token value to check.
  2139. *
  2140. * @returns True if `tokenValue` is one of supported extended pseudo-class names.
  2141. */
  2142. const isSupportedPseudoClass = (tokenValue) => {
  2143. return SUPPORTED_PSEUDO_CLASSES.includes(tokenValue);
  2144. };
  2145. /**
  2146. * Checks whether the passed pseudo-class `name` should be optimized,
  2147. * i.e. :not() and :is().
  2148. *
  2149. * @param name Pseudo-class name.
  2150. *
  2151. * @returns True if `name` is one if pseudo-class which should be optimized.
  2152. */
  2153. const isOptimizationPseudoClass = (name) => {
  2154. return OPTIMIZATION_PSEUDO_CLASSES.includes(name);
  2155. };
  2156. /**
  2157. * Checks whether next to "space" token is a continuation of regular selector being processed.
  2158. *
  2159. * @param nextTokenType Type of token next to current one.
  2160. * @param nextTokenValue Value of token next to current one.
  2161. *
  2162. * @returns True if next token seems to be a part of current regular selector.
  2163. */
  2164. const doesRegularContinueAfterSpace = (nextTokenType, nextTokenValue) => {
  2165. // regular selector does not continues after the current token
  2166. if (!nextTokenType || !nextTokenValue) {
  2167. return false;
  2168. }
  2169. return (
  2170. COMBINATORS.includes(nextTokenValue) ||
  2171. nextTokenType === TOKEN_TYPE.WORD || // e.g. '#main *:has(> .ad)'
  2172. nextTokenValue === ASTERISK ||
  2173. nextTokenValue === ID_MARKER ||
  2174. nextTokenValue === CLASS_MARKER || // e.g. 'div :where(.content)'
  2175. nextTokenValue === COLON || // e.g. "div[class*=' ']"
  2176. nextTokenValue === SINGLE_QUOTE || // e.g. 'div[class*=" "]'
  2177. nextTokenValue === DOUBLE_QUOTE ||
  2178. nextTokenValue === BRACKET.SQUARE.LEFT
  2179. );
  2180. };
  2181. /**
  2182. * Checks whether the regexp pattern for pseudo-class arg starts.
  2183. * Needed for `context.isRegexpOpen` flag.
  2184. *
  2185. * @param context Selector parser context.
  2186. * @param prevTokenValue Value of previous token.
  2187. * @param bufferNodeValue Value of bufferNode.
  2188. *
  2189. * @returns True if current token seems to be a start of regexp pseudo-class arg pattern.
  2190. * @throws An error on invalid regexp pattern.
  2191. */
  2192. const isRegexpOpening = (context, prevTokenValue, bufferNodeValue) => {
  2193. const lastExtendedPseudoClassName = getLast(
  2194. context.extendedPseudoNamesStack
  2195. );
  2196. if (!lastExtendedPseudoClassName) {
  2197. throw new Error(
  2198. "Regexp pattern allowed only in arg of extended pseudo-class"
  2199. );
  2200. } // for regexp pattens the slash should not be escaped
  2201. // const isRegexpPatternSlash = prevTokenValue !== BACKSLASH;
  2202. // regexp pattern can be set as arg of pseudo-class
  2203. // which means limited list of available symbols before slash `/`;
  2204. // for :contains() pseudo-class regexp pattern should be at the beginning of arg
  2205. if (CONTAINS_PSEUDO_NAMES.includes(lastExtendedPseudoClassName)) {
  2206. return POSSIBLE_MARKS_BEFORE_REGEXP.CONTAINS.includes(prevTokenValue);
  2207. }
  2208. if (
  2209. prevTokenValue === SLASH &&
  2210. lastExtendedPseudoClassName !== XPATH_PSEUDO_CLASS_MARKER
  2211. ) {
  2212. const rawArgDesc = bufferNodeValue
  2213. ? `in arg part: '${bufferNodeValue}'`
  2214. : "arg";
  2215. throw new Error(
  2216. `Invalid regexp pattern for :${lastExtendedPseudoClassName}() pseudo-class ${rawArgDesc}`
  2217. );
  2218. } // for other pseudo-classes regexp pattern can be either the whole arg or its part
  2219. return POSSIBLE_MARKS_BEFORE_REGEXP.COMMON.includes(prevTokenValue);
  2220. };
  2221. /**
  2222. * Checks whether the attribute starts.
  2223. *
  2224. * @param tokenValue Value of current token.
  2225. * @param prevTokenValue Previous token value.
  2226. *
  2227. * @returns True if combination of current and previous token seems to be **a start** of attribute.
  2228. */
  2229. const isAttributeOpening = (tokenValue, prevTokenValue) => {
  2230. return tokenValue === BRACKET.SQUARE.LEFT && prevTokenValue !== BACKSLASH;
  2231. };
  2232. /**
  2233. * Checks whether the attribute ends.
  2234. *
  2235. * @param context Selector parser context.
  2236. *
  2237. * @returns True if combination of current and previous token seems to be **an end** of attribute.
  2238. * @throws An error on invalid attribute.
  2239. */
  2240. const isAttributeClosing = (context) => {
  2241. var _getPrevToLast;
  2242. if (!context.isAttributeBracketsOpen) {
  2243. return false;
  2244. } // valid attributes may have extra spaces inside.
  2245. // we get rid of them just to simplify the checking and they are skipped only here:
  2246. // - spaces will be collected to the ast with spaces as they were declared is selector
  2247. // - extra spaces in attribute are not relevant to attribute syntax validity
  2248. // e.g. 'a[ title ]' is the same as 'a[title]'
  2249. // 'div[style *= "MARGIN" i]' is the same as 'div[style*="MARGIN"i]'
  2250. const noSpaceAttr = context.attributeBuffer.split(SPACE).join(""); // tokenize the prepared attribute string
  2251. const attrTokens = tokenizeAttribute(noSpaceAttr);
  2252. const firstAttrToken = getFirst(attrTokens);
  2253. const firstAttrTokenType =
  2254. firstAttrToken === null || firstAttrToken === void 0
  2255. ? void 0
  2256. : firstAttrToken.type;
  2257. const firstAttrTokenValue =
  2258. firstAttrToken === null || firstAttrToken === void 0
  2259. ? void 0
  2260. : firstAttrToken.value; // signal an error on any mark-type token except backslash
  2261. // e.g. '[="margin"]'
  2262. if (
  2263. firstAttrTokenType === TOKEN_TYPE.MARK && // backslash is allowed at start of attribute
  2264. // e.g. '[\\:data-service-slot]'
  2265. firstAttrTokenValue !== BACKSLASH
  2266. ) {
  2267. // eslint-disable-next-line max-len
  2268. throw new Error(
  2269. `'[${context.attributeBuffer}]' is not a valid attribute due to '${firstAttrTokenValue}' at start of it`
  2270. );
  2271. }
  2272. const lastAttrToken = getLast(attrTokens);
  2273. const lastAttrTokenType =
  2274. lastAttrToken === null || lastAttrToken === void 0
  2275. ? void 0
  2276. : lastAttrToken.type;
  2277. const lastAttrTokenValue =
  2278. lastAttrToken === null || lastAttrToken === void 0
  2279. ? void 0
  2280. : lastAttrToken.value;
  2281. if (lastAttrTokenValue === EQUAL_SIGN) {
  2282. // e.g. '[style=]'
  2283. throw new Error(
  2284. `'[${context.attributeBuffer}]' is not a valid attribute due to '${EQUAL_SIGN}'`
  2285. );
  2286. }
  2287. const equalSignIndex = attrTokens.findIndex((token) => {
  2288. return token.type === TOKEN_TYPE.MARK && token.value === EQUAL_SIGN;
  2289. });
  2290. const prevToLastAttrTokenValue =
  2291. (_getPrevToLast = getPrevToLast(attrTokens)) === null ||
  2292. _getPrevToLast === void 0
  2293. ? void 0
  2294. : _getPrevToLast.value;
  2295. if (equalSignIndex === -1) {
  2296. // if there is no '=' inside attribute,
  2297. // it must be just attribute name which means the word-type token before closing bracket
  2298. // e.g. 'div[style]'
  2299. if (lastAttrTokenType === TOKEN_TYPE.WORD) {
  2300. return true;
  2301. }
  2302. return (
  2303. prevToLastAttrTokenValue === BACKSLASH && // some weird attribute are valid too
  2304. // e.g. '[class\\"ads-article\\"]'
  2305. (lastAttrTokenValue === DOUBLE_QUOTE || // e.g. "[class\\'ads-article\\']"
  2306. lastAttrTokenValue === SINGLE_QUOTE)
  2307. );
  2308. } // get the value of token next to `=`
  2309. const nextToEqualSignToken = getItemByIndex(
  2310. attrTokens,
  2311. equalSignIndex + 1
  2312. );
  2313. const nextToEqualSignTokenValue = nextToEqualSignToken.value; // check whether the attribute value wrapper in quotes
  2314. const isAttrValueQuote =
  2315. nextToEqualSignTokenValue === SINGLE_QUOTE ||
  2316. nextToEqualSignTokenValue === DOUBLE_QUOTE; // for no quotes after `=` the last token before `]` should be a word-type one
  2317. // e.g. 'div[style*=margin]'
  2318. // 'div[style*=MARGIN i]'
  2319. if (!isAttrValueQuote) {
  2320. if (lastAttrTokenType === TOKEN_TYPE.WORD) {
  2321. return true;
  2322. } // otherwise signal an error
  2323. // e.g. 'table[style*=border: 0px"]'
  2324. throw new Error(
  2325. `'[${context.attributeBuffer}]' is not a valid attribute`
  2326. );
  2327. } // otherwise if quotes for value are present
  2328. // the last token before `]` can still be word-type token
  2329. // e.g. 'div[style*="MARGIN" i]'
  2330. if (
  2331. lastAttrTokenType === TOKEN_TYPE.WORD &&
  2332. (lastAttrTokenValue === null || lastAttrTokenValue === void 0
  2333. ? void 0
  2334. : lastAttrTokenValue.toLocaleLowerCase()) ===
  2335. ATTRIBUTE_CASE_INSENSITIVE_FLAG
  2336. ) {
  2337. return prevToLastAttrTokenValue === nextToEqualSignTokenValue;
  2338. } // eventually if there is quotes for attribute value and last token is not a word,
  2339. // the closing mark should be the same quote as opening one
  2340. return lastAttrTokenValue === nextToEqualSignTokenValue;
  2341. };
  2342. /**
  2343. * Checks whether the `tokenValue` is a whitespace character.
  2344. *
  2345. * @param tokenValue Token value.
  2346. *
  2347. * @returns True if `tokenValue` is a whitespace character.
  2348. */
  2349. const isWhiteSpaceChar = (tokenValue) => {
  2350. if (!tokenValue) {
  2351. return false;
  2352. }
  2353. return WHITE_SPACE_CHARACTERS.includes(tokenValue);
  2354. };
  2355. /**
  2356. * Checks whether the passed `str` is a name of supported absolute extended pseudo-class,
  2357. * e.g. :contains(), :matches-css() etc.
  2358. *
  2359. * @param str Token value to check.
  2360. *
  2361. * @returns True if `str` is one of absolute extended pseudo-class names.
  2362. */
  2363. const isAbsolutePseudoClass = (str) => {
  2364. return ABSOLUTE_PSEUDO_CLASSES.includes(str);
  2365. };
  2366. /**
  2367. * Checks whether the passed `str` is a name of supported relative extended pseudo-class,
  2368. * e.g. :has(), :not() etc.
  2369. *
  2370. * @param str Token value to check.
  2371. *
  2372. * @returns True if `str` is one of relative extended pseudo-class names.
  2373. */
  2374. const isRelativePseudoClass = (str) => {
  2375. return RELATIVE_PSEUDO_CLASSES.includes(str);
  2376. };
  2377. /**
  2378. * Returns the node which is being collected
  2379. * or null if there is no such one.
  2380. *
  2381. * @param context Selector parser context.
  2382. *
  2383. * @returns Buffer node or null.
  2384. */
  2385. const getBufferNode = (context) => {
  2386. if (context.pathToBufferNode.length === 0) {
  2387. return null;
  2388. } // buffer node is always the last in the pathToBufferNode stack
  2389. return getLast(context.pathToBufferNode) || null;
  2390. };
  2391. /**
  2392. * Returns the parent node to the 'buffer node' — which is the one being collected —
  2393. * or null if there is no such one.
  2394. *
  2395. * @param context Selector parser context.
  2396. *
  2397. * @returns Parent node of buffer node or null.
  2398. */
  2399. const getBufferNodeParent = (context) => {
  2400. // at least two nodes should exist — the buffer node and its parent
  2401. // otherwise return null
  2402. if (context.pathToBufferNode.length < 2) {
  2403. return null;
  2404. } // since the buffer node is always the last in the pathToBufferNode stack
  2405. // its parent is previous to it in the stack
  2406. return getPrevToLast(context.pathToBufferNode) || null;
  2407. };
  2408. /**
  2409. * Returns last RegularSelector ast node.
  2410. * Needed for parsing of the complex selector with extended pseudo-class inside it.
  2411. *
  2412. * @param context Selector parser context.
  2413. *
  2414. * @returns Ast RegularSelector node.
  2415. * @throws An error if:
  2416. * - bufferNode is absent;
  2417. * - type of bufferNode is unsupported;
  2418. * - no RegularSelector in bufferNode.
  2419. */
  2420. const getContextLastRegularSelectorNode = (context) => {
  2421. const bufferNode = getBufferNode(context);
  2422. if (!bufferNode) {
  2423. throw new Error("No bufferNode found");
  2424. }
  2425. if (!isSelectorNode(bufferNode)) {
  2426. throw new Error("Unsupported bufferNode type");
  2427. }
  2428. const lastRegularSelectorNode = getLastRegularChild(bufferNode.children);
  2429. context.pathToBufferNode.push(lastRegularSelectorNode);
  2430. return lastRegularSelectorNode;
  2431. };
  2432. /**
  2433. * Updates needed buffer node value while tokens iterating.
  2434. * For RegularSelector also collects token values to context.attributeBuffer
  2435. * for proper attribute parsing.
  2436. *
  2437. * @param context Selector parser context.
  2438. * @param tokenValue Value of current token.
  2439. *
  2440. * @throws An error if:
  2441. * - no bufferNode;
  2442. * - bufferNode.type is not RegularSelector or AbsolutePseudoClass.
  2443. */
  2444. const updateBufferNode = (context, tokenValue) => {
  2445. const bufferNode = getBufferNode(context);
  2446. if (bufferNode === null) {
  2447. throw new Error("No bufferNode to update");
  2448. }
  2449. if (isAbsolutePseudoClassNode(bufferNode)) {
  2450. bufferNode.value += tokenValue;
  2451. } else if (isRegularSelectorNode(bufferNode)) {
  2452. bufferNode.value += tokenValue;
  2453. if (context.isAttributeBracketsOpen) {
  2454. context.attributeBuffer += tokenValue;
  2455. }
  2456. } else {
  2457. // eslint-disable-next-line max-len
  2458. throw new Error(
  2459. `${bufferNode.type} node cannot be updated. Only RegularSelector and AbsolutePseudoClass are supported`
  2460. );
  2461. }
  2462. };
  2463. /**
  2464. * Adds SelectorList node to context.ast at the start of ast collecting.
  2465. *
  2466. * @param context Selector parser context.
  2467. */
  2468. const addSelectorListNode = (context) => {
  2469. const selectorListNode = new AnySelectorNode(NODE.SELECTOR_LIST);
  2470. context.ast = selectorListNode;
  2471. context.pathToBufferNode.push(selectorListNode);
  2472. };
  2473. /**
  2474. * Adds new node to buffer node children.
  2475. * New added node will be considered as buffer node after it.
  2476. *
  2477. * @param context Selector parser context.
  2478. * @param type Type of node to add.
  2479. * @param tokenValue Optional, defaults to `''`, value of processing token.
  2480. *
  2481. * @throws An error if no bufferNode.
  2482. */
  2483. const addAstNodeByType = function (context, type) {
  2484. let tokenValue =
  2485. arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "";
  2486. const bufferNode = getBufferNode(context);
  2487. if (bufferNode === null) {
  2488. throw new Error("No buffer node");
  2489. }
  2490. let node;
  2491. if (type === NODE.REGULAR_SELECTOR) {
  2492. node = new RegularSelectorNode(tokenValue);
  2493. } else if (type === NODE.ABSOLUTE_PSEUDO_CLASS) {
  2494. node = new AbsolutePseudoClassNode(tokenValue);
  2495. } else if (type === NODE.RELATIVE_PSEUDO_CLASS) {
  2496. node = new RelativePseudoClassNode(tokenValue);
  2497. } else {
  2498. // SelectorList || Selector || ExtendedSelector
  2499. node = new AnySelectorNode(type);
  2500. }
  2501. bufferNode.addChild(node);
  2502. context.pathToBufferNode.push(node);
  2503. };
  2504. /**
  2505. * The very beginning of ast collecting.
  2506. *
  2507. * @param context Selector parser context.
  2508. * @param tokenValue Value of regular selector.
  2509. */
  2510. const initAst = (context, tokenValue) => {
  2511. addSelectorListNode(context);
  2512. addAstNodeByType(context, NODE.SELECTOR); // RegularSelector node is always the first child of Selector node
  2513. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  2514. };
  2515. /**
  2516. * Inits selector list subtree for relative extended pseudo-classes, e.g. :has(), :not().
  2517. *
  2518. * @param context Selector parser context.
  2519. * @param tokenValue Optional, defaults to `''`, value of inner regular selector.
  2520. */
  2521. const initRelativeSubtree = function (context) {
  2522. let tokenValue =
  2523. arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
  2524. addAstNodeByType(context, NODE.SELECTOR_LIST);
  2525. addAstNodeByType(context, NODE.SELECTOR);
  2526. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  2527. };
  2528. /**
  2529. * Goes to closest parent specified by type.
  2530. * Actually updates path to buffer node for proper ast collecting of selectors while parsing.
  2531. *
  2532. * @param context Selector parser context.
  2533. * @param parentType Type of needed parent node in ast.
  2534. */
  2535. const upToClosest = (context, parentType) => {
  2536. for (let i = context.pathToBufferNode.length - 1; i >= 0; i -= 1) {
  2537. var _context$pathToBuffer;
  2538. if (
  2539. ((_context$pathToBuffer = context.pathToBufferNode[i]) === null ||
  2540. _context$pathToBuffer === void 0
  2541. ? void 0
  2542. : _context$pathToBuffer.type) === parentType
  2543. ) {
  2544. context.pathToBufferNode = context.pathToBufferNode.slice(0, i + 1);
  2545. break;
  2546. }
  2547. }
  2548. };
  2549. /**
  2550. * Returns needed buffer node updated due to complex selector parsing.
  2551. *
  2552. * @param context Selector parser context.
  2553. *
  2554. * @returns Ast node for following selector parsing.
  2555. * @throws An error if there is no upper SelectorNode is ast.
  2556. */
  2557. const getUpdatedBufferNode = (context) => {
  2558. // it may happen during the parsing of selector list
  2559. // which is an argument of relative pseudo-class
  2560. // e.g. '.banner:has(~span, ~p)'
  2561. // parser position is here ↑
  2562. // so if after the comma the buffer node type is SelectorList and parent type is RelativePseudoClass
  2563. // we should simply return the current buffer node
  2564. const bufferNode = getBufferNode(context);
  2565. if (
  2566. bufferNode &&
  2567. isSelectorListNode(bufferNode) &&
  2568. isRelativePseudoClassNode(getBufferNodeParent(context))
  2569. ) {
  2570. return bufferNode;
  2571. }
  2572. upToClosest(context, NODE.SELECTOR);
  2573. const selectorNode = getBufferNode(context);
  2574. if (!selectorNode) {
  2575. throw new Error(
  2576. "No SelectorNode, impossible to continue selector parsing by ExtendedCss"
  2577. );
  2578. }
  2579. const lastSelectorNodeChild = getLast(selectorNode.children);
  2580. const hasExtended =
  2581. lastSelectorNodeChild &&
  2582. isExtendedSelectorNode(lastSelectorNodeChild) && // parser position might be inside standard pseudo-class brackets which has space
  2583. // e.g. 'div:contains(/а/):nth-child(100n + 2)'
  2584. context.standardPseudoBracketsStack.length === 0;
  2585. const supposedPseudoClassNode =
  2586. hasExtended && getFirst(lastSelectorNodeChild.children);
  2587. let newNeededBufferNode = selectorNode;
  2588. if (supposedPseudoClassNode) {
  2589. // name of pseudo-class for last extended-node child for Selector node
  2590. const lastExtendedPseudoName =
  2591. hasExtended && supposedPseudoClassNode.name;
  2592. const isLastExtendedNameRelative =
  2593. lastExtendedPseudoName &&
  2594. isRelativePseudoClass(lastExtendedPseudoName);
  2595. const isLastExtendedNameAbsolute =
  2596. lastExtendedPseudoName &&
  2597. isAbsolutePseudoClass(lastExtendedPseudoName);
  2598. const hasRelativeExtended =
  2599. isLastExtendedNameRelative &&
  2600. context.extendedPseudoBracketsStack.length > 0 &&
  2601. context.extendedPseudoBracketsStack.length ===
  2602. context.extendedPseudoNamesStack.length;
  2603. const hasAbsoluteExtended =
  2604. isLastExtendedNameAbsolute &&
  2605. lastExtendedPseudoName === getLast(context.extendedPseudoNamesStack);
  2606. if (hasRelativeExtended) {
  2607. // return relative selector node to update later
  2608. context.pathToBufferNode.push(lastSelectorNodeChild);
  2609. newNeededBufferNode = supposedPseudoClassNode;
  2610. } else if (hasAbsoluteExtended) {
  2611. // return absolute selector node to update later
  2612. context.pathToBufferNode.push(lastSelectorNodeChild);
  2613. newNeededBufferNode = supposedPseudoClassNode;
  2614. }
  2615. } else if (hasExtended) {
  2616. // return selector node to add new regular selector node later
  2617. newNeededBufferNode = selectorNode;
  2618. } else {
  2619. // otherwise return last regular selector node to update later
  2620. newNeededBufferNode = getContextLastRegularSelectorNode(context);
  2621. } // update the path to buffer node properly
  2622. context.pathToBufferNode.push(newNeededBufferNode);
  2623. return newNeededBufferNode;
  2624. };
  2625. /**
  2626. * Checks values of few next tokens on colon token `:` and:
  2627. * - updates buffer node for following standard pseudo-class;
  2628. * - adds extended selector ast node for following extended pseudo-class;
  2629. * - validates some cases of `:remove()` and `:has()` usage.
  2630. *
  2631. * @param context Selector parser context.
  2632. * @param selector Selector.
  2633. * @param tokenValue Value of current token.
  2634. * @param nextTokenValue Value of token next to current one.
  2635. * @param nextToNextTokenValue Value of token next to next to current one.
  2636. *
  2637. * @throws An error on :remove() pseudo-class in selector
  2638. * or :has() inside regular pseudo limitation.
  2639. */
  2640. const handleNextTokenOnColon = (
  2641. context,
  2642. selector,
  2643. tokenValue,
  2644. nextTokenValue,
  2645. nextToNextTokenValue
  2646. ) => {
  2647. if (!nextTokenValue) {
  2648. throw new Error(
  2649. `Invalid colon ':' at the end of selector: '${selector}'`
  2650. );
  2651. }
  2652. if (!isSupportedPseudoClass(nextTokenValue.toLowerCase())) {
  2653. if (nextTokenValue.toLowerCase() === REMOVE_PSEUDO_MARKER) {
  2654. // :remove() pseudo-class should be handled before
  2655. // as it is not about element selecting but actions with elements
  2656. // e.g. 'body > div:empty:remove()'
  2657. throw new Error(
  2658. `${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`
  2659. );
  2660. } // if following token is not an extended pseudo
  2661. // the colon should be collected to value of RegularSelector
  2662. // e.g. '.entry_text:nth-child(2)'
  2663. updateBufferNode(context, tokenValue); // check the token after the pseudo and do balance parentheses later
  2664. // only if it is functional pseudo-class (standard with brackets, e.g. ':lang()').
  2665. // no brackets balance needed for such case,
  2666. // parser position is on first colon after the 'div':
  2667. // e.g. 'div:last-child:has(button.privacy-policy__btn)'
  2668. if (
  2669. nextToNextTokenValue &&
  2670. nextToNextTokenValue === BRACKET.PARENTHESES.LEFT && // no brackets balance needed for parentheses inside attribute value
  2671. // e.g. 'a[href="javascript:void(0)"]' <-- parser position is on colon `:`
  2672. // before `void` ↑
  2673. !context.isAttributeBracketsOpen
  2674. ) {
  2675. context.standardPseudoNamesStack.push(nextTokenValue);
  2676. }
  2677. } else {
  2678. // it is supported extended pseudo-class.
  2679. // Disallow :has() inside the pseudos accepting only compound selectors
  2680. // https://bugs.chromium.org/p/chromium/issues/detail?id=669058#c54 [2]
  2681. if (
  2682. HAS_PSEUDO_CLASS_MARKERS.includes(nextTokenValue) &&
  2683. context.standardPseudoNamesStack.length > 0
  2684. ) {
  2685. // eslint-disable-next-line max-len
  2686. throw new Error(
  2687. `Usage of :${nextTokenValue}() pseudo-class is not allowed inside regular pseudo: '${getLast(
  2688. context.standardPseudoNamesStack
  2689. )}'`
  2690. );
  2691. } else {
  2692. // stop RegularSelector value collecting
  2693. upToClosest(context, NODE.SELECTOR); // add ExtendedSelector to Selector children
  2694. addAstNodeByType(context, NODE.EXTENDED_SELECTOR);
  2695. }
  2696. }
  2697. };
  2698. // e.g. ':is(.page, .main) > .banner' or '*:not(span):not(p)'
  2699. const IS_OR_NOT_PSEUDO_SELECTING_ROOT = `html ${ASTERISK}`;
  2700. /**
  2701. * Checks if there are any ExtendedSelector node in selector list.
  2702. *
  2703. * @param selectorList Ast SelectorList node.
  2704. *
  2705. * @returns True if `selectorList` has any inner ExtendedSelector node.
  2706. */
  2707. const hasExtendedSelector = (selectorList) => {
  2708. return selectorList.children.some((selectorNode) => {
  2709. return selectorNode.children.some((selectorNodeChild) => {
  2710. return isExtendedSelectorNode(selectorNodeChild);
  2711. });
  2712. });
  2713. };
  2714. /**
  2715. * Converts selector list of RegularSelector nodes to string.
  2716. *
  2717. * @param selectorList Ast SelectorList node.
  2718. *
  2719. * @returns String representation for selector list of regular selectors.
  2720. */
  2721. const selectorListOfRegularsToString = (selectorList) => {
  2722. // if there is no ExtendedSelector in relative SelectorList
  2723. // it means that each Selector node has single child — RegularSelector node
  2724. // and their values should be combined to string
  2725. const standardCssSelectors = selectorList.children.map((selectorNode) => {
  2726. const selectorOnlyChild = getNodeOnlyChild(
  2727. selectorNode,
  2728. "Ast Selector node should have RegularSelector node"
  2729. );
  2730. return getNodeValue(selectorOnlyChild);
  2731. });
  2732. return standardCssSelectors.join(`${COMMA}${SPACE}`);
  2733. };
  2734. /**
  2735. * Updates children of `node` replacing them with `newChildren`.
  2736. * Important: modifies input `node` which is passed by reference.
  2737. *
  2738. * @param node Ast node to update.
  2739. * @param newChildren Array of new children for ast node.
  2740. *
  2741. * @returns Updated ast node.
  2742. */
  2743. const updateNodeChildren = (node, newChildren) => {
  2744. node.children = newChildren;
  2745. return node;
  2746. };
  2747. /**
  2748. * Recursively checks whether the ExtendedSelector node should be optimized.
  2749. * It has to be recursive because RelativePseudoClass has inner SelectorList node.
  2750. *
  2751. * @param currExtendedSelectorNode Ast ExtendedSelector node.
  2752. *
  2753. * @returns True is ExtendedSelector should be optimized.
  2754. */
  2755. const shouldOptimizeExtendedSelector = (currExtendedSelectorNode) => {
  2756. if (currExtendedSelectorNode === null) {
  2757. return false;
  2758. }
  2759. const extendedPseudoClassNode = getPseudoClassNode(
  2760. currExtendedSelectorNode
  2761. );
  2762. const pseudoName = getNodeName(extendedPseudoClassNode);
  2763. if (isAbsolutePseudoClass(pseudoName)) {
  2764. return false;
  2765. }
  2766. const relativeSelectorList = getRelativeSelectorListNode(
  2767. extendedPseudoClassNode
  2768. );
  2769. const innerSelectorNodes = relativeSelectorList.children; // simple checking for standard selectors in arg of :not() or :is() pseudo-class
  2770. // e.g. 'div > *:is(div, a, span)'
  2771. if (isOptimizationPseudoClass(pseudoName)) {
  2772. const areAllSelectorNodeChildrenRegular = innerSelectorNodes.every(
  2773. (selectorNode) => {
  2774. try {
  2775. const selectorOnlyChild = getNodeOnlyChild(
  2776. selectorNode,
  2777. "Selector node should have RegularSelector"
  2778. ); // it means that the only child is RegularSelector and it can be optimized
  2779. return isRegularSelectorNode(selectorOnlyChild);
  2780. } catch (e) {
  2781. return false;
  2782. }
  2783. }
  2784. );
  2785. if (areAllSelectorNodeChildrenRegular) {
  2786. return true;
  2787. }
  2788. } // for other extended pseudo-classes than :not() and :is()
  2789. return innerSelectorNodes.some((selectorNode) => {
  2790. return selectorNode.children.some((selectorNodeChild) => {
  2791. if (!isExtendedSelectorNode(selectorNodeChild)) {
  2792. return false;
  2793. } // check inner ExtendedSelector recursively
  2794. // e.g. 'div:has(*:not(.header))'
  2795. return shouldOptimizeExtendedSelector(selectorNodeChild);
  2796. });
  2797. });
  2798. };
  2799. /**
  2800. * Returns optimized ExtendedSelector node if it can be optimized
  2801. * or null if ExtendedSelector is fully optimized while function execution
  2802. * which means that value of `prevRegularSelectorNode` is updated.
  2803. *
  2804. * @param currExtendedSelectorNode Current ExtendedSelector node to optimize.
  2805. * @param prevRegularSelectorNode Previous RegularSelector node.
  2806. *
  2807. * @returns Ast node or null.
  2808. */
  2809. const getOptimizedExtendedSelector = (
  2810. currExtendedSelectorNode,
  2811. prevRegularSelectorNode
  2812. ) => {
  2813. if (!currExtendedSelectorNode) {
  2814. return null;
  2815. }
  2816. const extendedPseudoClassNode = getPseudoClassNode(
  2817. currExtendedSelectorNode
  2818. );
  2819. const relativeSelectorList = getRelativeSelectorListNode(
  2820. extendedPseudoClassNode
  2821. );
  2822. const hasInnerExtendedSelector =
  2823. hasExtendedSelector(relativeSelectorList);
  2824. if (!hasInnerExtendedSelector) {
  2825. // if there is no extended selectors for :not() or :is()
  2826. // e.g. 'div:not(.content, .main)'
  2827. const relativeSelectorListStr =
  2828. selectorListOfRegularsToString(relativeSelectorList);
  2829. const pseudoName = getNodeName(extendedPseudoClassNode); // eslint-disable-next-line max-len
  2830. const optimizedExtendedStr = `${COLON}${pseudoName}${BRACKET.PARENTHESES.LEFT}${relativeSelectorListStr}${BRACKET.PARENTHESES.RIGHT}`;
  2831. prevRegularSelectorNode.value = `${getNodeValue(
  2832. prevRegularSelectorNode
  2833. )}${optimizedExtendedStr}`;
  2834. return null;
  2835. } // eslint-disable-next-line @typescript-eslint/no-use-before-define
  2836. const optimizedRelativeSelectorList =
  2837. optimizeSelectorListNode(relativeSelectorList);
  2838. const optimizedExtendedPseudoClassNode = updateNodeChildren(
  2839. extendedPseudoClassNode,
  2840. [optimizedRelativeSelectorList]
  2841. );
  2842. return updateNodeChildren(currExtendedSelectorNode, [
  2843. optimizedExtendedPseudoClassNode,
  2844. ]);
  2845. };
  2846. /**
  2847. * Combines values of `previous` and `current` RegularSelector nodes.
  2848. * It may happen during the optimization when ExtendedSelector between RegularSelector node was optimized.
  2849. *
  2850. * @param current Current RegularSelector node.
  2851. * @param previous Previous RegularSelector node.
  2852. */
  2853. const optimizeCurrentRegularSelector = (current, previous) => {
  2854. previous.value = `${getNodeValue(previous)}${SPACE}${getNodeValue(
  2855. current
  2856. )}`;
  2857. };
  2858. /**
  2859. * Optimizes ast Selector node.
  2860. *
  2861. * @param selectorNode Ast Selector node.
  2862. *
  2863. * @returns Optimized ast node.
  2864. * @throws An error while collecting optimized nodes.
  2865. */
  2866. const optimizeSelectorNode = (selectorNode) => {
  2867. // non-optimized list of SelectorNode children
  2868. const rawSelectorNodeChildren = selectorNode.children; // for collecting optimized children list
  2869. const optimizedChildrenList = [];
  2870. let currentIndex = 0; // iterate through all children in non-optimized ast Selector node
  2871. while (currentIndex < rawSelectorNodeChildren.length) {
  2872. const currentChild = getItemByIndex(
  2873. rawSelectorNodeChildren,
  2874. currentIndex,
  2875. "currentChild should be specified"
  2876. ); // no need to optimize the very first child which is always RegularSelector node
  2877. if (currentIndex === 0) {
  2878. optimizedChildrenList.push(currentChild);
  2879. } else {
  2880. const prevRegularChild = getLastRegularChild(optimizedChildrenList);
  2881. if (isExtendedSelectorNode(currentChild)) {
  2882. // start checking with point is null
  2883. let optimizedExtendedSelector = null; // check whether the optimization is needed
  2884. let isOptimizationNeeded =
  2885. shouldOptimizeExtendedSelector(currentChild); // update optimizedExtendedSelector so it can be optimized recursively
  2886. // i.e. `getOptimizedExtendedSelector(optimizedExtendedSelector)` below
  2887. optimizedExtendedSelector = currentChild;
  2888. while (isOptimizationNeeded) {
  2889. // recursively optimize ExtendedSelector until no optimization needed
  2890. // e.g. div > *:is(.banner:not(.block))
  2891. optimizedExtendedSelector = getOptimizedExtendedSelector(
  2892. optimizedExtendedSelector,
  2893. prevRegularChild
  2894. );
  2895. isOptimizationNeeded = shouldOptimizeExtendedSelector(
  2896. optimizedExtendedSelector
  2897. );
  2898. } // if it was simple :not() of :is() with standard selector arg
  2899. // e.g. 'div:not([class][id])'
  2900. // or '.main > *:is([data-loaded], .banner)'
  2901. // after the optimization the ExtendedSelector node become part of RegularSelector
  2902. // so nothing to save eventually
  2903. // otherwise the optimized ExtendedSelector should be saved
  2904. // e.g. 'div:has(:not([class]))'
  2905. if (optimizedExtendedSelector !== null) {
  2906. optimizedChildrenList.push(optimizedExtendedSelector); // if optimization is not needed
  2907. const optimizedPseudoClass = getPseudoClassNode(
  2908. optimizedExtendedSelector
  2909. );
  2910. const optimizedPseudoName = getNodeName(optimizedPseudoClass); // parent element checking is used to apply :is() and :not() pseudo-classes as extended.
  2911. // as there is no parentNode for root element (html)
  2912. // so element selection should be limited to it's children
  2913. // e.g. '*:is(:has(.page))' -> 'html *:is(has(.page))'
  2914. // or '*:not(:has(span))' -> 'html *:not(:has(span))'
  2915. if (
  2916. getNodeValue(prevRegularChild) === ASTERISK &&
  2917. isOptimizationPseudoClass(optimizedPseudoName)
  2918. ) {
  2919. prevRegularChild.value = IS_OR_NOT_PSEUDO_SELECTING_ROOT;
  2920. }
  2921. }
  2922. } else if (isRegularSelectorNode(currentChild)) {
  2923. // in non-optimized ast, RegularSelector node may follow ExtendedSelector which should be optimized
  2924. // for example, for 'div:not(.content) > .banner' schematically it looks like
  2925. // non-optimized ast: [
  2926. // 1. RegularSelector: 'div'
  2927. // 2. ExtendedSelector: 'not(.content)'
  2928. // 3. RegularSelector: '> .banner'
  2929. // ]
  2930. // which after the ExtendedSelector looks like
  2931. // partly optimized ast: [
  2932. // 1. RegularSelector: 'div:not(.content)'
  2933. // 2. RegularSelector: '> .banner'
  2934. // ]
  2935. // so second RegularSelector value should be combined with first one
  2936. // optimized ast: [
  2937. // 1. RegularSelector: 'div:not(.content) > .banner'
  2938. // ]
  2939. // here we check **children of selectorNode** after previous optimization if it was
  2940. const lastOptimizedChild = getLast(optimizedChildrenList) || null;
  2941. if (isRegularSelectorNode(lastOptimizedChild)) {
  2942. optimizeCurrentRegularSelector(currentChild, prevRegularChild);
  2943. }
  2944. }
  2945. }
  2946. currentIndex += 1;
  2947. }
  2948. return updateNodeChildren(selectorNode, optimizedChildrenList);
  2949. };
  2950. /**
  2951. * Optimizes ast SelectorList node.
  2952. *
  2953. * @param selectorListNode SelectorList node.
  2954. *
  2955. * @returns Optimized ast node.
  2956. */
  2957. const optimizeSelectorListNode = (selectorListNode) => {
  2958. return updateNodeChildren(
  2959. selectorListNode,
  2960. selectorListNode.children.map((s) => optimizeSelectorNode(s))
  2961. );
  2962. };
  2963. /**
  2964. * Optimizes ast:
  2965. * If arg of :not() and :is() pseudo-classes does not contain extended selectors,
  2966. * native Document.querySelectorAll() can be used to query elements.
  2967. * It means that ExtendedSelector ast nodes can be removed
  2968. * and value of relevant RegularSelector node should be updated accordingly.
  2969. *
  2970. * @param ast Non-optimized ast.
  2971. *
  2972. * @returns Optimized ast.
  2973. */
  2974. const optimizeAst = (ast) => {
  2975. // ast is basically the selector list of selectors
  2976. return optimizeSelectorListNode(ast);
  2977. };
  2978. // https://github.com/AdguardTeam/ExtendedCss/issues/115
  2979. const XPATH_PSEUDO_SELECTING_ROOT = "body";
  2980. const NO_WHITESPACE_ERROR_PREFIX =
  2981. "No white space is allowed before or after extended pseudo-class name in selector";
  2982. /**
  2983. * Parses selector into ast for following element selection.
  2984. *
  2985. * @param selector Selector to parse.
  2986. *
  2987. * @returns Parsed ast.
  2988. * @throws An error on invalid selector.
  2989. */
  2990. const parse = (selector) => {
  2991. const tokens = tokenizeSelector(selector);
  2992. const context = {
  2993. ast: null,
  2994. pathToBufferNode: [],
  2995. extendedPseudoNamesStack: [],
  2996. extendedPseudoBracketsStack: [],
  2997. standardPseudoNamesStack: [],
  2998. standardPseudoBracketsStack: [],
  2999. isAttributeBracketsOpen: false,
  3000. attributeBuffer: "",
  3001. isRegexpOpen: false,
  3002. shouldOptimize: false,
  3003. };
  3004. let i = 0;
  3005. while (i < tokens.length) {
  3006. const token = tokens[i];
  3007. if (!token) {
  3008. break;
  3009. } // Token to process
  3010. const { type: tokenType, value: tokenValue } = token; // needed for SPACE and COLON tokens checking
  3011. const nextToken = tokens[i + 1];
  3012. const nextTokenType =
  3013. nextToken === null || nextToken === void 0 ? void 0 : nextToken.type;
  3014. const nextTokenValue =
  3015. nextToken === null || nextToken === void 0 ? void 0 : nextToken.value; // needed for limitations
  3016. // - :not() and :is() root element
  3017. // - :has() usage
  3018. // - white space before and after pseudo-class name
  3019. const nextToNextToken = tokens[i + 2];
  3020. const nextToNextTokenValue =
  3021. nextToNextToken === null || nextToNextToken === void 0
  3022. ? void 0
  3023. : nextToNextToken.value; // needed for COLON token checking for none-specified regular selector before extended one
  3024. // e.g. 'p, :hover'
  3025. // or '.banner, :contains(ads)'
  3026. const previousToken = tokens[i - 1];
  3027. const prevTokenType =
  3028. previousToken === null || previousToken === void 0
  3029. ? void 0
  3030. : previousToken.type;
  3031. const prevTokenValue =
  3032. previousToken === null || previousToken === void 0
  3033. ? void 0
  3034. : previousToken.value; // needed for proper parsing of regexp pattern arg
  3035. // e.g. ':matches-css(background-image: /^url\(https:\/\/example\.org\//)'
  3036. const previousToPreviousToken = tokens[i - 2];
  3037. const prevToPrevTokenValue =
  3038. previousToPreviousToken === null || previousToPreviousToken === void 0
  3039. ? void 0
  3040. : previousToPreviousToken.value;
  3041. let bufferNode = getBufferNode(context);
  3042. switch (tokenType) {
  3043. case TOKEN_TYPE.WORD:
  3044. if (bufferNode === null) {
  3045. // there is no buffer node only in one case — no ast collecting has been started
  3046. initAst(context, tokenValue);
  3047. } else if (isSelectorListNode(bufferNode)) {
  3048. // add new selector to selector list
  3049. addAstNodeByType(context, NODE.SELECTOR);
  3050. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  3051. } else if (isRegularSelectorNode(bufferNode)) {
  3052. updateBufferNode(context, tokenValue);
  3053. } else if (isExtendedSelectorNode(bufferNode)) {
  3054. // No white space is allowed between the name of extended pseudo-class
  3055. // and its opening parenthesis
  3056. // https://www.w3.org/TR/selectors-4/#pseudo-classes
  3057. // e.g. 'span:contains (text)'
  3058. if (
  3059. isWhiteSpaceChar(nextTokenValue) &&
  3060. nextToNextTokenValue === BRACKET.PARENTHESES.LEFT
  3061. ) {
  3062. throw new Error(`${NO_WHITESPACE_ERROR_PREFIX}: '${selector}'`);
  3063. }
  3064. const lowerCaseTokenValue = tokenValue.toLowerCase(); // save pseudo-class name for brackets balance checking
  3065. context.extendedPseudoNamesStack.push(lowerCaseTokenValue); // extended pseudo-class name are parsed in lower case
  3066. // as they should be case-insensitive
  3067. // https://www.w3.org/TR/selectors-4/#pseudo-classes
  3068. if (isAbsolutePseudoClass(lowerCaseTokenValue)) {
  3069. addAstNodeByType(
  3070. context,
  3071. NODE.ABSOLUTE_PSEUDO_CLASS,
  3072. lowerCaseTokenValue
  3073. );
  3074. } else {
  3075. // if it is not absolute pseudo-class, it must be relative one
  3076. // add RelativePseudoClass with tokenValue as pseudo-class name to ExtendedSelector children
  3077. addAstNodeByType(
  3078. context,
  3079. NODE.RELATIVE_PSEUDO_CLASS,
  3080. lowerCaseTokenValue
  3081. ); // for :not() and :is() pseudo-classes parsed ast should be optimized later
  3082. if (isOptimizationPseudoClass(lowerCaseTokenValue)) {
  3083. context.shouldOptimize = true;
  3084. }
  3085. }
  3086. } else if (isAbsolutePseudoClassNode(bufferNode)) {
  3087. // collect absolute pseudo-class arg
  3088. updateBufferNode(context, tokenValue);
  3089. } else if (isRelativePseudoClassNode(bufferNode)) {
  3090. initRelativeSubtree(context, tokenValue);
  3091. }
  3092. break;
  3093. case TOKEN_TYPE.MARK:
  3094. switch (tokenValue) {
  3095. case COMMA:
  3096. if (
  3097. !bufferNode ||
  3098. (typeof bufferNode !== "undefined" && !nextTokenValue)
  3099. ) {
  3100. // consider the selector is invalid if there is no bufferNode yet (e.g. ', a')
  3101. // or there is nothing after the comma while bufferNode is defined (e.g. 'div, ')
  3102. throw new Error(`'${selector}' is not a valid selector`);
  3103. } else if (isRegularSelectorNode(bufferNode)) {
  3104. if (context.isAttributeBracketsOpen) {
  3105. // the comma might be inside element attribute value
  3106. // e.g. 'div[data-comma="0,1"]'
  3107. updateBufferNode(context, tokenValue);
  3108. } else {
  3109. // new Selector should be collected to upper SelectorList
  3110. upToClosest(context, NODE.SELECTOR_LIST);
  3111. }
  3112. } else if (isAbsolutePseudoClassNode(bufferNode)) {
  3113. // the comma inside arg of absolute extended pseudo
  3114. // e.g. 'div:xpath(//h3[contains(text(),"Share it!")]/..)'
  3115. updateBufferNode(context, tokenValue);
  3116. } else if (isSelectorNode(bufferNode)) {
  3117. // new Selector should be collected to upper SelectorList
  3118. // if parser position is on Selector node
  3119. upToClosest(context, NODE.SELECTOR_LIST);
  3120. }
  3121. break;
  3122. case SPACE:
  3123. // it might be complex selector with extended pseudo-class inside it
  3124. // and the space is between that complex selector and following regular selector
  3125. // parser position is on ` ` before `span` now:
  3126. // e.g. 'div:has(img).banner span'
  3127. // so we need to check whether the new ast node should be added (example above)
  3128. // or previous regular selector node should be updated
  3129. if (
  3130. isRegularSelectorNode(bufferNode) && // no need to update the buffer node if attribute value is being parsed
  3131. // e.g. 'div:not([id])[style="position: absolute; z-index: 10000;"]'
  3132. // parser position inside attribute ↑
  3133. !context.isAttributeBracketsOpen
  3134. ) {
  3135. bufferNode = getUpdatedBufferNode(context);
  3136. }
  3137. if (isRegularSelectorNode(bufferNode)) {
  3138. // standard selectors with white space between colon and name of pseudo
  3139. // are invalid for native document.querySelectorAll() anyway,
  3140. // so throwing the error here is better
  3141. // than proper parsing of invalid selector and passing it further.
  3142. // first of all do not check attributes
  3143. // e.g. div[style="text-align: center"]
  3144. if (
  3145. !context.isAttributeBracketsOpen && // check the space after the colon and before the pseudo
  3146. // e.g. '.block: nth-child(2)
  3147. ((prevTokenValue === COLON &&
  3148. nextTokenType === TOKEN_TYPE.WORD) || // or after the pseudo and before the opening parenthesis
  3149. // e.g. '.block:nth-child (2)
  3150. (prevTokenType === TOKEN_TYPE.WORD &&
  3151. nextTokenValue === BRACKET.PARENTHESES.LEFT))
  3152. ) {
  3153. throw new Error(`'${selector}' is not a valid selector`);
  3154. } // collect current tokenValue to value of RegularSelector
  3155. // if it is the last token or standard selector continues after the space.
  3156. // otherwise it will be skipped
  3157. if (
  3158. !nextTokenValue ||
  3159. doesRegularContinueAfterSpace(
  3160. nextTokenType,
  3161. nextTokenValue
  3162. ) || // we also should collect space inside attribute value
  3163. // e.g. `[onclick^="window.open ('https://example.com/share?url="]`
  3164. // parser position ↑
  3165. context.isAttributeBracketsOpen
  3166. ) {
  3167. updateBufferNode(context, tokenValue);
  3168. }
  3169. }
  3170. if (isAbsolutePseudoClassNode(bufferNode)) {
  3171. // space inside extended pseudo-class arg
  3172. // e.g. 'span:contains(some text)'
  3173. updateBufferNode(context, tokenValue);
  3174. }
  3175. if (isRelativePseudoClassNode(bufferNode)) {
  3176. // init with empty value RegularSelector
  3177. // as the space is not needed for selector value
  3178. // e.g. 'p:not( .content )'
  3179. initRelativeSubtree(context);
  3180. }
  3181. if (isSelectorNode(bufferNode)) {
  3182. // do NOT add RegularSelector if parser position on space BEFORE the comma in selector list
  3183. // e.g. '.block:has(> img) , .banner)'
  3184. if (
  3185. doesRegularContinueAfterSpace(nextTokenType, nextTokenValue)
  3186. ) {
  3187. // regular selector might be after the extended one.
  3188. // extra space before combinator or selector should not be collected
  3189. // e.g. '.banner:upward(2) .block'
  3190. // '.banner:upward(2) > .block'
  3191. // so no tokenValue passed to addAnySelectorNode()
  3192. addAstNodeByType(context, NODE.REGULAR_SELECTOR);
  3193. }
  3194. }
  3195. break;
  3196. case DESCENDANT_COMBINATOR:
  3197. case CHILD_COMBINATOR:
  3198. case NEXT_SIBLING_COMBINATOR:
  3199. case SUBSEQUENT_SIBLING_COMBINATOR:
  3200. case SEMICOLON:
  3201. case SLASH:
  3202. case BACKSLASH:
  3203. case SINGLE_QUOTE:
  3204. case DOUBLE_QUOTE:
  3205. case CARET:
  3206. case DOLLAR_SIGN:
  3207. case BRACKET.CURLY.LEFT:
  3208. case BRACKET.CURLY.RIGHT:
  3209. case ASTERISK:
  3210. case ID_MARKER:
  3211. case CLASS_MARKER:
  3212. case BRACKET.SQUARE.LEFT:
  3213. // it might be complex selector with extended pseudo-class inside it
  3214. // and the space is between that complex selector and following regular selector
  3215. // e.g. 'div:has(img).banner' // parser position is on `.` before `banner` now
  3216. // 'div:has(img)[attr]' // parser position is on `[` before `attr` now
  3217. // so we need to check whether the new ast node should be added (example above)
  3218. // or previous regular selector node should be updated
  3219. if (COMBINATORS.includes(tokenValue)) {
  3220. if (bufferNode === null) {
  3221. // cases where combinator at very beginning of a selector
  3222. // e.g. '> div'
  3223. // or '~ .banner'
  3224. // or even '+js(overlay-buster)' which not a selector at all
  3225. // but may be validated by FilterCompiler so error message should be appropriate
  3226. throw new Error(`'${selector}' is not a valid selector`);
  3227. }
  3228. bufferNode = getUpdatedBufferNode(context);
  3229. }
  3230. if (bufferNode === null) {
  3231. // no ast collecting has been started
  3232. // e.g. '.banner > p'
  3233. // or '#top > div.ad'
  3234. // or '[class][style][attr]'
  3235. // or '*:not(span)'
  3236. initAst(context, tokenValue);
  3237. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  3238. // e.g. '[class^="banner-"]'
  3239. context.isAttributeBracketsOpen = true;
  3240. }
  3241. } else if (isRegularSelectorNode(bufferNode)) {
  3242. if (
  3243. tokenValue === BRACKET.CURLY.LEFT &&
  3244. !(context.isAttributeBracketsOpen || context.isRegexpOpen)
  3245. ) {
  3246. // e.g. 'div { content: "'
  3247. throw new Error(`'${selector}' is not a valid selector`);
  3248. } // collect the mark to the value of RegularSelector node
  3249. updateBufferNode(context, tokenValue);
  3250. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  3251. // needed for proper handling element attribute value with comma
  3252. // e.g. 'div[data-comma="0,1"]'
  3253. context.isAttributeBracketsOpen = true;
  3254. }
  3255. } else if (isAbsolutePseudoClassNode(bufferNode)) {
  3256. // collect the mark to the arg of AbsolutePseudoClass node
  3257. updateBufferNode(context, tokenValue); // 'isRegexpOpen' flag is needed for brackets balancing inside extended pseudo-class arg
  3258. if (
  3259. tokenValue === SLASH &&
  3260. context.extendedPseudoNamesStack.length > 0
  3261. ) {
  3262. if (
  3263. prevTokenValue === SLASH &&
  3264. prevToPrevTokenValue === BACKSLASH
  3265. ) {
  3266. // it may be specific url regexp pattern in arg of pseudo-class
  3267. // e.g. ':matches-css(background-image: /^url\(https:\/\/example\.org\//)'
  3268. // parser position is on final slash before `)` ↑
  3269. context.isRegexpOpen = false;
  3270. } else if (prevTokenValue && prevTokenValue !== BACKSLASH) {
  3271. if (
  3272. isRegexpOpening(
  3273. context,
  3274. prevTokenValue,
  3275. getNodeValue(bufferNode)
  3276. )
  3277. ) {
  3278. context.isRegexpOpen = !context.isRegexpOpen;
  3279. } else {
  3280. // otherwise force `isRegexpOpen` flag to `false`
  3281. context.isRegexpOpen = false;
  3282. }
  3283. }
  3284. }
  3285. } else if (isRelativePseudoClassNode(bufferNode)) {
  3286. // add SelectorList to children of RelativePseudoClass node
  3287. initRelativeSubtree(context, tokenValue);
  3288. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  3289. // besides of creating the relative subtree
  3290. // opening square bracket means start of attribute
  3291. // e.g. 'div:not([class="content"])'
  3292. // 'div:not([href*="window.print()"])'
  3293. context.isAttributeBracketsOpen = true;
  3294. }
  3295. } else if (isSelectorNode(bufferNode)) {
  3296. // after the extended pseudo closing parentheses
  3297. // parser position is on Selector node
  3298. // and regular selector can be after the extended one
  3299. // e.g. '.banner:upward(2)> .block'
  3300. // or '.inner:nth-ancestor(1)~ .banner'
  3301. if (COMBINATORS.includes(tokenValue)) {
  3302. addAstNodeByType(
  3303. context,
  3304. NODE.REGULAR_SELECTOR,
  3305. tokenValue
  3306. );
  3307. } else if (!context.isRegexpOpen) {
  3308. // it might be complex selector with extended pseudo-class inside it.
  3309. // parser position is on `.` now:
  3310. // e.g. 'div:has(img).banner'
  3311. // so we need to get last regular selector node and update its value
  3312. bufferNode = getContextLastRegularSelectorNode(context);
  3313. updateBufferNode(context, tokenValue);
  3314. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  3315. // handle attribute in compound selector after extended pseudo-class
  3316. // e.g. 'div:not(.top)[style="z-index: 10000;"]'
  3317. // parser position ↑
  3318. context.isAttributeBracketsOpen = true;
  3319. }
  3320. }
  3321. } else if (isSelectorListNode(bufferNode)) {
  3322. // add Selector to SelectorList
  3323. addAstNodeByType(context, NODE.SELECTOR); // and RegularSelector as it is always the first child of Selector
  3324. addAstNodeByType(context, NODE.REGULAR_SELECTOR, tokenValue);
  3325. if (isAttributeOpening(tokenValue, prevTokenValue)) {
  3326. // handle simple attribute selector in selector list
  3327. // e.g. '.banner, [class^="ad-"]'
  3328. context.isAttributeBracketsOpen = true;
  3329. }
  3330. }
  3331. break;
  3332. case BRACKET.SQUARE.RIGHT:
  3333. if (isRegularSelectorNode(bufferNode)) {
  3334. // unescaped `]` in regular selector allowed only inside attribute value
  3335. if (
  3336. !context.isAttributeBracketsOpen &&
  3337. prevTokenValue !== BACKSLASH
  3338. ) {
  3339. // e.g. 'div]'
  3340. // eslint-disable-next-line max-len
  3341. throw new Error(
  3342. `'${selector}' is not a valid selector due to '${tokenValue}' after '${getNodeValue(
  3343. bufferNode
  3344. )}'`
  3345. );
  3346. } // needed for proper parsing regular selectors after the attributes with comma
  3347. // e.g. 'div[data-comma="0,1"] > img'
  3348. if (isAttributeClosing(context)) {
  3349. context.isAttributeBracketsOpen = false; // reset attribute buffer on closing `]`
  3350. context.attributeBuffer = "";
  3351. } // collect the bracket to the value of RegularSelector node
  3352. updateBufferNode(context, tokenValue);
  3353. }
  3354. if (isAbsolutePseudoClassNode(bufferNode)) {
  3355. // :xpath() expended pseudo-class arg might contain square bracket
  3356. // so it should be collected
  3357. // e.g. 'div:xpath(//h3[contains(text(),"Share it!")]/..)'
  3358. updateBufferNode(context, tokenValue);
  3359. }
  3360. break;
  3361. case COLON:
  3362. // No white space is allowed between the colon and the following name of the pseudo-class
  3363. // https://www.w3.org/TR/selectors-4/#pseudo-classes
  3364. // e.g. 'span: contains(text)'
  3365. if (
  3366. isWhiteSpaceChar(nextTokenValue) &&
  3367. nextToNextTokenValue &&
  3368. SUPPORTED_PSEUDO_CLASSES.includes(nextToNextTokenValue)
  3369. ) {
  3370. throw new Error(
  3371. `${NO_WHITESPACE_ERROR_PREFIX}: '${selector}'`
  3372. );
  3373. }
  3374. if (bufferNode === null) {
  3375. // no ast collecting has been started
  3376. if (nextTokenValue === XPATH_PSEUDO_CLASS_MARKER) {
  3377. // limit applying of "naked" :xpath pseudo-class
  3378. // https://github.com/AdguardTeam/ExtendedCss/issues/115
  3379. initAst(context, XPATH_PSEUDO_SELECTING_ROOT);
  3380. } else if (
  3381. nextTokenValue === UPWARD_PSEUDO_CLASS_MARKER ||
  3382. nextTokenValue === NTH_ANCESTOR_PSEUDO_CLASS_MARKER
  3383. ) {
  3384. // selector should be specified before :nth-ancestor() or :upward()
  3385. // e.g. ':nth-ancestor(3)'
  3386. // or ':upward(span)'
  3387. throw new Error(
  3388. `${NO_SELECTOR_ERROR_PREFIX} before :${nextTokenValue}() pseudo-class`
  3389. );
  3390. } else {
  3391. // make it more obvious if selector starts with pseudo with no tag specified
  3392. // e.g. ':has(a)' -> '*:has(a)'
  3393. // or ':empty' -> '*:empty'
  3394. initAst(context, ASTERISK);
  3395. } // bufferNode should be updated for following checking
  3396. bufferNode = getBufferNode(context);
  3397. }
  3398. if (isSelectorListNode(bufferNode)) {
  3399. // bufferNode is SelectorList after comma has been parsed.
  3400. // parser position is on colon now:
  3401. // e.g. 'img,:not(.content)'
  3402. addAstNodeByType(context, NODE.SELECTOR); // add empty value RegularSelector anyway as any selector should start with it
  3403. // and check previous token on the next step
  3404. addAstNodeByType(context, NODE.REGULAR_SELECTOR); // bufferNode should be updated for following checking
  3405. bufferNode = getBufferNode(context);
  3406. }
  3407. if (isRegularSelectorNode(bufferNode)) {
  3408. // it can be extended or standard pseudo
  3409. // e.g. '#share, :contains(share it)'
  3410. // or 'div,:hover'
  3411. // of 'div:has(+:contains(text))' // position is after '+'
  3412. if (
  3413. (prevTokenValue && COMBINATORS.includes(prevTokenValue)) ||
  3414. prevTokenValue === COMMA
  3415. ) {
  3416. // case with colon at the start of string - e.g. ':contains(text)'
  3417. // is covered by 'bufferNode === null' above at start of COLON checking
  3418. updateBufferNode(context, ASTERISK);
  3419. }
  3420. handleNextTokenOnColon(
  3421. context,
  3422. selector,
  3423. tokenValue,
  3424. nextTokenValue,
  3425. nextToNextTokenValue
  3426. );
  3427. }
  3428. if (isSelectorNode(bufferNode)) {
  3429. // e.g. 'div:contains(text):'
  3430. if (!nextTokenValue) {
  3431. throw new Error(
  3432. `Invalid colon ':' at the end of selector: '${selector}'`
  3433. );
  3434. } // after the extended pseudo closing parentheses
  3435. // parser position is on Selector node
  3436. // and there is might be another extended selector.
  3437. // parser position is on colon before 'upward':
  3438. // e.g. 'p:contains(PR):upward(2)'
  3439. if (isSupportedPseudoClass(nextTokenValue.toLowerCase())) {
  3440. // if supported extended pseudo-class is next to colon
  3441. // add ExtendedSelector to Selector children
  3442. addAstNodeByType(context, NODE.EXTENDED_SELECTOR);
  3443. } else if (
  3444. nextTokenValue.toLowerCase() === REMOVE_PSEUDO_MARKER
  3445. ) {
  3446. // :remove() pseudo-class should be handled before
  3447. // as it is not about element selecting but actions with elements
  3448. // e.g. '#banner:upward(2):remove()'
  3449. throw new Error(
  3450. `${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`
  3451. );
  3452. } else {
  3453. // otherwise it is standard pseudo after extended pseudo-class in complex selector
  3454. // and colon should be collected to value of previous RegularSelector
  3455. // e.g. 'body *:not(input)::selection'
  3456. // 'input:matches-css(padding: 10):checked'
  3457. bufferNode = getContextLastRegularSelectorNode(context);
  3458. handleNextTokenOnColon(
  3459. context,
  3460. selector,
  3461. tokenValue,
  3462. nextTokenType,
  3463. nextToNextTokenValue
  3464. );
  3465. }
  3466. }
  3467. if (isAbsolutePseudoClassNode(bufferNode)) {
  3468. // :xpath() pseudo-class should be the last of extended pseudo-classes
  3469. if (
  3470. getNodeName(bufferNode) === XPATH_PSEUDO_CLASS_MARKER &&
  3471. nextTokenValue &&
  3472. SUPPORTED_PSEUDO_CLASSES.includes(nextTokenValue) &&
  3473. nextToNextTokenValue === BRACKET.PARENTHESES.LEFT
  3474. ) {
  3475. throw new Error(
  3476. `:xpath() pseudo-class should be the last in selector: '${selector}'`
  3477. );
  3478. } // collecting arg for absolute pseudo-class
  3479. // e.g. 'div:matches-css(width:400px)'
  3480. updateBufferNode(context, tokenValue);
  3481. }
  3482. if (isRelativePseudoClassNode(bufferNode)) {
  3483. if (!nextTokenValue) {
  3484. // e.g. 'div:has(:'
  3485. throw new Error(
  3486. `Invalid pseudo-class arg at the end of selector: '${selector}'`
  3487. );
  3488. } // make it more obvious if selector starts with pseudo with no tag specified
  3489. // parser position is on colon inside :has() arg
  3490. // e.g. 'div:has(:contains(text))'
  3491. // or 'div:not(:empty)'
  3492. initRelativeSubtree(context, ASTERISK);
  3493. if (!isSupportedPseudoClass(nextTokenValue.toLowerCase())) {
  3494. // collect the colon to value of RegularSelector
  3495. // e.g. 'div:not(:empty)'
  3496. updateBufferNode(context, tokenValue); // parentheses should be balanced only for functional pseudo-classes
  3497. // e.g. '.yellow:not(:nth-child(3))'
  3498. if (nextToNextTokenValue === BRACKET.PARENTHESES.LEFT) {
  3499. context.standardPseudoNamesStack.push(nextTokenValue);
  3500. }
  3501. } else {
  3502. // add ExtendedSelector to Selector children
  3503. // e.g. 'div:has(:contains(text))'
  3504. upToClosest(context, NODE.SELECTOR);
  3505. addAstNodeByType(context, NODE.EXTENDED_SELECTOR);
  3506. }
  3507. }
  3508. break;
  3509. case BRACKET.PARENTHESES.LEFT:
  3510. // start of pseudo-class arg
  3511. if (isAbsolutePseudoClassNode(bufferNode)) {
  3512. // no brackets balancing needed inside
  3513. // 1. :xpath() extended pseudo-class arg
  3514. // 2. regexp arg for other extended pseudo-classes
  3515. if (
  3516. getNodeName(bufferNode) !== XPATH_PSEUDO_CLASS_MARKER &&
  3517. context.isRegexpOpen
  3518. ) {
  3519. // if the parentheses is escaped it should be part of regexp
  3520. // collect it to arg of AbsolutePseudoClass
  3521. // e.g. 'div:matches-css(background-image: /^url\\("data:image\\/gif;base64.+/)'
  3522. updateBufferNode(context, tokenValue);
  3523. } else {
  3524. // otherwise brackets should be balanced
  3525. // e.g. 'div:xpath(//h3[contains(text(),"Share it!")]/..)'
  3526. context.extendedPseudoBracketsStack.push(tokenValue); // eslint-disable-next-line max-len
  3527. if (
  3528. context.extendedPseudoBracketsStack.length >
  3529. context.extendedPseudoNamesStack.length
  3530. ) {
  3531. updateBufferNode(context, tokenValue);
  3532. }
  3533. }
  3534. }
  3535. if (isRegularSelectorNode(bufferNode)) {
  3536. // continue RegularSelector value collecting for standard pseudo-classes
  3537. // e.g. '.banner:where(div)'
  3538. if (context.standardPseudoNamesStack.length > 0) {
  3539. updateBufferNode(context, tokenValue);
  3540. context.standardPseudoBracketsStack.push(tokenValue);
  3541. } // parentheses inside attribute value should be part of RegularSelector value
  3542. // e.g. 'div:not([href*="window.print()"])' <-- parser position
  3543. // is on the `(` after `print` ↑
  3544. if (context.isAttributeBracketsOpen) {
  3545. updateBufferNode(context, tokenValue);
  3546. }
  3547. }
  3548. if (isRelativePseudoClassNode(bufferNode)) {
  3549. // save opening bracket for balancing
  3550. // e.g. 'div:not()' // position is on `(`
  3551. context.extendedPseudoBracketsStack.push(tokenValue);
  3552. }
  3553. break;
  3554. case BRACKET.PARENTHESES.RIGHT:
  3555. if (isAbsolutePseudoClassNode(bufferNode)) {
  3556. // no brackets balancing needed inside
  3557. // 1. :xpath() extended pseudo-class arg
  3558. // 2. regexp arg for other extended pseudo-classes
  3559. if (
  3560. getNodeName(bufferNode) !== XPATH_PSEUDO_CLASS_MARKER &&
  3561. context.isRegexpOpen
  3562. ) {
  3563. // if closing bracket is part of regexp
  3564. // simply save it to pseudo-class arg
  3565. updateBufferNode(context, tokenValue);
  3566. } else {
  3567. // remove stacked open parentheses for brackets balance
  3568. // e.g. 'h3:contains((Ads))'
  3569. // or 'div:xpath(//h3[contains(text(),"Share it!")]/..)'
  3570. context.extendedPseudoBracketsStack.pop();
  3571. if (getNodeName(bufferNode) !== XPATH_PSEUDO_CLASS_MARKER) {
  3572. // for all other absolute pseudo-classes except :xpath()
  3573. // remove stacked name of extended pseudo-class
  3574. context.extendedPseudoNamesStack.pop(); // eslint-disable-next-line max-len
  3575. if (
  3576. context.extendedPseudoBracketsStack.length >
  3577. context.extendedPseudoNamesStack.length
  3578. ) {
  3579. // if brackets stack is not empty yet,
  3580. // save tokenValue to arg of AbsolutePseudoClass
  3581. // parser position on first closing bracket after 'Ads':
  3582. // e.g. 'h3:contains((Ads))'
  3583. updateBufferNode(context, tokenValue);
  3584. } else if (
  3585. context.extendedPseudoBracketsStack.length >= 0 &&
  3586. context.extendedPseudoNamesStack.length >= 0
  3587. ) {
  3588. // assume it is combined extended pseudo-classes
  3589. // parser position on first closing bracket after 'advert':
  3590. // e.g. 'div:has(.banner, :contains(advert))'
  3591. upToClosest(context, NODE.SELECTOR);
  3592. }
  3593. } else {
  3594. // for :xpath()
  3595. // eslint-disable-next-line max-len
  3596. if (
  3597. context.extendedPseudoBracketsStack.length <
  3598. context.extendedPseudoNamesStack.length
  3599. ) {
  3600. // remove stacked name of extended pseudo-class
  3601. // if there are less brackets than pseudo-class names
  3602. // with means last removes bracket was closing for pseudo-class
  3603. context.extendedPseudoNamesStack.pop();
  3604. } else {
  3605. // otherwise the bracket is part of arg
  3606. updateBufferNode(context, tokenValue);
  3607. }
  3608. }
  3609. }
  3610. }
  3611. if (isRegularSelectorNode(bufferNode)) {
  3612. if (context.isAttributeBracketsOpen) {
  3613. // parentheses inside attribute value should be part of RegularSelector value
  3614. // e.g. 'div:not([href*="window.print()"])' <-- parser position
  3615. // is on the `)` after `print(` ↑
  3616. updateBufferNode(context, tokenValue);
  3617. } else if (
  3618. context.standardPseudoNamesStack.length > 0 &&
  3619. context.standardPseudoBracketsStack.length > 0
  3620. ) {
  3621. // standard pseudo-class was processing.
  3622. // collect the closing bracket to value of RegularSelector
  3623. // parser position is on bracket after 'class' now:
  3624. // e.g. 'div:where(.class)'
  3625. updateBufferNode(context, tokenValue); // remove bracket and pseudo name from stacks
  3626. context.standardPseudoBracketsStack.pop();
  3627. const lastStandardPseudo =
  3628. context.standardPseudoNamesStack.pop();
  3629. if (!lastStandardPseudo) {
  3630. // standard pseudo should be in standardPseudoNamesStack
  3631. // as related to standardPseudoBracketsStack
  3632. throw new Error(
  3633. `Parsing error. Invalid selector: ${selector}`
  3634. );
  3635. } // Disallow :has() after regular pseudo-elements
  3636. // https://bugs.chromium.org/p/chromium/issues/detail?id=669058#c54 [3]
  3637. if (
  3638. Object.values(REGULAR_PSEUDO_ELEMENTS).includes(
  3639. lastStandardPseudo
  3640. ) && // check token which is next to closing parentheses and token after it
  3641. // parser position is on bracket after 'foo' now:
  3642. // e.g. '::part(foo):has(.a)'
  3643. nextTokenValue === COLON &&
  3644. nextToNextTokenValue &&
  3645. HAS_PSEUDO_CLASS_MARKERS.includes(nextToNextTokenValue)
  3646. ) {
  3647. // eslint-disable-next-line max-len
  3648. throw new Error(
  3649. `Usage of :${nextToNextTokenValue}() pseudo-class is not allowed after any regular pseudo-element: '${lastStandardPseudo}'`
  3650. );
  3651. }
  3652. } else {
  3653. // extended pseudo-class was processing.
  3654. // e.g. 'div:has(h3)'
  3655. // remove bracket and pseudo name from stacks
  3656. context.extendedPseudoBracketsStack.pop();
  3657. context.extendedPseudoNamesStack.pop();
  3658. upToClosest(context, NODE.EXTENDED_SELECTOR); // go to upper selector for possible selector continuation after extended pseudo-class
  3659. // e.g. 'div:has(h3) > img'
  3660. upToClosest(context, NODE.SELECTOR);
  3661. }
  3662. }
  3663. if (isSelectorNode(bufferNode)) {
  3664. // after inner extended pseudo-class bufferNode is Selector.
  3665. // parser position is on last bracket now:
  3666. // e.g. 'div:has(.banner, :contains(ads))'
  3667. context.extendedPseudoBracketsStack.pop();
  3668. context.extendedPseudoNamesStack.pop();
  3669. upToClosest(context, NODE.EXTENDED_SELECTOR);
  3670. upToClosest(context, NODE.SELECTOR);
  3671. }
  3672. if (isRelativePseudoClassNode(bufferNode)) {
  3673. // save opening bracket for balancing
  3674. // e.g. 'div:not()' // position is on `)`
  3675. // context.extendedPseudoBracketsStack.push(tokenValue);
  3676. if (
  3677. context.extendedPseudoNamesStack.length > 0 &&
  3678. context.extendedPseudoBracketsStack.length > 0
  3679. ) {
  3680. context.extendedPseudoBracketsStack.pop();
  3681. context.extendedPseudoNamesStack.pop();
  3682. }
  3683. }
  3684. break;
  3685. case LINE_FEED:
  3686. case FORM_FEED:
  3687. case CARRIAGE_RETURN:
  3688. // such characters at start and end of selector should be trimmed
  3689. // so is there is one them among tokens, it is not valid selector
  3690. throw new Error(`'${selector}' is not a valid selector`);
  3691. case TAB:
  3692. // allow tab only inside attribute value
  3693. // as there are such valid rules in filter lists
  3694. // e.g. 'div[style^="margin-right: auto; text-align: left;',
  3695. // parser position ↑
  3696. if (
  3697. isRegularSelectorNode(bufferNode) &&
  3698. context.isAttributeBracketsOpen
  3699. ) {
  3700. updateBufferNode(context, tokenValue);
  3701. } else {
  3702. // otherwise not valid
  3703. throw new Error(`'${selector}' is not a valid selector`);
  3704. }
  3705. }
  3706. break;
  3707. // no default statement for Marks as they are limited to SUPPORTED_SELECTOR_MARKS
  3708. // and all other symbol combinations are tokenized as Word
  3709. // so error for invalid Word will be thrown later while element selecting by parsed ast
  3710. default:
  3711. throw new Error(`Unknown type of token: '${tokenValue}'`);
  3712. }
  3713. i += 1;
  3714. }
  3715. if (context.ast === null) {
  3716. throw new Error(`'${selector}' is not a valid selector`);
  3717. }
  3718. if (
  3719. context.extendedPseudoNamesStack.length > 0 ||
  3720. context.extendedPseudoBracketsStack.length > 0
  3721. ) {
  3722. // eslint-disable-next-line max-len
  3723. throw new Error(
  3724. `Unbalanced brackets for extended pseudo-class: '${getLast(
  3725. context.extendedPseudoNamesStack
  3726. )}'`
  3727. );
  3728. }
  3729. if (context.isAttributeBracketsOpen) {
  3730. throw new Error(
  3731. `Unbalanced attribute brackets in selector: '${selector}'`
  3732. );
  3733. }
  3734. return context.shouldOptimize ? optimizeAst(context.ast) : context.ast;
  3735. };
  3736. const natives = {
  3737. MutationObserver:
  3738. window.MutationObserver || window.WebKitMutationObserver,
  3739. };
  3740. /**
  3741. * Class NativeTextContent is needed to intercept and save the native Node textContent getter
  3742. * for proper work of :contains() pseudo-class as it may be mocked.
  3743. *
  3744. * @see {@link https://github.com/AdguardTeam/ExtendedCss/issues/127}
  3745. */
  3746. class NativeTextContent {
  3747. /**
  3748. * Native Node.
  3749. */
  3750. /**
  3751. * Native Node textContent getter.
  3752. */
  3753. /**
  3754. * Stores native node.
  3755. */
  3756. constructor() {
  3757. this.nativeNode = window.Node || Node;
  3758. }
  3759. /**
  3760. * Sets native Node textContext getter to `getter` class field.
  3761. */
  3762. setGetter() {
  3763. var _Object$getOwnPropert;
  3764. this.getter =
  3765. (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(
  3766. this.nativeNode.prototype,
  3767. "textContent"
  3768. )) === null || _Object$getOwnPropert === void 0
  3769. ? void 0
  3770. : _Object$getOwnPropert.get;
  3771. }
  3772. }
  3773. const nativeTextContent = new NativeTextContent();
  3774. /**
  3775. * Returns textContent of passed domElement.
  3776. *
  3777. * @param domElement DOM element.
  3778. *
  3779. * @returns DOM element textContent.
  3780. */
  3781. const getNodeTextContent = (domElement) => {
  3782. if (nativeTextContent.getter) {
  3783. return nativeTextContent.getter.apply(domElement);
  3784. } // if ExtendedCss.init() has not been executed and there is no nodeTextContentGetter,
  3785. // use simple approach, especially when init() is not really needed, e.g. local tests
  3786. return domElement.textContent || "";
  3787. };
  3788. /**
  3789. * Returns element selector text based on it's tagName and attributes.
  3790. *
  3791. * @param element DOM element.
  3792. *
  3793. * @returns String representation of `element`.
  3794. */
  3795. const getElementSelectorDesc = (element) => {
  3796. let selectorText = element.tagName.toLowerCase();
  3797. selectorText += Array.from(element.attributes)
  3798. .map((attr) => {
  3799. return `[${attr.name}="${element.getAttribute(attr.name)}"]`;
  3800. })
  3801. .join("");
  3802. return selectorText;
  3803. };
  3804. /**
  3805. * Returns path to a DOM element as a selector string.
  3806. *
  3807. * @param inputEl Input element.
  3808. *
  3809. * @returns String path to a DOM element.
  3810. * @throws An error if `inputEl` in not instance of `Element`.
  3811. */
  3812. const getElementSelectorPath = (inputEl) => {
  3813. if (!(inputEl instanceof Element)) {
  3814. throw new Error("Function received argument with wrong type");
  3815. }
  3816. let el;
  3817. el = inputEl;
  3818. const path = []; // we need to check '!!el' first because it is possible
  3819. // that some ancestor of the inputEl was removed before it
  3820. while (!!el && el.nodeType === Node.ELEMENT_NODE) {
  3821. let selector = el.nodeName.toLowerCase();
  3822. if (el.id && typeof el.id === "string") {
  3823. selector += `#${el.id}`;
  3824. path.unshift(selector);
  3825. break;
  3826. }
  3827. let sibling = el;
  3828. let nth = 1;
  3829. while (sibling.previousElementSibling) {
  3830. sibling = sibling.previousElementSibling;
  3831. if (
  3832. sibling.nodeType === Node.ELEMENT_NODE &&
  3833. sibling.nodeName.toLowerCase() === selector
  3834. ) {
  3835. nth += 1;
  3836. }
  3837. }
  3838. if (nth !== 1) {
  3839. selector += `:nth-of-type(${nth})`;
  3840. }
  3841. path.unshift(selector);
  3842. el = el.parentElement;
  3843. }
  3844. return path.join(" > ");
  3845. };
  3846. /**
  3847. * Checks whether the element is instance of HTMLElement.
  3848. *
  3849. * @param element Element to check.
  3850. *
  3851. * @returns True if `element` is HTMLElement.
  3852. */
  3853. const isHtmlElement = (element) => {
  3854. return element instanceof HTMLElement;
  3855. };
  3856. /**
  3857. * Takes `element` and returns its parent element.
  3858. *
  3859. * @param element Element.
  3860. * @param errorMessage Optional error message to throw.
  3861. *
  3862. * @returns Parent of `element`.
  3863. * @throws An error if element has no parent element.
  3864. */
  3865. const getParent = (element, errorMessage) => {
  3866. const { parentElement } = element;
  3867. if (!parentElement) {
  3868. throw new Error(errorMessage || "Element does no have parent element");
  3869. }
  3870. return parentElement;
  3871. };
  3872. /**
  3873. * Checks whether the `error` has `message` property which type is string.
  3874. *
  3875. * @param error Error object.
  3876. *
  3877. * @returns True if `error` has message.
  3878. */
  3879. const isErrorWithMessage = (error) => {
  3880. return (
  3881. typeof error === "object" &&
  3882. error !== null &&
  3883. "message" in error &&
  3884. typeof error.message === "string"
  3885. );
  3886. };
  3887. /**
  3888. * Converts `maybeError` to error object with message.
  3889. *
  3890. * @param maybeError Possible error.
  3891. *
  3892. * @returns Error object with defined `message` property.
  3893. */
  3894. const toErrorWithMessage = (maybeError) => {
  3895. if (isErrorWithMessage(maybeError)) {
  3896. return maybeError;
  3897. }
  3898. try {
  3899. return new Error(JSON.stringify(maybeError));
  3900. } catch {
  3901. // fallback in case if there is an error happened during the maybeError stringifying
  3902. // like with circular references for example
  3903. return new Error(String(maybeError));
  3904. }
  3905. };
  3906. /**
  3907. * Returns error message from `error`.
  3908. * May be helpful to handle caught errors.
  3909. *
  3910. * @param error Error object.
  3911. *
  3912. * @returns Message of `error`.
  3913. */
  3914. const getErrorMessage = (error) => {
  3915. return toErrorWithMessage(error).message;
  3916. };
  3917. const logger = {
  3918. /**
  3919. * Safe console.error version.
  3920. */
  3921. error:
  3922. typeof console !== "undefined" && console.error && console.error.bind
  3923. ? console.error.bind(window.console)
  3924. : console.error,
  3925. /**
  3926. * Safe console.info version.
  3927. */
  3928. info:
  3929. typeof console !== "undefined" && console.info && console.info.bind
  3930. ? console.info.bind(window.console)
  3931. : console.info,
  3932. };
  3933. /**
  3934. * Returns string without suffix.
  3935. *
  3936. * @param str Input string.
  3937. * @param suffix Needed to remove.
  3938. *
  3939. * @returns String without suffix.
  3940. */
  3941. const removeSuffix = (str, suffix) => {
  3942. const index = str.indexOf(suffix, str.length - suffix.length);
  3943. if (index >= 0) {
  3944. return str.substring(0, index);
  3945. }
  3946. return str;
  3947. };
  3948. /**
  3949. * Replaces all `pattern`s with `replacement` in `input` string.
  3950. * String.replaceAll() polyfill because it is not supported by old browsers, e.g. Chrome 55.
  3951. *
  3952. * @see {@link https://caniuse.com/?search=String.replaceAll}
  3953. *
  3954. * @param input Input string to process.
  3955. * @param pattern Find in the input string.
  3956. * @param replacement Replace the pattern with.
  3957. *
  3958. * @returns Modified string.
  3959. */
  3960. const replaceAll = (input, pattern, replacement) => {
  3961. if (!input) {
  3962. return input;
  3963. }
  3964. return input.split(pattern).join(replacement);
  3965. };
  3966. /**
  3967. * Converts string pattern to regular expression.
  3968. *
  3969. * @param str String to convert.
  3970. *
  3971. * @returns Regular expression converted from pattern `str`.
  3972. */
  3973. const toRegExp = (str) => {
  3974. if (str.startsWith(SLASH) && str.endsWith(SLASH)) {
  3975. return new RegExp(str.slice(1, -1));
  3976. }
  3977. const escaped = str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  3978. return new RegExp(escaped);
  3979. };
  3980. /**
  3981. * Converts any simple type value to string type,
  3982. * e.g. `undefined` -> `'undefined'`.
  3983. *
  3984. * @param value Any type value.
  3985. *
  3986. * @returns String representation of `value`.
  3987. */
  3988. const convertTypeIntoString = (value) => {
  3989. let output;
  3990. switch (value) {
  3991. case undefined:
  3992. output = "undefined";
  3993. break;
  3994. case null:
  3995. output = "null";
  3996. break;
  3997. default:
  3998. output = value.toString();
  3999. }
  4000. return output;
  4001. };
  4002. /**
  4003. * Converts instance of string value into other simple types,
  4004. * e.g. `'null'` -> `null`, `'true'` -> `true`.
  4005. *
  4006. * @param value String-type value.
  4007. *
  4008. * @returns Its own type representation of string-type `value`.
  4009. */
  4010. const convertTypeFromString = (value) => {
  4011. const numValue = Number(value);
  4012. let output;
  4013. if (!Number.isNaN(numValue)) {
  4014. output = numValue;
  4015. } else {
  4016. switch (value) {
  4017. case "undefined":
  4018. output = undefined;
  4019. break;
  4020. case "null":
  4021. output = null;
  4022. break;
  4023. case "true":
  4024. output = true;
  4025. break;
  4026. case "false":
  4027. output = false;
  4028. break;
  4029. default:
  4030. output = value;
  4031. }
  4032. }
  4033. return output;
  4034. };
  4035. const SAFARI_USER_AGENT_REGEXP =
  4036. /\sVersion\/(\d{2}\.\d)(.+\s|\s)(Safari)\//;
  4037. const isSafariBrowser = SAFARI_USER_AGENT_REGEXP.test(navigator.userAgent);
  4038. /**
  4039. * Checks whether the browser userAgent is supported.
  4040. *
  4041. * @param userAgent User agent of browser.
  4042. *
  4043. * @returns False only for Internet Explorer.
  4044. */
  4045. const isUserAgentSupported = (userAgent) => {
  4046. // do not support Internet Explorer
  4047. if (userAgent.includes("MSIE") || userAgent.includes("Trident/")) {
  4048. return false;
  4049. }
  4050. return true;
  4051. };
  4052. /**
  4053. * Checks whether the current browser is supported.
  4054. *
  4055. * @returns False for Internet Explorer, otherwise true.
  4056. */
  4057. const isBrowserSupported = () => {
  4058. return isUserAgentSupported(navigator.userAgent);
  4059. };
  4060. /**
  4061. * CSS_PROPERTY is needed for style values normalization.
  4062. *
  4063. * IMPORTANT: it is used as 'const' instead of 'enum' to avoid side effects
  4064. * during ExtendedCss import into other libraries.
  4065. */
  4066. const CSS_PROPERTY = {
  4067. BACKGROUND: "background",
  4068. BACKGROUND_IMAGE: "background-image",
  4069. CONTENT: "content",
  4070. OPACITY: "opacity",
  4071. };
  4072. const REGEXP_ANY_SYMBOL = ".*";
  4073. const REGEXP_WITH_FLAGS_REGEXP = /^\s*\/.*\/[gmisuy]*\s*$/;
  4074. /**
  4075. * Removes quotes for specified content value.
  4076. *
  4077. * For example, content style declaration with `::before` can be set as '-' (e.g. unordered list)
  4078. * which displayed as simple dash `-` with no quotes.
  4079. * But CSSStyleDeclaration.getPropertyValue('content') will return value
  4080. * wrapped into quotes, e.g. '"-"', which should be removed
  4081. * because filters maintainers does not use any quotes in real rules.
  4082. *
  4083. * @param str Input string.
  4084. *
  4085. * @returns String with no quotes for content value.
  4086. */
  4087. const removeContentQuotes = (str) => {
  4088. return str.replace(/^(["'])([\s\S]*)\1$/, "$2");
  4089. };
  4090. /**
  4091. * Adds quotes for specified background url value.
  4092. *
  4093. * If background-image is specified **without** quotes:
  4094. * e.g. 'background: url(data:image/gif;base64,R0lGODlhAQA7)'.
  4095. *
  4096. * CSSStyleDeclaration.getPropertyValue('background-image') may return value **with** quotes:
  4097. * e.g. 'background: url("data:image/gif;base64,R0lGODlhAQA7")'.
  4098. *
  4099. * So we add quotes for compatibility since filters maintainers might use quotes in real rules.
  4100. *
  4101. * @param str Input string.
  4102. *
  4103. * @returns String with unified quotes for background url value.
  4104. */
  4105. const addUrlPropertyQuotes = (str) => {
  4106. if (!str.includes('url("')) {
  4107. const re = /url\((.*?)\)/g;
  4108. return str.replace(re, 'url("$1")');
  4109. }
  4110. return str;
  4111. };
  4112. /**
  4113. * Adds quotes to url arg for consistent property value matching.
  4114. */
  4115. const addUrlQuotesTo = {
  4116. regexpArg: (str) => {
  4117. // e.g. /^url\\([a-z]{4}:[a-z]{5}/
  4118. // or /^url\\(data\\:\\image\\/gif;base64.+/
  4119. const re = /(\^)?url(\\)?\\\((\w|\[\w)/g;
  4120. return str.replace(re, '$1url$2\\(\\"?$3');
  4121. },
  4122. noneRegexpArg: addUrlPropertyQuotes,
  4123. };
  4124. /**
  4125. * Escapes regular expression string.
  4126. *
  4127. * @see {@link https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp}
  4128. *
  4129. * @param str Input string.
  4130. *
  4131. * @returns Escaped regular expression string.
  4132. */
  4133. const escapeRegExp = (str) => {
  4134. // should be escaped . * + ? ^ $ { } ( ) | [ ] / \
  4135. // except of * | ^
  4136. const specials = [
  4137. ".",
  4138. "+",
  4139. "?",
  4140. "$",
  4141. "{",
  4142. "}",
  4143. "(",
  4144. ")",
  4145. "[",
  4146. "]",
  4147. "\\",
  4148. "/",
  4149. ];
  4150. const specialsRegex = new RegExp(`[${specials.join("\\")}]`, "g");
  4151. return str.replace(specialsRegex, "\\$&");
  4152. };
  4153. /**
  4154. * Converts :matches-css() arg property value match to regexp.
  4155. *
  4156. * @param rawValue Style match value pattern.
  4157. *
  4158. * @returns Arg of :matches-css() converted to regular expression.
  4159. */
  4160. const convertStyleMatchValueToRegexp = (rawValue) => {
  4161. let value;
  4162. if (rawValue.startsWith(SLASH) && rawValue.endsWith(SLASH)) {
  4163. // For regex patterns double quotes `"` and backslashes `\` should be escaped
  4164. value = addUrlQuotesTo.regexpArg(rawValue);
  4165. value = value.slice(1, -1);
  4166. } else {
  4167. // For non-regex patterns parentheses `(` `)` and square brackets `[` `]`
  4168. // should be unescaped, because their escaping in filter rules is required
  4169. value = addUrlQuotesTo.noneRegexpArg(rawValue);
  4170. value = value.replace(/\\([\\()[\]"])/g, "$1");
  4171. value = escapeRegExp(value); // e.g. div:matches-css(background-image: url(data:*))
  4172. value = replaceAll(value, ASTERISK, REGEXP_ANY_SYMBOL);
  4173. }
  4174. return new RegExp(value, "i");
  4175. };
  4176. /**
  4177. * Makes some properties values compatible.
  4178. *
  4179. * @param propertyName Name of style property.
  4180. * @param propertyValue Value of style property.
  4181. *
  4182. * @returns Normalized values for some CSS properties.
  4183. */
  4184. const normalizePropertyValue = (propertyName, propertyValue) => {
  4185. let normalized = "";
  4186. switch (propertyName) {
  4187. case CSS_PROPERTY.BACKGROUND:
  4188. case CSS_PROPERTY.BACKGROUND_IMAGE:
  4189. // sometimes url property does not have quotes
  4190. // so we add them for consistent matching
  4191. normalized = addUrlPropertyQuotes(propertyValue);
  4192. break;
  4193. case CSS_PROPERTY.CONTENT:
  4194. normalized = removeContentQuotes(propertyValue);
  4195. break;
  4196. case CSS_PROPERTY.OPACITY:
  4197. // https://bugs.webkit.org/show_bug.cgi?id=93445
  4198. normalized = isSafariBrowser
  4199. ? (Math.round(parseFloat(propertyValue) * 100) / 100).toString()
  4200. : propertyValue;
  4201. break;
  4202. default:
  4203. normalized = propertyValue;
  4204. }
  4205. return normalized;
  4206. };
  4207. /**
  4208. * Returns domElement style property value
  4209. * by css property name and standard pseudo-element.
  4210. *
  4211. * @param domElement DOM element.
  4212. * @param propertyName CSS property name.
  4213. * @param regularPseudoElement Standard pseudo-element — '::before', '::after' etc.
  4214. *
  4215. * @returns String containing the value of a specified CSS property.
  4216. */
  4217. const getComputedStylePropertyValue = (
  4218. domElement,
  4219. propertyName,
  4220. regularPseudoElement
  4221. ) => {
  4222. const style = window.getComputedStyle(domElement, regularPseudoElement);
  4223. const propertyValue = style.getPropertyValue(propertyName);
  4224. return normalizePropertyValue(propertyName, propertyValue);
  4225. };
  4226. /**
  4227. * Parses arg of absolute pseudo-class into 'name' and 'value' if set.
  4228. *
  4229. * Used for :matches-css() - with COLON as separator,
  4230. * for :matches-attr() and :matches-property() - with EQUAL_SIGN as separator.
  4231. *
  4232. * @param pseudoArg Arg of pseudo-class.
  4233. * @param separator Divider symbol.
  4234. *
  4235. * @returns Parsed 'matches' pseudo-class arg data.
  4236. */
  4237. const getPseudoArgData = (pseudoArg, separator) => {
  4238. const index = pseudoArg.indexOf(separator);
  4239. let name;
  4240. let value;
  4241. if (index > -1) {
  4242. name = pseudoArg.substring(0, index).trim();
  4243. value = pseudoArg.substring(index + 1).trim();
  4244. } else {
  4245. name = pseudoArg;
  4246. }
  4247. return {
  4248. name,
  4249. value,
  4250. };
  4251. };
  4252. /**
  4253. * Parses :matches-css() pseudo-class arg
  4254. * where regular pseudo-element can be a part of arg
  4255. * e.g. 'div:matches-css(before, color: rgb(255, 255, 255))' <-- obsolete `:matches-css-before()`.
  4256. *
  4257. * @param pseudoName Pseudo-class name.
  4258. * @param rawArg Pseudo-class arg.
  4259. *
  4260. * @returns Parsed :matches-css() pseudo-class arg data.
  4261. * @throws An error on invalid `rawArg`.
  4262. */
  4263. const parseStyleMatchArg = (pseudoName, rawArg) => {
  4264. const { name, value } = getPseudoArgData(rawArg, COMMA);
  4265. let regularPseudoElement = name;
  4266. let styleMatchArg = value; // check whether the string part before the separator is valid regular pseudo-element,
  4267. // otherwise `regularPseudoElement` is null, and `styleMatchArg` is rawArg
  4268. if (!Object.values(REGULAR_PSEUDO_ELEMENTS).includes(name)) {
  4269. regularPseudoElement = null;
  4270. styleMatchArg = rawArg;
  4271. }
  4272. if (!styleMatchArg) {
  4273. throw new Error(
  4274. `Required style property argument part is missing in :${pseudoName}() arg: '${rawArg}'`
  4275. );
  4276. } // if regularPseudoElement is not `null`
  4277. if (regularPseudoElement) {
  4278. // pseudo-element should have two colon marks for Window.getComputedStyle() due to the syntax:
  4279. // https://www.w3.org/TR/selectors-4/#pseudo-element-syntax
  4280. // ':matches-css(before, content: ads)' ->> '::before'
  4281. regularPseudoElement = `${COLON}${COLON}${regularPseudoElement}`;
  4282. }
  4283. return {
  4284. regularPseudoElement,
  4285. styleMatchArg,
  4286. };
  4287. };
  4288. /**
  4289. * Checks whether the domElement is matched by :matches-css() arg.
  4290. *
  4291. * @param argsData Pseudo-class name, arg, and dom element to check.
  4292. *
  4293. @returns True if DOM element is matched.
  4294. * @throws An error on invalid pseudo-class arg.
  4295. */
  4296. const isStyleMatched = (argsData) => {
  4297. const { pseudoName, pseudoArg, domElement } = argsData;
  4298. const { regularPseudoElement, styleMatchArg } = parseStyleMatchArg(
  4299. pseudoName,
  4300. pseudoArg
  4301. );
  4302. const { name: matchName, value: matchValue } = getPseudoArgData(
  4303. styleMatchArg,
  4304. COLON
  4305. );
  4306. if (!matchName || !matchValue) {
  4307. throw new Error(
  4308. `Required property name or value is missing in :${pseudoName}() arg: '${styleMatchArg}'`
  4309. );
  4310. }
  4311. let valueRegexp;
  4312. try {
  4313. valueRegexp = convertStyleMatchValueToRegexp(matchValue);
  4314. } catch (e) {
  4315. logger.error(getErrorMessage(e));
  4316. throw new Error(
  4317. `Invalid argument of :${pseudoName}() pseudo-class: '${styleMatchArg}'`
  4318. );
  4319. }
  4320. const value = getComputedStylePropertyValue(
  4321. domElement,
  4322. matchName,
  4323. regularPseudoElement
  4324. );
  4325. return valueRegexp && valueRegexp.test(value);
  4326. };
  4327. /**
  4328. * Validates string arg for :matches-attr() and :matches-property().
  4329. *
  4330. * @param arg Pseudo-class arg.
  4331. *
  4332. * @returns True if 'matches' pseudo-class string arg is valid.
  4333. */
  4334. const validateStrMatcherArg = (arg) => {
  4335. if (arg.includes(SLASH)) {
  4336. return false;
  4337. }
  4338. if (!/^[\w-]+$/.test(arg)) {
  4339. return false;
  4340. }
  4341. return true;
  4342. };
  4343. /**
  4344. * Returns valid arg for :matches-attr() and :matcher-property().
  4345. *
  4346. * @param rawArg Arg pattern.
  4347. * @param [isWildcardAllowed=false] Flag for wildcard (`*`) using as pseudo-class arg.
  4348. *
  4349. * @returns Valid arg for :matches-attr() and :matcher-property().
  4350. * @throws An error on invalid `rawArg`.
  4351. */
  4352. const getValidMatcherArg = function (rawArg) {
  4353. let isWildcardAllowed =
  4354. arguments.length > 1 && arguments[1] !== undefined
  4355. ? arguments[1]
  4356. : false;
  4357. // if rawArg is missing for pseudo-class
  4358. // e.g. :matches-attr()
  4359. // error will be thrown before getValidMatcherArg() is called:
  4360. // name or arg is missing in AbsolutePseudoClass
  4361. let arg;
  4362. if (
  4363. rawArg.length > 1 &&
  4364. rawArg.startsWith(DOUBLE_QUOTE) &&
  4365. rawArg.endsWith(DOUBLE_QUOTE)
  4366. ) {
  4367. rawArg = rawArg.slice(1, -1);
  4368. }
  4369. if (rawArg === "") {
  4370. // e.g. :matches-property("")
  4371. throw new Error("Argument should be specified. Empty arg is invalid.");
  4372. }
  4373. if (rawArg.startsWith(SLASH) && rawArg.endsWith(SLASH)) {
  4374. // e.g. :matches-property("//")
  4375. if (rawArg.length > 2) {
  4376. arg = toRegExp(rawArg);
  4377. } else {
  4378. throw new Error(`Invalid regexp: '${rawArg}'`);
  4379. }
  4380. } else if (rawArg.includes(ASTERISK)) {
  4381. if (rawArg === ASTERISK && !isWildcardAllowed) {
  4382. // e.g. :matches-attr(*)
  4383. throw new Error(`Argument should be more specific than ${rawArg}`);
  4384. }
  4385. arg = replaceAll(rawArg, ASTERISK, REGEXP_ANY_SYMBOL);
  4386. arg = new RegExp(arg);
  4387. } else {
  4388. if (!validateStrMatcherArg(rawArg)) {
  4389. throw new Error(`Invalid argument: '${rawArg}'`);
  4390. }
  4391. arg = rawArg;
  4392. }
  4393. return arg;
  4394. };
  4395. /**
  4396. * Parses pseudo-class argument and returns parsed data.
  4397. *
  4398. * @param pseudoName Extended pseudo-class name.
  4399. * @param pseudoArg Extended pseudo-class argument.
  4400. *
  4401. * @returns Parsed pseudo-class argument data.
  4402. * @throws An error if attribute name is missing in pseudo-class arg.
  4403. */
  4404. const getRawMatchingData = (pseudoName, pseudoArg) => {
  4405. const { name: rawName, value: rawValue } = getPseudoArgData(
  4406. pseudoArg,
  4407. EQUAL_SIGN
  4408. );
  4409. if (!rawName) {
  4410. throw new Error(
  4411. `Required attribute name is missing in :${pseudoName} arg: ${pseudoArg}`
  4412. );
  4413. }
  4414. return {
  4415. rawName,
  4416. rawValue,
  4417. };
  4418. };
  4419. /**
  4420. * Checks whether the domElement is matched by :matches-attr() arg.
  4421. *
  4422. * @param argsData Pseudo-class name, arg, and dom element to check.
  4423. *
  4424. @returns True if DOM element is matched.
  4425. * @throws An error on invalid arg of pseudo-class.
  4426. */
  4427. const isAttributeMatched = (argsData) => {
  4428. const { pseudoName, pseudoArg, domElement } = argsData;
  4429. const elementAttributes = domElement.attributes; // no match if dom element has no attributes
  4430. if (elementAttributes.length === 0) {
  4431. return false;
  4432. }
  4433. const { rawName: rawAttrName, rawValue: rawAttrValue } =
  4434. getRawMatchingData(pseudoName, pseudoArg);
  4435. let attrNameMatch;
  4436. try {
  4437. attrNameMatch = getValidMatcherArg(rawAttrName);
  4438. } catch (e) {
  4439. const errorMessage = getErrorMessage(e);
  4440. logger.error(errorMessage);
  4441. throw new SyntaxError(errorMessage);
  4442. }
  4443. let isMatched = false;
  4444. let i = 0;
  4445. while (i < elementAttributes.length && !isMatched) {
  4446. const attr = elementAttributes[i];
  4447. if (!attr) {
  4448. break;
  4449. }
  4450. const isNameMatched =
  4451. attrNameMatch instanceof RegExp
  4452. ? attrNameMatch.test(attr.name)
  4453. : attrNameMatch === attr.name;
  4454. if (!rawAttrValue) {
  4455. // for rules with no attribute value specified
  4456. // e.g. :matches-attr("/regex/") or :matches-attr("attr-name")
  4457. isMatched = isNameMatched;
  4458. } else {
  4459. let attrValueMatch;
  4460. try {
  4461. attrValueMatch = getValidMatcherArg(rawAttrValue);
  4462. } catch (e) {
  4463. const errorMessage = getErrorMessage(e);
  4464. logger.error(errorMessage);
  4465. throw new SyntaxError(errorMessage);
  4466. }
  4467. const isValueMatched =
  4468. attrValueMatch instanceof RegExp
  4469. ? attrValueMatch.test(attr.value)
  4470. : attrValueMatch === attr.value;
  4471. isMatched = isNameMatched && isValueMatched;
  4472. }
  4473. i += 1;
  4474. }
  4475. return isMatched;
  4476. };
  4477. /**
  4478. * Parses raw :matches-property() arg which may be chain of properties.
  4479. *
  4480. * @param input Argument of :matches-property().
  4481. *
  4482. * @returns Arg of :matches-property() as array of strings or regular expressions.
  4483. * @throws An error on invalid chain.
  4484. */
  4485. const parseRawPropChain = (input) => {
  4486. if (
  4487. input.length > 1 &&
  4488. input.startsWith(DOUBLE_QUOTE) &&
  4489. input.endsWith(DOUBLE_QUOTE)
  4490. ) {
  4491. input = input.slice(1, -1);
  4492. }
  4493. const chainChunks = input.split(DOT);
  4494. const chainPatterns = [];
  4495. let patternBuffer = "";
  4496. let isRegexpPattern = false;
  4497. let i = 0;
  4498. while (i < chainChunks.length) {
  4499. const chunk = getItemByIndex(
  4500. chainChunks,
  4501. i,
  4502. `Invalid pseudo-class arg: '${input}'`
  4503. );
  4504. if (
  4505. chunk.startsWith(SLASH) &&
  4506. chunk.endsWith(SLASH) &&
  4507. chunk.length > 2
  4508. ) {
  4509. // regexp pattern with no dot in it, e.g. /propName/
  4510. chainPatterns.push(chunk);
  4511. } else if (chunk.startsWith(SLASH)) {
  4512. // if chunk is a start of regexp pattern
  4513. isRegexpPattern = true;
  4514. patternBuffer += chunk;
  4515. } else if (chunk.endsWith(SLASH)) {
  4516. isRegexpPattern = false; // restore dot removed while splitting
  4517. // e.g. testProp./.{1,5}/
  4518. patternBuffer += `.${chunk}`;
  4519. chainPatterns.push(patternBuffer);
  4520. patternBuffer = "";
  4521. } else {
  4522. // if there are few dots in regexp pattern
  4523. // so chunk might be in the middle of it
  4524. if (isRegexpPattern) {
  4525. patternBuffer += chunk;
  4526. } else {
  4527. // otherwise it is string pattern
  4528. chainPatterns.push(chunk);
  4529. }
  4530. }
  4531. i += 1;
  4532. }
  4533. if (patternBuffer.length > 0) {
  4534. throw new Error(`Invalid regexp property pattern '${input}'`);
  4535. }
  4536. const chainMatchPatterns = chainPatterns.map((pattern) => {
  4537. if (pattern.length === 0) {
  4538. // e.g. '.prop.id' or 'nested..test'
  4539. throw new Error(
  4540. `Empty pattern '${pattern}' is invalid in chain '${input}'`
  4541. );
  4542. }
  4543. let validPattern;
  4544. try {
  4545. validPattern = getValidMatcherArg(pattern, true);
  4546. } catch (e) {
  4547. logger.error(getErrorMessage(e));
  4548. throw new Error(
  4549. `Invalid property pattern '${pattern}' in property chain '${input}'`
  4550. );
  4551. }
  4552. return validPattern;
  4553. });
  4554. return chainMatchPatterns;
  4555. };
  4556. /**
  4557. * Checks if the property exists in the base object (recursively).
  4558. *
  4559. * @param base Element to check.
  4560. * @param chain Array of objects - parsed string property chain.
  4561. * @param [output=[]] Result acc.
  4562. *
  4563. * @returns Array of parsed data — representation of `base`-related `chain`.
  4564. */
  4565. const filterRootsByRegexpChain = function (base, chain) {
  4566. let output =
  4567. arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  4568. const tempProp = getFirst(chain);
  4569. if (chain.length === 1) {
  4570. let key;
  4571. for (key in base) {
  4572. if (tempProp instanceof RegExp) {
  4573. if (tempProp.test(key)) {
  4574. output.push({
  4575. base,
  4576. prop: key,
  4577. value: base[key],
  4578. });
  4579. }
  4580. } else if (tempProp === key) {
  4581. output.push({
  4582. base,
  4583. prop: tempProp,
  4584. value: base[key],
  4585. });
  4586. }
  4587. }
  4588. return output;
  4589. } // if there is a regexp prop in input chain
  4590. // e.g. 'unit./^ad.+/.src' for 'unit.ad-1gf2.src unit.ad-fgd34.src'),
  4591. // every base keys should be tested by regexp and it can be more that one results
  4592. if (tempProp instanceof RegExp) {
  4593. const nextProp = chain.slice(1);
  4594. const baseKeys = [];
  4595. for (const key in base) {
  4596. if (tempProp.test(key)) {
  4597. baseKeys.push(key);
  4598. }
  4599. }
  4600. baseKeys.forEach((key) => {
  4601. var _Object$getOwnPropert;
  4602. const item =
  4603. (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(
  4604. base,
  4605. key
  4606. )) === null || _Object$getOwnPropert === void 0
  4607. ? void 0
  4608. : _Object$getOwnPropert.value;
  4609. filterRootsByRegexpChain(item, nextProp, output);
  4610. });
  4611. }
  4612. if (base && typeof tempProp === "string") {
  4613. var _Object$getOwnPropert2;
  4614. const nextBase =
  4615. (_Object$getOwnPropert2 = Object.getOwnPropertyDescriptor(
  4616. base,
  4617. tempProp
  4618. )) === null || _Object$getOwnPropert2 === void 0
  4619. ? void 0
  4620. : _Object$getOwnPropert2.value;
  4621. chain = chain.slice(1);
  4622. if (nextBase !== undefined) {
  4623. filterRootsByRegexpChain(nextBase, chain, output);
  4624. }
  4625. }
  4626. return output;
  4627. };
  4628. /**
  4629. * Checks whether the domElement is matched by :matches-property() arg.
  4630. *
  4631. * @param argsData Pseudo-class name, arg, and dom element to check.
  4632. *
  4633. @returns True if DOM element is matched.
  4634. * @throws An error on invalid prop in chain.
  4635. */
  4636. const isPropertyMatched = (argsData) => {
  4637. const { pseudoName, pseudoArg, domElement } = argsData;
  4638. const { rawName: rawPropertyName, rawValue: rawPropertyValue } =
  4639. getRawMatchingData(pseudoName, pseudoArg); // chained property name cannot include '/' or '.'
  4640. // so regex prop names with such escaped characters are invalid
  4641. if (rawPropertyName.includes("\\/") || rawPropertyName.includes("\\.")) {
  4642. throw new Error(
  4643. `Invalid :${pseudoName} name pattern: ${rawPropertyName}`
  4644. );
  4645. }
  4646. let propChainMatches;
  4647. try {
  4648. propChainMatches = parseRawPropChain(rawPropertyName);
  4649. } catch (e) {
  4650. const errorMessage = getErrorMessage(e);
  4651. logger.error(errorMessage);
  4652. throw new SyntaxError(errorMessage);
  4653. }
  4654. const ownerObjArr = filterRootsByRegexpChain(
  4655. domElement,
  4656. propChainMatches
  4657. );
  4658. if (ownerObjArr.length === 0) {
  4659. return false;
  4660. }
  4661. let isMatched = true;
  4662. if (rawPropertyValue) {
  4663. let propValueMatch;
  4664. try {
  4665. propValueMatch = getValidMatcherArg(rawPropertyValue);
  4666. } catch (e) {
  4667. const errorMessage = getErrorMessage(e);
  4668. logger.error(errorMessage);
  4669. throw new SyntaxError(errorMessage);
  4670. }
  4671. if (propValueMatch) {
  4672. for (let i = 0; i < ownerObjArr.length; i += 1) {
  4673. var _ownerObjArr$i;
  4674. const realValue =
  4675. (_ownerObjArr$i = ownerObjArr[i]) === null ||
  4676. _ownerObjArr$i === void 0
  4677. ? void 0
  4678. : _ownerObjArr$i.value;
  4679. if (propValueMatch instanceof RegExp) {
  4680. isMatched = propValueMatch.test(convertTypeIntoString(realValue));
  4681. } else {
  4682. // handle 'null' and 'undefined' property values set as string
  4683. if (realValue === "null" || realValue === "undefined") {
  4684. isMatched = propValueMatch === realValue;
  4685. break;
  4686. }
  4687. isMatched = convertTypeFromString(propValueMatch) === realValue;
  4688. }
  4689. if (isMatched) {
  4690. break;
  4691. }
  4692. }
  4693. }
  4694. }
  4695. return isMatched;
  4696. };
  4697. /**
  4698. * Checks whether the textContent is matched by :contains arg.
  4699. *
  4700. * @param argsData Pseudo-class name, arg, and dom element to check.
  4701. *
  4702. @returns True if DOM element is matched.
  4703. * @throws An error on invalid arg of pseudo-class.
  4704. */
  4705. const isTextMatched = (argsData) => {
  4706. const { pseudoName, pseudoArg, domElement } = argsData;
  4707. const textContent = getNodeTextContent(domElement);
  4708. let isTextContentMatched;
  4709. let pseudoArgToMatch = pseudoArg;
  4710. if (
  4711. pseudoArgToMatch.startsWith(SLASH) &&
  4712. REGEXP_WITH_FLAGS_REGEXP.test(pseudoArgToMatch)
  4713. ) {
  4714. // regexp arg
  4715. const flagsIndex = pseudoArgToMatch.lastIndexOf("/");
  4716. const flagsStr = pseudoArgToMatch.substring(flagsIndex + 1);
  4717. pseudoArgToMatch = pseudoArgToMatch
  4718. .substring(0, flagsIndex + 1)
  4719. .slice(1, -1)
  4720. .replace(/\\([\\"])/g, "$1");
  4721. let regex;
  4722. try {
  4723. regex = new RegExp(pseudoArgToMatch, flagsStr);
  4724. } catch (e) {
  4725. throw new Error(
  4726. `Invalid argument of :${pseudoName}() pseudo-class: ${pseudoArg}`
  4727. );
  4728. }
  4729. isTextContentMatched = regex.test(textContent);
  4730. } else {
  4731. // none-regexp arg
  4732. pseudoArgToMatch = pseudoArgToMatch.replace(/\\([\\()[\]"])/g, "$1");
  4733. isTextContentMatched = textContent.includes(pseudoArgToMatch);
  4734. }
  4735. return isTextContentMatched;
  4736. };
  4737. /**
  4738. * Validates number arg for :nth-ancestor() and :upward() pseudo-classes.
  4739. *
  4740. * @param rawArg Raw arg of pseudo-class.
  4741. * @param pseudoName Pseudo-class name.
  4742. *
  4743. * @returns Valid number arg for :nth-ancestor() and :upward().
  4744. * @throws An error on invalid `rawArg`.
  4745. */
  4746. const getValidNumberAncestorArg = (rawArg, pseudoName) => {
  4747. const deep = Number(rawArg);
  4748. if (Number.isNaN(deep) || deep < 1 || deep >= 256) {
  4749. throw new Error(
  4750. `Invalid argument of :${pseudoName} pseudo-class: '${rawArg}'`
  4751. );
  4752. }
  4753. return deep;
  4754. };
  4755. /**
  4756. * Returns nth ancestor by 'deep' number arg OR undefined if ancestor range limit exceeded.
  4757. *
  4758. * @param domElement DOM element to find ancestor for.
  4759. * @param nth Depth up to needed ancestor.
  4760. * @param pseudoName Pseudo-class name.
  4761. *
  4762. * @returns Ancestor element found in DOM, or null if not found.
  4763. * @throws An error on invalid `nth` arg.
  4764. */
  4765. const getNthAncestor = (domElement, nth, pseudoName) => {
  4766. let ancestor = null;
  4767. let i = 0;
  4768. while (i < nth) {
  4769. ancestor = domElement.parentElement;
  4770. if (!ancestor) {
  4771. throw new Error(
  4772. `Out of DOM: Argument of :${pseudoName}() pseudo-class is too big '${nth}'.`
  4773. );
  4774. }
  4775. domElement = ancestor;
  4776. i += 1;
  4777. }
  4778. return ancestor;
  4779. };
  4780. /**
  4781. * Validates standard CSS selector.
  4782. *
  4783. * @param selector Standard selector.
  4784. *
  4785. * @returns True if standard CSS selector is valid.
  4786. */
  4787. const validateStandardSelector = (selector) => {
  4788. let isValid;
  4789. try {
  4790. document.querySelectorAll(selector);
  4791. isValid = true;
  4792. } catch (e) {
  4793. isValid = false;
  4794. }
  4795. return isValid;
  4796. };
  4797. /**
  4798. * Wrapper to run matcher `callback` with `args`
  4799. * and throw error with `errorMessage` if `callback` run fails.
  4800. *
  4801. * @param callback Matcher callback.
  4802. * @param argsData Args needed for matcher callback.
  4803. * @param errorMessage Error message.
  4804. *
  4805. * @returns True if `callback` returns true.
  4806. * @throws An error if `callback` fails.
  4807. */
  4808. const matcherWrapper = (callback, argsData, errorMessage) => {
  4809. let isMatched;
  4810. try {
  4811. isMatched = callback(argsData);
  4812. } catch (e) {
  4813. logger.error(getErrorMessage(e));
  4814. throw new Error(errorMessage);
  4815. }
  4816. return isMatched;
  4817. };
  4818. /**
  4819. * Generates common error message to throw while matching element `propDesc`.
  4820. *
  4821. * @param propDesc Text to describe what element 'prop' pseudo-class is trying to match.
  4822. * @param pseudoName Pseudo-class name.
  4823. * @param pseudoArg Pseudo-class arg.
  4824. *
  4825. * @returns Generated error message string.
  4826. */
  4827. const getAbsolutePseudoError = (propDesc, pseudoName, pseudoArg) => {
  4828. // eslint-disable-next-line max-len
  4829. return `${MATCHING_ELEMENT_ERROR_PREFIX} ${propDesc}, may be invalid :${pseudoName}() pseudo-class arg: '${pseudoArg}'`;
  4830. };
  4831. /**
  4832. * Checks whether the domElement is matched by absolute extended pseudo-class argument.
  4833. *
  4834. * @param domElement Page element.
  4835. * @param pseudoName Pseudo-class name.
  4836. * @param pseudoArg Pseudo-class arg.
  4837. *
  4838. * @returns True if `domElement` is matched by absolute pseudo-class.
  4839. * @throws An error on unknown absolute pseudo-class.
  4840. */
  4841. const isMatchedByAbsolutePseudo = (domElement, pseudoName, pseudoArg) => {
  4842. let argsData;
  4843. let errorMessage;
  4844. let callback;
  4845. switch (pseudoName) {
  4846. case CONTAINS_PSEUDO:
  4847. case HAS_TEXT_PSEUDO:
  4848. case ABP_CONTAINS_PSEUDO:
  4849. callback = isTextMatched;
  4850. argsData = {
  4851. pseudoName,
  4852. pseudoArg,
  4853. domElement,
  4854. };
  4855. errorMessage = getAbsolutePseudoError(
  4856. "text content",
  4857. pseudoName,
  4858. pseudoArg
  4859. );
  4860. break;
  4861. case MATCHES_CSS_PSEUDO:
  4862. case MATCHES_CSS_AFTER_PSEUDO:
  4863. case MATCHES_CSS_BEFORE_PSEUDO:
  4864. callback = isStyleMatched;
  4865. argsData = {
  4866. pseudoName,
  4867. pseudoArg,
  4868. domElement,
  4869. };
  4870. errorMessage = getAbsolutePseudoError("style", pseudoName, pseudoArg);
  4871. break;
  4872. case MATCHES_ATTR_PSEUDO_CLASS_MARKER:
  4873. callback = isAttributeMatched;
  4874. argsData = {
  4875. domElement,
  4876. pseudoName,
  4877. pseudoArg,
  4878. };
  4879. errorMessage = getAbsolutePseudoError(
  4880. "attributes",
  4881. pseudoName,
  4882. pseudoArg
  4883. );
  4884. break;
  4885. case MATCHES_PROPERTY_PSEUDO_CLASS_MARKER:
  4886. callback = isPropertyMatched;
  4887. argsData = {
  4888. domElement,
  4889. pseudoName,
  4890. pseudoArg,
  4891. };
  4892. errorMessage = getAbsolutePseudoError(
  4893. "properties",
  4894. pseudoName,
  4895. pseudoArg
  4896. );
  4897. break;
  4898. default:
  4899. throw new Error(`Unknown absolute pseudo-class :${pseudoName}()`);
  4900. }
  4901. return matcherWrapper(callback, argsData, errorMessage);
  4902. };
  4903. const findByAbsolutePseudoPseudo = {
  4904. /**
  4905. * Returns list of nth ancestors relative to every dom node from domElements list.
  4906. *
  4907. * @param domElements DOM elements.
  4908. * @param rawPseudoArg Number arg of :nth-ancestor() or :upward() pseudo-class.
  4909. * @param pseudoName Pseudo-class name.
  4910. *
  4911. * @returns Array of ancestor DOM elements.
  4912. */
  4913. nthAncestor: (domElements, rawPseudoArg, pseudoName) => {
  4914. const deep = getValidNumberAncestorArg(rawPseudoArg, pseudoName);
  4915. const ancestors = domElements
  4916. .map((domElement) => {
  4917. let ancestor = null;
  4918. try {
  4919. ancestor = getNthAncestor(domElement, deep, pseudoName);
  4920. } catch (e) {
  4921. logger.error(getErrorMessage(e));
  4922. }
  4923. return ancestor;
  4924. })
  4925. .filter(isHtmlElement);
  4926. return ancestors;
  4927. },
  4928. /**
  4929. * Returns list of elements by xpath expression, evaluated on every dom node from domElements list.
  4930. *
  4931. * @param domElements DOM elements.
  4932. * @param rawPseudoArg Arg of :xpath() pseudo-class.
  4933. *
  4934. * @returns Array of DOM elements matched by xpath expression.
  4935. */
  4936. xpath: (domElements, rawPseudoArg) => {
  4937. const foundElements = domElements.map((domElement) => {
  4938. const result = [];
  4939. let xpathResult;
  4940. try {
  4941. xpathResult = document.evaluate(
  4942. rawPseudoArg,
  4943. domElement,
  4944. null,
  4945. window.XPathResult.UNORDERED_NODE_ITERATOR_TYPE,
  4946. null
  4947. );
  4948. } catch (e) {
  4949. logger.error(getErrorMessage(e));
  4950. throw new Error(
  4951. `Invalid argument of :xpath() pseudo-class: '${rawPseudoArg}'`
  4952. );
  4953. }
  4954. let node = xpathResult.iterateNext();
  4955. while (node) {
  4956. if (isHtmlElement(node)) {
  4957. result.push(node);
  4958. }
  4959. node = xpathResult.iterateNext();
  4960. }
  4961. return result;
  4962. });
  4963. return flatten(foundElements);
  4964. },
  4965. /**
  4966. * Returns list of closest ancestors relative to every dom node from domElements list.
  4967. *
  4968. * @param domElements DOM elements.
  4969. * @param rawPseudoArg Standard selector arg of :upward() pseudo-class.
  4970. *
  4971. * @returns Array of closest ancestor DOM elements.
  4972. * @throws An error if `rawPseudoArg` is not a valid standard selector.
  4973. */
  4974. upward: (domElements, rawPseudoArg) => {
  4975. if (!validateStandardSelector(rawPseudoArg)) {
  4976. throw new Error(
  4977. `Invalid argument of :upward pseudo-class: '${rawPseudoArg}'`
  4978. );
  4979. }
  4980. const closestAncestors = domElements
  4981. .map((domElement) => {
  4982. // closest to parent element should be found
  4983. // otherwise `.base:upward(.base)` will return itself too, not only ancestor
  4984. const parent = domElement.parentElement;
  4985. if (!parent) {
  4986. return null;
  4987. }
  4988. return parent.closest(rawPseudoArg);
  4989. })
  4990. .filter(isHtmlElement);
  4991. return closestAncestors;
  4992. },
  4993. };
  4994. /**
  4995. * Calculated selector text which is needed to :has(), :is() and :not() pseudo-classes.
  4996. * Contains calculated part (depends on the processed element)
  4997. * and value of RegularSelector which is next to selector by.
  4998. *
  4999. * Native Document.querySelectorAll() does not select exact descendant elements
  5000. * but match all page elements satisfying the selector,
  5001. * so extra specification is needed for proper descendants selection
  5002. * e.g. 'div:has(> img)'.
  5003. *
  5004. * Its calculation depends on extended selector.
  5005. */
  5006. /**
  5007. * Combined `:scope` pseudo-class and **child** combinator — `:scope>`.
  5008. */
  5009. const scopeDirectChildren = `${SCOPE_CSS_PSEUDO_CLASS}${CHILD_COMBINATOR}`;
  5010. /**
  5011. * Combined `:scope` pseudo-class and **descendant** combinator — `:scope `.
  5012. */
  5013. const scopeAnyChildren = `${SCOPE_CSS_PSEUDO_CLASS}${DESCENDANT_COMBINATOR}`;
  5014. /**
  5015. * Type for relative pseudo-class helpers args.
  5016. */
  5017. /**
  5018. * Returns the first of RegularSelector child node for `selectorNode`.
  5019. *
  5020. * @param selectorNode Ast Selector node.
  5021. * @param pseudoName Name of relative pseudo-class.
  5022. *
  5023. * @returns Ast RegularSelector node.
  5024. */
  5025. const getFirstInnerRegularChild = (selectorNode, pseudoName) => {
  5026. return getFirstRegularChild(
  5027. selectorNode.children,
  5028. `RegularSelector is missing for :${pseudoName}() pseudo-class`
  5029. );
  5030. }; // TODO: fix for <forgiving-relative-selector-list>
  5031. // https://github.com/AdguardTeam/ExtendedCss/issues/154
  5032. /**
  5033. * Checks whether the element has all relative elements specified by pseudo-class arg.
  5034. * Used for :has() pseudo-class.
  5035. *
  5036. * @param argsData Relative pseudo-class helpers args data.
  5037. *
  5038. * @returns True if **all selectors** from argsData.relativeSelectorList is **matched** for argsData.element.
  5039. */
  5040. const hasRelativesBySelectorList = (argsData) => {
  5041. const { element, relativeSelectorList, pseudoName } = argsData;
  5042. return relativeSelectorList.children // Array.every() is used here as each Selector node from SelectorList should exist on page
  5043. .every((selectorNode) => {
  5044. // selectorList.children always starts with regular selector as any selector generally
  5045. const relativeRegularSelector = getFirstInnerRegularChild(
  5046. selectorNode,
  5047. pseudoName
  5048. );
  5049. let specifiedSelector = "";
  5050. let rootElement = null;
  5051. const regularSelector = getNodeValue(relativeRegularSelector);
  5052. if (
  5053. regularSelector.startsWith(NEXT_SIBLING_COMBINATOR) ||
  5054. regularSelector.startsWith(SUBSEQUENT_SIBLING_COMBINATOR)
  5055. ) {
  5056. /**
  5057. * For matching the element by "element:has(+ next-sibling)" and "element:has(~ sibling)"
  5058. * we check whether the element's parentElement has specific direct child combination,
  5059. * e.g. 'h1:has(+ .share)' -> `h1Node.parentElement.querySelectorAll(':scope > h1 + .share')`.
  5060. *
  5061. * @see {@link https://www.w3.org/TR/selectors-4/#relational}
  5062. */
  5063. rootElement = element.parentElement;
  5064. const elementSelectorText = getElementSelectorDesc(element);
  5065. specifiedSelector = `${scopeDirectChildren}${elementSelectorText}${regularSelector}`;
  5066. } else if (regularSelector === ASTERISK) {
  5067. /**
  5068. * :scope specification is needed for proper descendants selection
  5069. * as native element.querySelectorAll() does not select exact element descendants
  5070. * e.g. 'a:has(> img)' -> `aNode.querySelectorAll(':scope > img')`.
  5071. *
  5072. * For 'any selector' as arg of relative simplicity should be set for all inner elements
  5073. * e.g. 'div:has(*)' -> `divNode.querySelectorAll(':scope *')`
  5074. * which means empty div with no child element.
  5075. */
  5076. rootElement = element;
  5077. specifiedSelector = `${scopeAnyChildren}${ASTERISK}`;
  5078. } else {
  5079. /**
  5080. * As it described above, inner elements should be found using `:scope` pseudo-class
  5081. * e.g. 'a:has(> img)' -> `aNode.querySelectorAll(':scope > img')`
  5082. * OR '.block(div > span)' -> `blockClassNode.querySelectorAll(':scope div > span')`.
  5083. */
  5084. specifiedSelector = `${scopeAnyChildren}${regularSelector}`;
  5085. rootElement = element;
  5086. }
  5087. if (!rootElement) {
  5088. throw new Error(
  5089. `Selection by :${pseudoName}() pseudo-class is not possible`
  5090. );
  5091. }
  5092. let relativeElements;
  5093. try {
  5094. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  5095. relativeElements = getElementsForSelectorNode(
  5096. selectorNode,
  5097. rootElement,
  5098. specifiedSelector
  5099. );
  5100. } catch (e) {
  5101. logger.error(getErrorMessage(e)); // fail for invalid selector
  5102. throw new Error(
  5103. `Invalid selector for :${pseudoName}() pseudo-class: '${regularSelector}'`
  5104. );
  5105. }
  5106. return relativeElements.length > 0;
  5107. });
  5108. };
  5109. /**
  5110. * Checks whether the element is an any element specified by pseudo-class arg.
  5111. * Used for :is() pseudo-class.
  5112. *
  5113. * @param argsData Relative pseudo-class helpers args data.
  5114. *
  5115. * @returns True if **any selector** from argsData.relativeSelectorList is **matched** for argsData.element.
  5116. */
  5117. const isAnyElementBySelectorList = (argsData) => {
  5118. const { element, relativeSelectorList, pseudoName } = argsData;
  5119. return relativeSelectorList.children // Array.some() is used here as any selector from selector list should exist on page
  5120. .some((selectorNode) => {
  5121. // selectorList.children always starts with regular selector
  5122. const relativeRegularSelector = getFirstInnerRegularChild(
  5123. selectorNode,
  5124. pseudoName
  5125. );
  5126. /**
  5127. * For checking the element by 'div:is(.banner)'
  5128. * we check whether the element's parentElement has any specific direct child.
  5129. */
  5130. const rootElement = getParent(
  5131. element,
  5132. `Selection by :${pseudoName}() pseudo-class is not possible`
  5133. );
  5134. /**
  5135. * So we calculate the element "description" by it's tagname and attributes for targeting
  5136. * and use it to specify the selection
  5137. * e.g. `div:is(.banner)` --> `divNode.parentElement.querySelectorAll(':scope > .banner')`.
  5138. */
  5139. const specifiedSelector = `${scopeDirectChildren}${getNodeValue(
  5140. relativeRegularSelector
  5141. )}`;
  5142. let anyElements;
  5143. try {
  5144. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  5145. anyElements = getElementsForSelectorNode(
  5146. selectorNode,
  5147. rootElement,
  5148. specifiedSelector
  5149. );
  5150. } catch (e) {
  5151. // do not fail on invalid selectors for :is()
  5152. return false;
  5153. } // TODO: figure out how to handle complex selectors with extended pseudo-classes
  5154. // (check readme - extended-css-is-limitations)
  5155. // because `element` and `anyElements` may be from different DOM levels
  5156. return anyElements.includes(element);
  5157. });
  5158. };
  5159. /**
  5160. * Checks whether the element is not an element specified by pseudo-class arg.
  5161. * Used for :not() pseudo-class.
  5162. *
  5163. * @param argsData Relative pseudo-class helpers args data.
  5164. *
  5165. * @returns True if **any selector** from argsData.relativeSelectorList is **not matched** for argsData.element.
  5166. */
  5167. const notElementBySelectorList = (argsData) => {
  5168. const { element, relativeSelectorList, pseudoName } = argsData;
  5169. return relativeSelectorList.children // Array.every() is used here as element should not be selected by any selector from selector list
  5170. .every((selectorNode) => {
  5171. // selectorList.children always starts with regular selector
  5172. const relativeRegularSelector = getFirstInnerRegularChild(
  5173. selectorNode,
  5174. pseudoName
  5175. );
  5176. /**
  5177. * For checking the element by 'div:not([data="content"])
  5178. * we check whether the element's parentElement has any specific direct child.
  5179. */
  5180. const rootElement = getParent(
  5181. element,
  5182. `Selection by :${pseudoName}() pseudo-class is not possible`
  5183. );
  5184. /**
  5185. * So we calculate the element "description" by it's tagname and attributes for targeting
  5186. * and use it to specify the selection
  5187. * e.g. `div:not(.banner)` --> `divNode.parentElement.querySelectorAll(':scope > .banner')`.
  5188. */
  5189. const specifiedSelector = `${scopeDirectChildren}${getNodeValue(
  5190. relativeRegularSelector
  5191. )}`;
  5192. let anyElements;
  5193. try {
  5194. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  5195. anyElements = getElementsForSelectorNode(
  5196. selectorNode,
  5197. rootElement,
  5198. specifiedSelector
  5199. );
  5200. } catch (e) {
  5201. // fail on invalid selectors for :not()
  5202. logger.error(getErrorMessage(e)); // eslint-disable-next-line max-len
  5203. throw new Error(
  5204. `Invalid selector for :${pseudoName}() pseudo-class: '${getNodeValue(
  5205. relativeRegularSelector
  5206. )}'`
  5207. );
  5208. } // TODO: figure out how to handle up-looking pseudo-classes inside :not()
  5209. // (check readme - extended-css-not-limitations)
  5210. // because `element` and `anyElements` may be from different DOM levels
  5211. return !anyElements.includes(element);
  5212. });
  5213. };
  5214. /**
  5215. * Selects dom elements by value of RegularSelector.
  5216. *
  5217. * @param regularSelectorNode RegularSelector node.
  5218. * @param root Root DOM element.
  5219. * @param specifiedSelector @see {@link SpecifiedSelector}.
  5220. *
  5221. * @returns Array of DOM elements.
  5222. * @throws An error if RegularSelector node value is an invalid selector.
  5223. */
  5224. const getByRegularSelector = (
  5225. regularSelectorNode,
  5226. root,
  5227. specifiedSelector
  5228. ) => {
  5229. const selectorText = specifiedSelector
  5230. ? specifiedSelector
  5231. : getNodeValue(regularSelectorNode);
  5232. let selectedElements = [];
  5233. try {
  5234. selectedElements = Array.from(root.querySelectorAll(selectorText));
  5235. } catch (e) {
  5236. throw new Error(
  5237. `Error: unable to select by '${selectorText}' ${getErrorMessage(e)}`
  5238. );
  5239. }
  5240. return selectedElements;
  5241. };
  5242. /**
  5243. * Returns list of dom elements filtered or selected by ExtendedSelector node.
  5244. *
  5245. * @param domElements Array of DOM elements.
  5246. * @param extendedSelectorNode ExtendedSelector node.
  5247. *
  5248. * @returns Array of DOM elements.
  5249. * @throws An error on unknown pseudo-class,
  5250. * absent or invalid arg of extended pseudo-class, etc.
  5251. */
  5252. const getByExtendedSelector = (domElements, extendedSelectorNode) => {
  5253. let foundElements = [];
  5254. const extendedPseudoClassNode = getPseudoClassNode(extendedSelectorNode);
  5255. const pseudoName = getNodeName(extendedPseudoClassNode);
  5256. if (isAbsolutePseudoClass(pseudoName)) {
  5257. // absolute extended pseudo-classes should have an argument
  5258. const absolutePseudoArg = getNodeValue(
  5259. extendedPseudoClassNode,
  5260. `Missing arg for :${pseudoName}() pseudo-class`
  5261. );
  5262. if (pseudoName === NTH_ANCESTOR_PSEUDO_CLASS_MARKER) {
  5263. // :nth-ancestor()
  5264. foundElements = findByAbsolutePseudoPseudo.nthAncestor(
  5265. domElements,
  5266. absolutePseudoArg,
  5267. pseudoName
  5268. );
  5269. } else if (pseudoName === XPATH_PSEUDO_CLASS_MARKER) {
  5270. // :xpath()
  5271. try {
  5272. document.createExpression(absolutePseudoArg, null);
  5273. } catch (e) {
  5274. throw new Error(
  5275. `Invalid argument of :${pseudoName}() pseudo-class: '${absolutePseudoArg}'`
  5276. );
  5277. }
  5278. foundElements = findByAbsolutePseudoPseudo.xpath(
  5279. domElements,
  5280. absolutePseudoArg
  5281. );
  5282. } else if (pseudoName === UPWARD_PSEUDO_CLASS_MARKER) {
  5283. // :upward()
  5284. if (Number.isNaN(Number(absolutePseudoArg))) {
  5285. // so arg is selector, not a number
  5286. foundElements = findByAbsolutePseudoPseudo.upward(
  5287. domElements,
  5288. absolutePseudoArg
  5289. );
  5290. } else {
  5291. foundElements = findByAbsolutePseudoPseudo.nthAncestor(
  5292. domElements,
  5293. absolutePseudoArg,
  5294. pseudoName
  5295. );
  5296. }
  5297. } else {
  5298. // all other absolute extended pseudo-classes
  5299. // e.g. contains, matches-attr, etc.
  5300. foundElements = domElements.filter((element) => {
  5301. return isMatchedByAbsolutePseudo(
  5302. element,
  5303. pseudoName,
  5304. absolutePseudoArg
  5305. );
  5306. });
  5307. }
  5308. } else if (isRelativePseudoClass(pseudoName)) {
  5309. const relativeSelectorList = getRelativeSelectorListNode(
  5310. extendedPseudoClassNode
  5311. );
  5312. let relativePredicate;
  5313. switch (pseudoName) {
  5314. case HAS_PSEUDO_CLASS_MARKER:
  5315. case ABP_HAS_PSEUDO_CLASS_MARKER:
  5316. relativePredicate = (element) =>
  5317. hasRelativesBySelectorList({
  5318. element,
  5319. relativeSelectorList,
  5320. pseudoName,
  5321. });
  5322. break;
  5323. case IS_PSEUDO_CLASS_MARKER:
  5324. relativePredicate = (element) =>
  5325. isAnyElementBySelectorList({
  5326. element,
  5327. relativeSelectorList,
  5328. pseudoName,
  5329. });
  5330. break;
  5331. case NOT_PSEUDO_CLASS_MARKER:
  5332. relativePredicate = (element) =>
  5333. notElementBySelectorList({
  5334. element,
  5335. relativeSelectorList,
  5336. pseudoName,
  5337. });
  5338. break;
  5339. default:
  5340. throw new Error(`Unknown relative pseudo-class: '${pseudoName}'`);
  5341. }
  5342. foundElements = domElements.filter(relativePredicate);
  5343. } else {
  5344. // extra check is parser missed something
  5345. throw new Error(`Unknown extended pseudo-class: '${pseudoName}'`);
  5346. }
  5347. return foundElements;
  5348. };
  5349. /**
  5350. * Returns list of dom elements which is selected by RegularSelector value.
  5351. *
  5352. * @param domElements Array of DOM elements.
  5353. * @param regularSelectorNode RegularSelector node.
  5354. *
  5355. * @returns Array of DOM elements.
  5356. * @throws An error if RegularSelector has not value.
  5357. */
  5358. const getByFollowingRegularSelector = (
  5359. domElements,
  5360. regularSelectorNode
  5361. ) => {
  5362. // array of arrays because of Array.map() later
  5363. let foundElements = [];
  5364. const value = getNodeValue(regularSelectorNode);
  5365. if (value.startsWith(CHILD_COMBINATOR)) {
  5366. // e.g. div:has(> img) > .banner
  5367. foundElements = domElements.map((root) => {
  5368. const specifiedSelector = `${SCOPE_CSS_PSEUDO_CLASS}${value}`;
  5369. return getByRegularSelector(
  5370. regularSelectorNode,
  5371. root,
  5372. specifiedSelector
  5373. );
  5374. });
  5375. } else if (
  5376. value.startsWith(NEXT_SIBLING_COMBINATOR) ||
  5377. value.startsWith(SUBSEQUENT_SIBLING_COMBINATOR)
  5378. ) {
  5379. // e.g. div:has(> img) + .banner
  5380. // or div:has(> img) ~ .banner
  5381. foundElements = domElements.map((element) => {
  5382. const rootElement = element.parentElement;
  5383. if (!rootElement) {
  5384. // do not throw error if there in no parent for element
  5385. // e.g. '*:contains(text)' selects `html` which has no parentElement
  5386. return [];
  5387. }
  5388. const elementSelectorText = getElementSelectorDesc(element);
  5389. const specifiedSelector = `${scopeDirectChildren}${elementSelectorText}${value}`;
  5390. const selected = getByRegularSelector(
  5391. regularSelectorNode,
  5392. rootElement,
  5393. specifiedSelector
  5394. );
  5395. return selected;
  5396. });
  5397. } else {
  5398. // space-separated regular selector after extended one
  5399. // e.g. div:has(> img) .banner
  5400. foundElements = domElements.map((root) => {
  5401. const specifiedSelector = `${scopeAnyChildren}${getNodeValue(
  5402. regularSelectorNode
  5403. )}`;
  5404. return getByRegularSelector(
  5405. regularSelectorNode,
  5406. root,
  5407. specifiedSelector
  5408. );
  5409. });
  5410. } // foundElements should be flattened
  5411. // as getByRegularSelector() returns elements array, and Array.map() collects them to array
  5412. return flatten(foundElements);
  5413. };
  5414. /**
  5415. * Returns elements nodes for Selector node.
  5416. * As far as any selector always starts with regular part,
  5417. * it selects by RegularSelector first and checks found elements later.
  5418. *
  5419. * Relative pseudo-classes has it's own subtree so getElementsForSelectorNode is called recursively.
  5420. *
  5421. * 'specifiedSelector' is needed for :has(), :is(), and :not() pseudo-classes
  5422. * as native querySelectorAll() does not select exact element descendants even if it is called on 'div'
  5423. * e.g. ':scope' specification is needed for proper descendants selection for 'div:has(> img)'.
  5424. * So we check `divNode.querySelectorAll(':scope > img').length > 0`.
  5425. *
  5426. * @param selectorNode Selector node.
  5427. * @param root Root DOM element.
  5428. * @param specifiedSelector Needed element specification.
  5429. *
  5430. * @returns Array of DOM elements.
  5431. * @throws An error if there is no selectorNodeChild.
  5432. */
  5433. const getElementsForSelectorNode = (
  5434. selectorNode,
  5435. root,
  5436. specifiedSelector
  5437. ) => {
  5438. let selectedElements = [];
  5439. let i = 0;
  5440. while (i < selectorNode.children.length) {
  5441. const selectorNodeChild = getItemByIndex(
  5442. selectorNode.children,
  5443. i,
  5444. "selectorNodeChild should be specified"
  5445. );
  5446. if (i === 0) {
  5447. // any selector always starts with regular selector
  5448. selectedElements = getByRegularSelector(
  5449. selectorNodeChild,
  5450. root,
  5451. specifiedSelector
  5452. );
  5453. } else if (isExtendedSelectorNode(selectorNodeChild)) {
  5454. // filter previously selected elements by next selector nodes
  5455. selectedElements = getByExtendedSelector(
  5456. selectedElements,
  5457. selectorNodeChild
  5458. );
  5459. } else if (isRegularSelectorNode(selectorNodeChild)) {
  5460. selectedElements = getByFollowingRegularSelector(
  5461. selectedElements,
  5462. selectorNodeChild
  5463. );
  5464. }
  5465. i += 1;
  5466. }
  5467. return selectedElements;
  5468. };
  5469. /**
  5470. * Selects elements by ast.
  5471. *
  5472. * @param ast Ast of parsed selector.
  5473. * @param doc Document.
  5474. *
  5475. * @returns Array of DOM elements.
  5476. */
  5477. const selectElementsByAst = function (ast) {
  5478. let doc =
  5479. arguments.length > 1 && arguments[1] !== undefined
  5480. ? arguments[1]
  5481. : document;
  5482. const selectedElements = []; // ast root is SelectorList node;
  5483. // it has Selector nodes as children which should be processed separately
  5484. ast.children.forEach((selectorNode) => {
  5485. selectedElements.push(...getElementsForSelectorNode(selectorNode, doc));
  5486. }); // selectedElements should be flattened as it is array of arrays with elements
  5487. const uniqueElements = [...new Set(flatten(selectedElements))];
  5488. return uniqueElements;
  5489. };
  5490. /**
  5491. * Class of ExtCssDocument is needed for caching.
  5492. * For making cache related to each new instance of class, not global.
  5493. */
  5494. class ExtCssDocument {
  5495. /**
  5496. * Cache with selectors and their AST parsing results.
  5497. */
  5498. /**
  5499. * Creates new ExtCssDocument and inits new `astCache`.
  5500. */
  5501. constructor() {
  5502. this.astCache = new Map();
  5503. }
  5504. /**
  5505. * Saves selector and it's ast to cache.
  5506. *
  5507. * @param selector Standard or extended selector.
  5508. * @param ast Selector ast.
  5509. */
  5510. saveAstToCache(selector, ast) {
  5511. this.astCache.set(selector, ast);
  5512. }
  5513. /**
  5514. * Returns ast from cache for given selector.
  5515. *
  5516. * @param selector Standard or extended selector.
  5517. *
  5518. * @returns Previously parsed ast found in cache, or null if not found.
  5519. */
  5520. getAstFromCache(selector) {
  5521. const cachedAst = this.astCache.get(selector) || null;
  5522. return cachedAst;
  5523. }
  5524. /**
  5525. * Returns selector ast:
  5526. * - if cached ast exists — returns it;
  5527. * - if no cached ast — saves newly parsed ast to cache and returns it.
  5528. *
  5529. * @param selector Standard or extended selector.
  5530. *
  5531. * @returns Ast for `selector`.
  5532. */
  5533. getSelectorAst(selector) {
  5534. let ast = this.getAstFromCache(selector);
  5535. if (!ast) {
  5536. ast = parse(selector);
  5537. }
  5538. this.saveAstToCache(selector, ast);
  5539. return ast;
  5540. }
  5541. /**
  5542. * Selects elements by selector.
  5543. *
  5544. * @param selector Standard or extended selector.
  5545. *
  5546. * @returns Array of DOM elements.
  5547. */
  5548. querySelectorAll(selector) {
  5549. const ast = this.getSelectorAst(selector);
  5550. return selectElementsByAst(ast);
  5551. }
  5552. }
  5553. const extCssDocument = new ExtCssDocument();
  5554. /**
  5555. * Converts array of `entries` to object.
  5556. * Object.fromEntries() polyfill because it is not supported by old browsers, e.g. Chrome 55.
  5557. * Only first two elements of `entries` array matter, other will be skipped silently.
  5558. *
  5559. * @see {@link https://caniuse.com/?search=Object.fromEntries}
  5560. *
  5561. * @param entries Array of pairs.
  5562. *
  5563. * @returns Object converted from `entries`.
  5564. */
  5565. const getObjectFromEntries = (entries) => {
  5566. const object = {};
  5567. entries.forEach((el) => {
  5568. const [key, value] = el;
  5569. object[key] = value;
  5570. });
  5571. return object;
  5572. };
  5573. const DEBUG_PSEUDO_PROPERTY_KEY = "debug";
  5574. /**
  5575. * Checks the presence of :remove() pseudo-class and validates it while parsing the selector part of css rule.
  5576. *
  5577. * @param rawSelector Selector which may contain :remove() pseudo-class.
  5578. *
  5579. * @returns Parsed selector data with selector and styles.
  5580. * @throws An error on invalid :remove() position.
  5581. */
  5582. const parseRemoveSelector = (rawSelector) => {
  5583. /**
  5584. * No error will be thrown on invalid selector as it will be validated later
  5585. * so it's better to explicitly specify 'any' selector for :remove() pseudo-class by '*',
  5586. * e.g. '.banner > *:remove()' instead of '.banner > :remove()'.
  5587. */
  5588. // ':remove()'
  5589. // eslint-disable-next-line max-len
  5590. const VALID_REMOVE_MARKER = `${COLON}${REMOVE_PSEUDO_MARKER}${BRACKET.PARENTHESES.LEFT}${BRACKET.PARENTHESES.RIGHT}`; // ':remove(' - needed for validation rules like 'div:remove(2)'
  5591. const INVALID_REMOVE_MARKER = `${COLON}${REMOVE_PSEUDO_MARKER}${BRACKET.PARENTHESES.LEFT}`;
  5592. let selector;
  5593. let shouldRemove = false;
  5594. const firstIndex = rawSelector.indexOf(VALID_REMOVE_MARKER);
  5595. if (firstIndex === 0) {
  5596. // e.g. ':remove()'
  5597. throw new Error(
  5598. `${REMOVE_ERROR_PREFIX.NO_TARGET_SELECTOR}: '${rawSelector}'`
  5599. );
  5600. } else if (firstIndex > 0) {
  5601. if (firstIndex !== rawSelector.lastIndexOf(VALID_REMOVE_MARKER)) {
  5602. // rule with more than one :remove() pseudo-class is invalid
  5603. // e.g. '.block:remove() > .banner:remove()'
  5604. throw new Error(
  5605. `${REMOVE_ERROR_PREFIX.MULTIPLE_USAGE}: '${rawSelector}'`
  5606. );
  5607. } else if (
  5608. firstIndex + VALID_REMOVE_MARKER.length <
  5609. rawSelector.length
  5610. ) {
  5611. // remove pseudo-class should be last in the rule
  5612. // e.g. '.block:remove():upward(2)'
  5613. throw new Error(
  5614. `${REMOVE_ERROR_PREFIX.INVALID_POSITION}: '${rawSelector}'`
  5615. );
  5616. } else {
  5617. // valid :remove() pseudo-class position
  5618. selector = rawSelector.substring(0, firstIndex);
  5619. shouldRemove = true;
  5620. }
  5621. } else if (rawSelector.includes(INVALID_REMOVE_MARKER)) {
  5622. // it is not valid if ':remove()' is absent in rule but just ':remove(' is present
  5623. // e.g. 'div:remove(0)'
  5624. throw new Error(
  5625. `${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${rawSelector}'`
  5626. );
  5627. } else {
  5628. // there is no :remove() pseudo-class in rule
  5629. selector = rawSelector;
  5630. }
  5631. const stylesOfSelector = shouldRemove
  5632. ? [
  5633. {
  5634. property: REMOVE_PSEUDO_MARKER,
  5635. value: PSEUDO_PROPERTY_POSITIVE_VALUE,
  5636. },
  5637. ]
  5638. : [];
  5639. return {
  5640. selector,
  5641. stylesOfSelector,
  5642. };
  5643. };
  5644. /**
  5645. * Parses cropped selector part found before `{`.
  5646. *
  5647. * @param selectorBuffer Buffered selector to parse.
  5648. * @param extCssDoc Needed for caching of selector ast.
  5649. *
  5650. * @returns Parsed validation data for cropped part of stylesheet which may be a selector.
  5651. * @throws An error on unsupported CSS features, e.g. at-rules.
  5652. */
  5653. const parseSelectorRulePart = (selectorBuffer, extCssDoc) => {
  5654. let selector = selectorBuffer.trim();
  5655. if (selector.startsWith(AT_RULE_MARKER)) {
  5656. throw new Error(`${NO_AT_RULE_ERROR_PREFIX}: '${selector}'.`);
  5657. }
  5658. let removeSelectorData;
  5659. try {
  5660. removeSelectorData = parseRemoveSelector(selector);
  5661. } catch (e) {
  5662. logger.error(getErrorMessage(e));
  5663. throw new Error(`${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`);
  5664. }
  5665. let stylesOfSelector = [];
  5666. let success = false;
  5667. let ast;
  5668. try {
  5669. selector = removeSelectorData.selector;
  5670. stylesOfSelector = removeSelectorData.stylesOfSelector; // validate found selector by parsing it to ast
  5671. // so if it is invalid error will be thrown
  5672. ast = extCssDoc.getSelectorAst(selector);
  5673. success = true;
  5674. } catch (e) {
  5675. success = false;
  5676. }
  5677. return {
  5678. success,
  5679. selector,
  5680. ast,
  5681. stylesOfSelector,
  5682. };
  5683. };
  5684. /**
  5685. * Creates a map for storing raw results of css rules parsing.
  5686. * Used for merging styles for same selector.
  5687. *
  5688. * @returns Map where **key** is `selector`
  5689. * and **value** is object with `ast` and `styles`.
  5690. */
  5691. const createRawResultsMap = () => {
  5692. return new Map();
  5693. };
  5694. /**
  5695. * Saves rules data for unique selectors.
  5696. *
  5697. * @param rawResults Previously collected results of parsing.
  5698. * @param rawRuleData Parsed rule data.
  5699. *
  5700. * @throws An error if there is no rawRuleData.styles or rawRuleData.ast.
  5701. */
  5702. const saveToRawResults = (rawResults, rawRuleData) => {
  5703. const { selector, ast, rawStyles } = rawRuleData;
  5704. if (!rawStyles) {
  5705. throw new Error(`No style declaration for selector: '${selector}'`);
  5706. }
  5707. if (!ast) {
  5708. throw new Error(`No ast parsed for selector: '${selector}'`);
  5709. }
  5710. const storedRuleData = rawResults.get(selector);
  5711. if (!storedRuleData) {
  5712. rawResults.set(selector, {
  5713. ast,
  5714. styles: rawStyles,
  5715. });
  5716. } else {
  5717. storedRuleData.styles.push(...rawStyles);
  5718. }
  5719. };
  5720. /**
  5721. * Checks whether the 'remove' property positively set in styles
  5722. * with only one positive value - 'true'.
  5723. *
  5724. * @param styles Array of styles.
  5725. *
  5726. * @returns True if there is 'remove' property with 'true' value in `styles`.
  5727. */
  5728. const isRemoveSetInStyles = (styles) => {
  5729. return styles.some((s) => {
  5730. return (
  5731. s.property === REMOVE_PSEUDO_MARKER &&
  5732. s.value === PSEUDO_PROPERTY_POSITIVE_VALUE
  5733. );
  5734. });
  5735. };
  5736. /**
  5737. * Returns 'debug' property value which is set in styles.
  5738. *
  5739. * @param styles Array of styles.
  5740. *
  5741. * @returns Value of 'debug' property if it is set in `styles`,
  5742. * or `undefined` if the property is not found.
  5743. */
  5744. const getDebugStyleValue = (styles) => {
  5745. const debugStyle = styles.find((s) => {
  5746. return s.property === DEBUG_PSEUDO_PROPERTY_KEY;
  5747. });
  5748. return debugStyle === null || debugStyle === void 0
  5749. ? void 0
  5750. : debugStyle.value;
  5751. };
  5752. /**
  5753. * Prepares final RuleData.
  5754. * Handles `debug` and `remove` in raw rule data styles.
  5755. *
  5756. * @param rawRuleData Raw data of selector css rule parsing.
  5757. *
  5758. * @returns Parsed ExtendedCss rule data.
  5759. * @throws An error if rawRuleData.ast or rawRuleData.rawStyles not defined.
  5760. */
  5761. const prepareRuleData = (rawRuleData) => {
  5762. const { selector, ast, rawStyles } = rawRuleData;
  5763. if (!ast) {
  5764. throw new Error(`AST should be parsed for selector: '${selector}'`);
  5765. }
  5766. if (!rawStyles) {
  5767. throw new Error(`Styles should be parsed for selector: '${selector}'`);
  5768. }
  5769. const ruleData = {
  5770. selector,
  5771. ast,
  5772. };
  5773. const debugValue = getDebugStyleValue(rawStyles);
  5774. const shouldRemove = isRemoveSetInStyles(rawStyles);
  5775. let styles = rawStyles;
  5776. if (debugValue) {
  5777. // get rid of 'debug' from styles
  5778. styles = rawStyles.filter(
  5779. (s) => s.property !== DEBUG_PSEUDO_PROPERTY_KEY
  5780. ); // and set it as separate property only if its value is valid
  5781. // which is 'true' or 'global'
  5782. if (
  5783. debugValue === PSEUDO_PROPERTY_POSITIVE_VALUE ||
  5784. debugValue === DEBUG_PSEUDO_PROPERTY_GLOBAL_VALUE
  5785. ) {
  5786. ruleData.debug = debugValue;
  5787. }
  5788. }
  5789. if (shouldRemove) {
  5790. // no other styles are needed to apply if 'remove' is set
  5791. ruleData.style = {
  5792. [REMOVE_PSEUDO_MARKER]: PSEUDO_PROPERTY_POSITIVE_VALUE,
  5793. };
  5794. /**
  5795. * 'content' property is needed for ExtCssConfiguration.beforeStyleApplied().
  5796. *
  5797. * @see {@link BeforeStyleAppliedCallback}
  5798. */
  5799. const contentStyle = styles.find(
  5800. (s) => s.property === CONTENT_CSS_PROPERTY
  5801. );
  5802. if (contentStyle) {
  5803. ruleData.style[CONTENT_CSS_PROPERTY] = contentStyle.value;
  5804. }
  5805. } else {
  5806. // otherwise all styles should be applied.
  5807. // every style property will be unique because of their converting into object
  5808. if (styles.length > 0) {
  5809. const stylesAsEntries = styles.map((style) => {
  5810. const { property, value } = style;
  5811. return [property, value];
  5812. });
  5813. const preparedStyleData = getObjectFromEntries(stylesAsEntries);
  5814. ruleData.style = preparedStyleData;
  5815. }
  5816. }
  5817. return ruleData;
  5818. };
  5819. /**
  5820. * Combines previously parsed css rules data objects
  5821. * into rules which are ready to apply.
  5822. *
  5823. * @param rawResults Previously parsed css rules data objects.
  5824. *
  5825. * @returns Parsed ExtendedCss rule data.
  5826. */
  5827. const combineRulesData = (rawResults) => {
  5828. const results = [];
  5829. rawResults.forEach((value, key) => {
  5830. const selector = key;
  5831. const { ast, styles: rawStyles } = value;
  5832. results.push(
  5833. prepareRuleData({
  5834. selector,
  5835. ast,
  5836. rawStyles,
  5837. })
  5838. );
  5839. });
  5840. return results;
  5841. };
  5842. /**
  5843. * Trims `rawStyle` and splits it into tokens.
  5844. *
  5845. * @param rawStyle Style declaration block content inside curly bracket — `{` and `}` —
  5846. * can be a single style declaration or a list of declarations.
  5847. *
  5848. * @returns Array of tokens supported for style declaration block.
  5849. */
  5850. const tokenizeStyleBlock = (rawStyle) => {
  5851. const styleDeclaration = rawStyle.trim();
  5852. return tokenize(styleDeclaration, SUPPORTED_STYLE_DECLARATION_MARKS);
  5853. };
  5854. /**
  5855. * Describes possible style declaration parts.
  5856. *
  5857. * IMPORTANT: it is used as 'const' instead of 'enum' to avoid side effects
  5858. * during ExtendedCss import into other libraries.
  5859. */
  5860. const DECLARATION_PART = {
  5861. PROPERTY: "property",
  5862. VALUE: "value",
  5863. };
  5864. /**
  5865. * Checks whether the quotes has been opened for style value.
  5866. *
  5867. * @param context Style block parser context.
  5868. *
  5869. * @returns True if style value has already opened quotes.
  5870. */
  5871. const isValueQuotesOpen = (context) => {
  5872. return context.bufferValue !== "" && context.valueQuoteMark !== null;
  5873. };
  5874. /**
  5875. * Saves parsed property and value to collection of parsed styles.
  5876. * Prunes context buffers for property and value.
  5877. *
  5878. * @param context Style block parser context.
  5879. */
  5880. const collectStyle = (context) => {
  5881. context.styles.push({
  5882. property: context.bufferProperty.trim(),
  5883. value: context.bufferValue.trim(),
  5884. }); // reset buffers
  5885. context.bufferProperty = "";
  5886. context.bufferValue = "";
  5887. };
  5888. /**
  5889. * Handles token which is supposed to be a part of style **property**.
  5890. *
  5891. * @param context Style block parser context.
  5892. * @param styleBlock Whole style block which is being parsed.
  5893. * @param token Current token.
  5894. *
  5895. * @throws An error on invalid token.
  5896. */
  5897. const processPropertyToken = (context, styleBlock, token) => {
  5898. const { value: tokenValue } = token;
  5899. switch (token.type) {
  5900. case TOKEN_TYPE.WORD:
  5901. if (context.bufferProperty.length > 0) {
  5902. // e.g. 'padding top: 0;' - current tokenValue is 'top' which is not valid
  5903. throw new Error(
  5904. `Invalid style property in style block: '${styleBlock}'`
  5905. );
  5906. }
  5907. context.bufferProperty += tokenValue;
  5908. break;
  5909. case TOKEN_TYPE.MARK:
  5910. // only colon and whitespaces are allowed while style property parsing
  5911. if (tokenValue === COLON) {
  5912. if (context.bufferProperty.trim().length === 0) {
  5913. // e.g. such style block: '{ : none; }'
  5914. throw new Error(
  5915. `Missing style property before ':' in style block: '${styleBlock}'`
  5916. );
  5917. } // the property successfully collected
  5918. context.bufferProperty = context.bufferProperty.trim(); // prepare for value collecting
  5919. context.processing = DECLARATION_PART.VALUE; // the property buffer shall be reset after the value is successfully collected
  5920. } else if (WHITE_SPACE_CHARACTERS.includes(tokenValue));
  5921. else {
  5922. // if after the property there is anything other than ':' except whitespace, this is a parse error
  5923. // https://www.w3.org/TR/css-syntax-3/#consume-declaration
  5924. throw new Error(
  5925. `Invalid style declaration in style block: '${styleBlock}'`
  5926. );
  5927. }
  5928. break;
  5929. default:
  5930. throw new Error(
  5931. `Unsupported style property character: '${tokenValue}' in style block: '${styleBlock}'`
  5932. );
  5933. }
  5934. };
  5935. /**
  5936. * Handles token which is supposed to be a part of style **value**.
  5937. *
  5938. * @param context Style block parser context.
  5939. * @param styleBlock Whole style block which is being parsed.
  5940. * @param token Current token.
  5941. *
  5942. * @throws An error on invalid token.
  5943. */
  5944. const processValueToken = (context, styleBlock, token) => {
  5945. const { value: tokenValue } = token;
  5946. if (token.type === TOKEN_TYPE.WORD) {
  5947. // simply collect to buffer
  5948. context.bufferValue += tokenValue;
  5949. } else {
  5950. // otherwise check the mark
  5951. switch (tokenValue) {
  5952. case COLON:
  5953. // the ':' character inside of the value should be inside of quotes
  5954. // otherwise the value is not valid
  5955. // e.g. 'content: display: none'
  5956. // parser is here ↑
  5957. if (!isValueQuotesOpen(context)) {
  5958. // eslint-disable-next-line max-len
  5959. throw new Error(
  5960. `Invalid style value for property '${context.bufferProperty}' in style block: '${styleBlock}'`
  5961. );
  5962. } // collect the colon inside quotes
  5963. // e.g. 'content: "test:123"'
  5964. // parser is here ↑
  5965. context.bufferValue += tokenValue;
  5966. break;
  5967. case SEMICOLON:
  5968. if (isValueQuotesOpen(context)) {
  5969. // ';' inside quotes is part of style value
  5970. // e.g. 'content: "test;"'
  5971. context.bufferValue += tokenValue;
  5972. } else {
  5973. // otherwise the value is successfully collected
  5974. // save parsed style
  5975. collectStyle(context); // prepare for value collecting
  5976. context.processing = DECLARATION_PART.PROPERTY;
  5977. }
  5978. break;
  5979. case SINGLE_QUOTE:
  5980. case DOUBLE_QUOTE:
  5981. // if quotes are not open
  5982. if (context.valueQuoteMark === null) {
  5983. // save the opening quote mark for later comparison
  5984. context.valueQuoteMark = tokenValue;
  5985. } else if (
  5986. !context.bufferValue.endsWith(BACKSLASH) && // otherwise a quote appeared in the value earlier,
  5987. // and non-escaped quote should be checked whether it is a closing quote
  5988. context.valueQuoteMark === tokenValue
  5989. ) {
  5990. context.valueQuoteMark = null;
  5991. } // always save the quote to the buffer
  5992. // but after the context.bufferValue is checked for BACKSLASH above
  5993. // e.g. 'content: "test:123"'
  5994. // 'content: "\""'
  5995. context.bufferValue += tokenValue;
  5996. break;
  5997. case BACKSLASH:
  5998. if (!isValueQuotesOpen(context)) {
  5999. // eslint-disable-next-line max-len
  6000. throw new Error(
  6001. `Invalid style value for property '${context.bufferProperty}' in style block: '${styleBlock}'`
  6002. );
  6003. } // collect the backslash inside quotes
  6004. // e.g. ' content: "\"" '
  6005. // parser is here ↑
  6006. context.bufferValue += tokenValue;
  6007. break;
  6008. case SPACE:
  6009. case TAB:
  6010. case CARRIAGE_RETURN:
  6011. case LINE_FEED:
  6012. case FORM_FEED:
  6013. // whitespace should be collected only if the value collecting started
  6014. // which means inside of the value
  6015. // e.g. 'width: 100% !important'
  6016. // parser is here ↑
  6017. if (context.bufferValue.length > 0) {
  6018. context.bufferValue += tokenValue;
  6019. } // otherwise it can be omitted
  6020. // e.g. 'width: 100% !important'
  6021. // here ↑
  6022. break;
  6023. default:
  6024. throw new Error(`Unknown style declaration token: '${tokenValue}'`);
  6025. }
  6026. }
  6027. };
  6028. /**
  6029. * Parses css rule style block.
  6030. *
  6031. * @param rawStyleBlock Style block to parse.
  6032. *
  6033. * @returns Array of style declarations.
  6034. * @throws An error on invalid style block.
  6035. */
  6036. const parseStyleBlock = (rawStyleBlock) => {
  6037. const styleBlock = rawStyleBlock.trim();
  6038. const tokens = tokenizeStyleBlock(styleBlock);
  6039. const context = {
  6040. // style declaration parsing always starts with 'property'
  6041. processing: DECLARATION_PART.PROPERTY,
  6042. styles: [],
  6043. bufferProperty: "",
  6044. bufferValue: "",
  6045. valueQuoteMark: null,
  6046. };
  6047. let i = 0;
  6048. while (i < tokens.length) {
  6049. const token = tokens[i];
  6050. if (!token) {
  6051. break;
  6052. }
  6053. if (context.processing === DECLARATION_PART.PROPERTY) {
  6054. processPropertyToken(context, styleBlock, token);
  6055. } else if (context.processing === DECLARATION_PART.VALUE) {
  6056. processValueToken(context, styleBlock, token);
  6057. } else {
  6058. throw new Error("Style declaration parsing failed");
  6059. }
  6060. i += 1;
  6061. } // unbalanced value quotes
  6062. // e.g. 'content: "test} '
  6063. if (isValueQuotesOpen(context)) {
  6064. throw new Error(
  6065. `Unbalanced style declaration quotes in style block: '${styleBlock}'`
  6066. );
  6067. } // collected property and value have not been saved to styles;
  6068. // it is possible for style block with no semicolon at the end
  6069. // e.g. such style block: '{ display: none }'
  6070. if (context.bufferProperty.length > 0) {
  6071. if (context.bufferValue.length === 0) {
  6072. // e.g. such style blocks:
  6073. // '{ display: }'
  6074. // '{ remove }'
  6075. // eslint-disable-next-line max-len
  6076. throw new Error(
  6077. `Missing style value for property '${context.bufferProperty}' in style block '${styleBlock}'`
  6078. );
  6079. }
  6080. collectStyle(context);
  6081. } // rule with empty style block
  6082. // e.g. 'div { }'
  6083. if (context.styles.length === 0) {
  6084. throw new Error(STYLE_ERROR_PREFIX.NO_STYLE);
  6085. }
  6086. return context.styles;
  6087. };
  6088. /**
  6089. * Returns array of positions of `{` in `cssRule`.
  6090. *
  6091. * @param cssRule CSS rule.
  6092. *
  6093. * @returns Array of left curly bracket indexes.
  6094. */
  6095. const getLeftCurlyBracketIndexes = (cssRule) => {
  6096. const indexes = [];
  6097. for (let i = 0; i < cssRule.length; i += 1) {
  6098. if (cssRule[i] === BRACKET.CURLY.LEFT) {
  6099. indexes.push(i);
  6100. }
  6101. }
  6102. return indexes;
  6103. }; // TODO: use `extCssDoc` for caching of style block parser results
  6104. /**
  6105. * Parses CSS rule into rules data object:
  6106. * 1. Find the last `{` mark in the rule
  6107. * which supposed to be a divider between selector and style block.
  6108. * 2. Validates found string part before the `{` via selector parser; and if:
  6109. * - parsing failed – get the previous `{` in the rule,
  6110. * and validates a new rule part again [2];
  6111. * - parsing successful — saves a found rule part as selector and parses the style block.
  6112. *
  6113. * @param rawCssRule Single CSS rule to parse.
  6114. * @param extCssDoc ExtCssDocument which is used for selector ast caching.
  6115. *
  6116. * @returns Array of rules data which contains:
  6117. * - selector as string;
  6118. * - ast to query elements by;
  6119. * - map of styles to apply.
  6120. * @throws An error on invalid css rule syntax:
  6121. * - unsupported CSS features – comments and at-rules
  6122. * - invalid selector or style block.
  6123. */
  6124. const parseRule = (rawCssRule, extCssDoc) => {
  6125. var _rawRuleData$selector;
  6126. const cssRule = rawCssRule.trim();
  6127. if (
  6128. cssRule.includes(`${SLASH}${ASTERISK}`) &&
  6129. cssRule.includes(`${ASTERISK}${SLASH}`)
  6130. ) {
  6131. throw new Error(STYLE_ERROR_PREFIX.NO_COMMENT);
  6132. }
  6133. const leftCurlyBracketIndexes = getLeftCurlyBracketIndexes(cssRule); // rule with style block but no selector
  6134. // e.g. '{ display: none; }'
  6135. if (getFirst(leftCurlyBracketIndexes) === 0) {
  6136. throw new Error(NO_SELECTOR_ERROR_PREFIX);
  6137. }
  6138. let selectorData; // if rule has `{` but there is no `}`
  6139. if (
  6140. leftCurlyBracketIndexes.length > 0 &&
  6141. !cssRule.includes(BRACKET.CURLY.RIGHT)
  6142. ) {
  6143. throw new Error(
  6144. `${STYLE_ERROR_PREFIX.NO_STYLE} OR ${STYLE_ERROR_PREFIX.UNCLOSED_STYLE}`
  6145. );
  6146. }
  6147. if (
  6148. // if rule has no `{`
  6149. leftCurlyBracketIndexes.length === 0 || // or `}`
  6150. !cssRule.includes(BRACKET.CURLY.RIGHT)
  6151. ) {
  6152. try {
  6153. // the whole css rule considered as "selector part"
  6154. // which may contain :remove() pseudo-class
  6155. selectorData = parseSelectorRulePart(cssRule, extCssDoc);
  6156. if (selectorData.success) {
  6157. var _selectorData$stylesO;
  6158. // rule with no style block has valid :remove() pseudo-class
  6159. // which is parsed into "styles"
  6160. // e.g. 'div:remove()'
  6161. // but also it can be just selector with no styles
  6162. // e.g. 'div'
  6163. // which should not be considered as valid css rule
  6164. if (
  6165. ((_selectorData$stylesO = selectorData.stylesOfSelector) ===
  6166. null || _selectorData$stylesO === void 0
  6167. ? void 0
  6168. : _selectorData$stylesO.length) === 0
  6169. ) {
  6170. throw new Error(STYLE_ERROR_PREFIX.NO_STYLE_OR_REMOVE);
  6171. }
  6172. return {
  6173. selector: selectorData.selector.trim(),
  6174. ast: selectorData.ast,
  6175. rawStyles: selectorData.stylesOfSelector,
  6176. };
  6177. } else {
  6178. // not valid selector
  6179. throw new Error("Invalid selector");
  6180. }
  6181. } catch (e) {
  6182. throw new Error(getErrorMessage(e));
  6183. }
  6184. }
  6185. let selectorBuffer;
  6186. let styleBlockBuffer;
  6187. const rawRuleData = {
  6188. selector: "",
  6189. }; // css rule should be parsed from its end
  6190. for (let i = leftCurlyBracketIndexes.length - 1; i > -1; i -= 1) {
  6191. const index = leftCurlyBracketIndexes[i];
  6192. if (!index) {
  6193. throw new Error(
  6194. `Impossible to continue, no '{' to process for rule: '${cssRule}'`
  6195. );
  6196. } // selector is before `{`, style block is after it
  6197. selectorBuffer = cssRule.slice(0, index); // skip curly brackets
  6198. styleBlockBuffer = cssRule.slice(index + 1, cssRule.length - 1);
  6199. selectorData = parseSelectorRulePart(selectorBuffer, extCssDoc);
  6200. if (selectorData.success) {
  6201. var _rawRuleData$rawStyle;
  6202. // selector successfully parsed
  6203. rawRuleData.selector = selectorData.selector.trim();
  6204. rawRuleData.ast = selectorData.ast;
  6205. rawRuleData.rawStyles = selectorData.stylesOfSelector; // style block should be parsed
  6206. // TODO: add cache for style block parsing
  6207. const parsedStyles = parseStyleBlock(styleBlockBuffer);
  6208. (_rawRuleData$rawStyle = rawRuleData.rawStyles) === null ||
  6209. _rawRuleData$rawStyle === void 0
  6210. ? void 0
  6211. : _rawRuleData$rawStyle.push(...parsedStyles); // stop rule parsing
  6212. break;
  6213. } else {
  6214. // if selector was not parsed successfully
  6215. // continue with next index of `{`
  6216. continue;
  6217. }
  6218. }
  6219. if (
  6220. ((_rawRuleData$selector = rawRuleData.selector) === null ||
  6221. _rawRuleData$selector === void 0
  6222. ? void 0
  6223. : _rawRuleData$selector.length) === 0
  6224. ) {
  6225. // skip the rule as selector
  6226. throw new Error("Selector in not valid");
  6227. }
  6228. return rawRuleData;
  6229. };
  6230. /**
  6231. * Parses array of CSS rules into array of rules data objects.
  6232. * Invalid rules are skipped and not applied,
  6233. * and the errors are logged.
  6234. *
  6235. * @param rawCssRules Array of rules to parse.
  6236. * @param extCssDoc Needed for selector ast caching.
  6237. *
  6238. * @returns Array of parsed valid rules data.
  6239. */
  6240. const parseRules$1 = (rawCssRules, extCssDoc) => {
  6241. const rawResults = createRawResultsMap();
  6242. const warnings = []; // trim all rules and find unique ones
  6243. const uniqueRules = [...new Set(rawCssRules.map((r) => r.trim()))];
  6244. uniqueRules.forEach((rule) => {
  6245. try {
  6246. saveToRawResults(rawResults, parseRule(rule, extCssDoc));
  6247. } catch (e) {
  6248. // skip the invalid rule
  6249. const errorMessage = getErrorMessage(e);
  6250. warnings.push(`'${rule}' - error: '${errorMessage}'`);
  6251. }
  6252. }); // log info about skipped invalid rules
  6253. if (warnings.length > 0) {
  6254. logger.info(`Invalid rules:\n ${warnings.join("\n ")}`);
  6255. }
  6256. return combineRulesData(rawResults);
  6257. };
  6258. const REGEXP_DECLARATION_END = /[;}]/g;
  6259. const REGEXP_DECLARATION_DIVIDER = /[;:}]/g;
  6260. const REGEXP_NON_WHITESPACE = /\S/g;
  6261. /**
  6262. * Interface for stylesheet parser context.
  6263. */
  6264. /**
  6265. * Resets rule data buffer to init value after rule successfully collected.
  6266. *
  6267. * @param context Stylesheet parser context.
  6268. */
  6269. const restoreRuleAcc = (context) => {
  6270. context.rawRuleData = {
  6271. selector: "",
  6272. };
  6273. };
  6274. /**
  6275. * Parses cropped selector part found before `{` previously.
  6276. *
  6277. * @param context Stylesheet parser context.
  6278. * @param extCssDoc Needed for caching of selector ast.
  6279. *
  6280. * @returns Parsed validation data for cropped part of stylesheet which may be a selector.
  6281. * @throws An error on unsupported CSS features, e.g. at-rules.
  6282. */
  6283. const parseSelectorPart = (context, extCssDoc) => {
  6284. let selector = context.selectorBuffer.trim();
  6285. if (selector.startsWith(AT_RULE_MARKER)) {
  6286. throw new Error(`${NO_AT_RULE_ERROR_PREFIX}: '${selector}'.`);
  6287. }
  6288. let removeSelectorData;
  6289. try {
  6290. removeSelectorData = parseRemoveSelector(selector);
  6291. } catch (e) {
  6292. logger.error(getErrorMessage(e));
  6293. throw new Error(`${REMOVE_ERROR_PREFIX.INVALID_REMOVE}: '${selector}'`);
  6294. }
  6295. if (context.nextIndex === -1) {
  6296. if (selector === removeSelectorData.selector) {
  6297. // rule should have style or pseudo-class :remove()
  6298. throw new Error(
  6299. `${STYLE_ERROR_PREFIX.NO_STYLE_OR_REMOVE}: '${context.cssToParse}'`
  6300. );
  6301. } // stop parsing as there is no style declaration and selector parsed fine
  6302. context.cssToParse = "";
  6303. }
  6304. let stylesOfSelector = [];
  6305. let success = false;
  6306. let ast;
  6307. try {
  6308. selector = removeSelectorData.selector;
  6309. stylesOfSelector = removeSelectorData.stylesOfSelector; // validate found selector by parsing it to ast
  6310. // so if it is invalid error will be thrown
  6311. ast = extCssDoc.getSelectorAst(selector);
  6312. success = true;
  6313. } catch (e) {
  6314. success = false;
  6315. }
  6316. if (context.nextIndex > 0) {
  6317. // slice found valid selector part off
  6318. // and parse rest of stylesheet later
  6319. context.cssToParse = context.cssToParse.slice(context.nextIndex);
  6320. }
  6321. return {
  6322. success,
  6323. selector,
  6324. ast,
  6325. stylesOfSelector,
  6326. };
  6327. };
  6328. /**
  6329. * Recursively parses style declaration string into `Style`s.
  6330. *
  6331. * @param context Stylesheet parser context.
  6332. * @param styles Array of styles.
  6333. *
  6334. * @throws An error on invalid style declaration.
  6335. * @returns A number index of the next `}` in `this.cssToParse`.
  6336. */
  6337. const parseUntilClosingBracket = (context, styles) => {
  6338. // Expects ":", ";", and "}".
  6339. REGEXP_DECLARATION_DIVIDER.lastIndex = context.nextIndex;
  6340. let match = REGEXP_DECLARATION_DIVIDER.exec(context.cssToParse);
  6341. if (match === null) {
  6342. throw new Error(
  6343. `${STYLE_ERROR_PREFIX.INVALID_STYLE}: '${context.cssToParse}'`
  6344. );
  6345. }
  6346. let matchPos = match.index;
  6347. let matched = match[0];
  6348. if (matched === BRACKET.CURLY.RIGHT) {
  6349. const declarationChunk = context.cssToParse.slice(
  6350. context.nextIndex,
  6351. matchPos
  6352. );
  6353. if (declarationChunk.trim().length === 0) {
  6354. // empty style declaration
  6355. // e.g. 'div { }'
  6356. if (styles.length === 0) {
  6357. throw new Error(
  6358. `${STYLE_ERROR_PREFIX.NO_STYLE}: '${context.cssToParse}'`
  6359. );
  6360. } // else valid style parsed before it
  6361. // e.g. '{ display: none; }' -- position is after ';'
  6362. } else {
  6363. // closing curly bracket '}' is matched before colon ':'
  6364. // trimmed declarationChunk is not a space, between ';' and '}',
  6365. // e.g. 'visible }' in style '{ display: none; visible }' after part before ';' is parsed
  6366. throw new Error(
  6367. `${STYLE_ERROR_PREFIX.INVALID_STYLE}: '${context.cssToParse}'`
  6368. );
  6369. }
  6370. return matchPos;
  6371. }
  6372. if (matched === COLON) {
  6373. const colonIndex = matchPos; // Expects ";" and "}".
  6374. REGEXP_DECLARATION_END.lastIndex = colonIndex;
  6375. match = REGEXP_DECLARATION_END.exec(context.cssToParse);
  6376. if (match === null) {
  6377. throw new Error(
  6378. `${STYLE_ERROR_PREFIX.UNCLOSED_STYLE}: '${context.cssToParse}'`
  6379. );
  6380. }
  6381. matchPos = match.index;
  6382. matched = match[0]; // Populates the `styleMap` key-value map.
  6383. const property = context.cssToParse
  6384. .slice(context.nextIndex, colonIndex)
  6385. .trim();
  6386. if (property.length === 0) {
  6387. throw new Error(
  6388. `${STYLE_ERROR_PREFIX.NO_PROPERTY}: '${context.cssToParse}'`
  6389. );
  6390. }
  6391. const value = context.cssToParse.slice(colonIndex + 1, matchPos).trim();
  6392. if (value.length === 0) {
  6393. throw new Error(
  6394. `${STYLE_ERROR_PREFIX.NO_VALUE}: '${context.cssToParse}'`
  6395. );
  6396. }
  6397. styles.push({
  6398. property,
  6399. value,
  6400. }); // finish style parsing if '}' is found
  6401. // e.g. '{ display: none }' -- no ';' at the end of declaration
  6402. if (matched === BRACKET.CURLY.RIGHT) {
  6403. return matchPos;
  6404. }
  6405. } // matchPos is the position of the next ';'
  6406. // crop 'cssToParse' and re-run the loop
  6407. context.cssToParse = context.cssToParse.slice(matchPos + 1);
  6408. context.nextIndex = 0;
  6409. return parseUntilClosingBracket(context, styles); // Should be a subject of tail-call optimization.
  6410. };
  6411. /**
  6412. * Parses next style declaration part in stylesheet.
  6413. *
  6414. * @param context Stylesheet parser context.
  6415. *
  6416. * @returns Array of style data objects.
  6417. */
  6418. const parseNextStyle = (context) => {
  6419. const styles = [];
  6420. const styleEndPos = parseUntilClosingBracket(context, styles); // find next rule after the style declaration
  6421. REGEXP_NON_WHITESPACE.lastIndex = styleEndPos + 1;
  6422. const match = REGEXP_NON_WHITESPACE.exec(context.cssToParse);
  6423. if (match === null) {
  6424. context.cssToParse = "";
  6425. return styles;
  6426. }
  6427. const matchPos = match.index; // cut out matched style declaration for previous selector
  6428. context.cssToParse = context.cssToParse.slice(matchPos);
  6429. return styles;
  6430. };
  6431. /**
  6432. * Parses stylesheet of rules into rules data objects (non-recursively):
  6433. * 1. Iterates through stylesheet string.
  6434. * 2. Finds first `{` which can be style declaration start or part of selector.
  6435. * 3. Validates found string part via selector parser; and if:
  6436. * - it throws error — saves string part to buffer as part of selector,
  6437. * slice next stylesheet part to `{` [2] and validates again [3];
  6438. * - no error — saves found string part as selector and starts to parse styles (recursively).
  6439. *
  6440. * @param rawStylesheet Raw stylesheet as string.
  6441. * @param extCssDoc ExtCssDocument which uses cache while selectors parsing.
  6442. * @throws An error on unsupported CSS features, e.g. comments or invalid stylesheet syntax.
  6443. * @returns Array of rules data which contains:
  6444. * - selector as string;
  6445. * - ast to query elements by;
  6446. * - map of styles to apply.
  6447. */
  6448. const parseStylesheet = (rawStylesheet, extCssDoc) => {
  6449. const stylesheet = rawStylesheet.trim();
  6450. if (
  6451. stylesheet.includes(`${SLASH}${ASTERISK}`) &&
  6452. stylesheet.includes(`${ASTERISK}${SLASH}`)
  6453. ) {
  6454. throw new Error(
  6455. `${STYLE_ERROR_PREFIX.NO_COMMENT} in stylesheet: '${stylesheet}'`
  6456. );
  6457. }
  6458. const context = {
  6459. // any stylesheet should start with selector
  6460. isSelector: true,
  6461. // init value of parser position
  6462. nextIndex: 0,
  6463. // init value of cssToParse
  6464. cssToParse: stylesheet,
  6465. // buffer for collecting selector part
  6466. selectorBuffer: "",
  6467. // accumulator for rules
  6468. rawRuleData: {
  6469. selector: "",
  6470. },
  6471. };
  6472. const rawResults = createRawResultsMap();
  6473. let selectorData; // context.cssToParse is going to be cropped while its parsing
  6474. while (context.cssToParse) {
  6475. if (context.isSelector) {
  6476. // find index of first opening curly bracket
  6477. // which may mean start of style part and end of selector one
  6478. context.nextIndex = context.cssToParse.indexOf(BRACKET.CURLY.LEFT); // rule should not start with style, selector is required
  6479. // e.g. '{ display: none; }'
  6480. if (context.selectorBuffer.length === 0 && context.nextIndex === 0) {
  6481. throw new Error(
  6482. `${STYLE_ERROR_PREFIX.NO_SELECTOR}: '${context.cssToParse}'`
  6483. );
  6484. }
  6485. if (context.nextIndex === -1) {
  6486. // no style declaration in rule
  6487. // but rule still may contain :remove() pseudo-class
  6488. context.selectorBuffer = context.cssToParse;
  6489. } else {
  6490. // collect string parts before opening curly bracket
  6491. // until valid selector collected
  6492. context.selectorBuffer += context.cssToParse.slice(
  6493. 0,
  6494. context.nextIndex
  6495. );
  6496. }
  6497. selectorData = parseSelectorPart(context, extCssDoc);
  6498. if (selectorData.success) {
  6499. // selector successfully parsed
  6500. context.rawRuleData.selector = selectorData.selector.trim();
  6501. context.rawRuleData.ast = selectorData.ast;
  6502. context.rawRuleData.rawStyles = selectorData.stylesOfSelector;
  6503. context.isSelector = false; // save rule data if there is no style declaration
  6504. if (context.nextIndex === -1) {
  6505. saveToRawResults(rawResults, context.rawRuleData); // clean up ruleContext
  6506. restoreRuleAcc(context);
  6507. } else {
  6508. // skip the opening curly bracket at the start of style declaration part
  6509. context.nextIndex = 1;
  6510. context.selectorBuffer = "";
  6511. }
  6512. } else {
  6513. // if selector was not successfully parsed parseSelectorPart(), continue stylesheet parsing:
  6514. // save the found bracket to buffer and proceed to next loop iteration
  6515. context.selectorBuffer += BRACKET.CURLY.LEFT; // delete `{` from cssToParse
  6516. context.cssToParse = context.cssToParse.slice(1);
  6517. }
  6518. } else {
  6519. var _context$rawRuleData$;
  6520. // style declaration should be parsed
  6521. const parsedStyles = parseNextStyle(context); // styles can be parsed from selector part if it has :remove() pseudo-class
  6522. // e.g. '.banner:remove() { debug: true; }'
  6523. (_context$rawRuleData$ = context.rawRuleData.rawStyles) === null ||
  6524. _context$rawRuleData$ === void 0
  6525. ? void 0
  6526. : _context$rawRuleData$.push(...parsedStyles); // save rule data to results
  6527. saveToRawResults(rawResults, context.rawRuleData);
  6528. context.nextIndex = 0; // clean up ruleContext
  6529. restoreRuleAcc(context); // parse next rule selector after style successfully parsed
  6530. context.isSelector = true;
  6531. }
  6532. }
  6533. return combineRulesData(rawResults);
  6534. };
  6535. /**
  6536. * Checks whether passed `arg` is number type.
  6537. *
  6538. * @param arg Value to check.
  6539. *
  6540. * @returns True if `arg` is number and not NaN.
  6541. */
  6542. const isNumber = (arg) => {
  6543. return typeof arg === "number" && !Number.isNaN(arg);
  6544. };
  6545. /**
  6546. * The purpose of ThrottleWrapper is to throttle calls of the function
  6547. * that applies ExtendedCss rules. The reasoning here is that the function calls
  6548. * are triggered by MutationObserver and there may be many mutations in a short period of time.
  6549. * We do not want to apply rules on every mutation so we use this helper to make sure
  6550. * that there is only one call in the given amount of time.
  6551. */
  6552. class ThrottleWrapper {
  6553. /**
  6554. * Creates new ThrottleWrapper.
  6555. * The {@link callback} should be executed not more often than {@link ThrottleWrapper.THROTTLE_DELAY_MS}.
  6556. *
  6557. * @param callback The callback.
  6558. */
  6559. constructor(callback) {
  6560. this.callback = callback;
  6561. this.executeCallback = this.executeCallback.bind(this);
  6562. }
  6563. /**
  6564. * Calls the {@link callback} function and update bounded throttle wrapper properties.
  6565. */
  6566. executeCallback() {
  6567. this.lastRunTime = performance.now();
  6568. if (isNumber(this.timerId)) {
  6569. clearTimeout(this.timerId);
  6570. delete this.timerId;
  6571. }
  6572. this.callback();
  6573. }
  6574. /**
  6575. * Schedules the {@link executeCallback} function execution via setTimeout.
  6576. * It may triggered by MutationObserver job which may occur too ofter, so we limit the function execution:
  6577. *
  6578. * 1. If {@link timerId} is set, ignore the call, because the function is already scheduled to be executed;
  6579. *
  6580. * 2. If {@link lastRunTime} is set, we need to check the time elapsed time since the last call. If it is
  6581. * less than {@link ThrottleWrapper.THROTTLE_DELAY_MS}, we schedule the function execution after the remaining time.
  6582. *
  6583. * Otherwise, we execute the function asynchronously to ensure that it is executed
  6584. * in the correct order with respect to DOM events, by deferring its execution until after
  6585. * those tasks have completed.
  6586. */
  6587. run() {
  6588. if (isNumber(this.timerId)) {
  6589. // there is a pending execution scheduled
  6590. return;
  6591. }
  6592. if (isNumber(this.lastRunTime)) {
  6593. const elapsedTime = performance.now() - this.lastRunTime;
  6594. if (elapsedTime < ThrottleWrapper.THROTTLE_DELAY_MS) {
  6595. this.timerId = window.setTimeout(
  6596. this.executeCallback,
  6597. ThrottleWrapper.THROTTLE_DELAY_MS - elapsedTime
  6598. );
  6599. return;
  6600. }
  6601. }
  6602. /**
  6603. * We use `setTimeout` instead `requestAnimationFrame`
  6604. * here because requestAnimationFrame can be delayed for a long time
  6605. * when the browser saves battery or the engine is heavily loaded.
  6606. */
  6607. this.timerId = window.setTimeout(this.executeCallback);
  6608. }
  6609. }
  6610. _defineProperty(ThrottleWrapper, "THROTTLE_DELAY_MS", 150);
  6611. const LAST_EVENT_TIMEOUT_MS = 10;
  6612. const IGNORED_EVENTS = [
  6613. "mouseover",
  6614. "mouseleave",
  6615. "mouseenter",
  6616. "mouseout",
  6617. ];
  6618. const SUPPORTED_EVENTS = [
  6619. // keyboard events
  6620. "keydown",
  6621. "keypress",
  6622. "keyup",
  6623. // mouse events
  6624. "auxclick",
  6625. "click",
  6626. "contextmenu",
  6627. "dblclick",
  6628. "mousedown",
  6629. "mouseenter",
  6630. "mouseleave",
  6631. "mousemove",
  6632. "mouseover",
  6633. "mouseout",
  6634. "mouseup",
  6635. "pointerlockchange",
  6636. "pointerlockerror",
  6637. "select",
  6638. "wheel",
  6639. ]; // 'wheel' event makes scrolling in Safari twitchy
  6640. // https://github.com/AdguardTeam/ExtendedCss/issues/120
  6641. const SAFARI_PROBLEMATIC_EVENTS = ["wheel"];
  6642. /**
  6643. * We use EventTracker to track the event that is likely to cause the mutation.
  6644. * The problem is that we cannot use `window.event` directly from the mutation observer call
  6645. * as we're not in the event handler context anymore.
  6646. */
  6647. class EventTracker {
  6648. /**
  6649. * Creates new EventTracker.
  6650. */
  6651. constructor() {
  6652. _defineProperty(this, "getLastEventType", () => this.lastEventType);
  6653. _defineProperty(this, "getTimeSinceLastEvent", () => {
  6654. if (!this.lastEventTime) {
  6655. return null;
  6656. }
  6657. return Date.now() - this.lastEventTime;
  6658. });
  6659. this.trackedEvents = isSafariBrowser
  6660. ? SUPPORTED_EVENTS.filter(
  6661. (event) => !SAFARI_PROBLEMATIC_EVENTS.includes(event)
  6662. )
  6663. : SUPPORTED_EVENTS;
  6664. this.trackedEvents.forEach((eventName) => {
  6665. document.documentElement.addEventListener(
  6666. eventName,
  6667. this.trackEvent,
  6668. true
  6669. );
  6670. });
  6671. }
  6672. /**
  6673. * Callback for event listener for events tracking.
  6674. *
  6675. * @param event Any event.
  6676. */
  6677. trackEvent(event) {
  6678. this.lastEventType = event.type;
  6679. this.lastEventTime = Date.now();
  6680. }
  6681. /**
  6682. * Checks whether the last caught event should be ignored.
  6683. *
  6684. * @returns True if event should be ignored.
  6685. */
  6686. isIgnoredEventType() {
  6687. const lastEventType = this.getLastEventType();
  6688. const sinceLastEventTime = this.getTimeSinceLastEvent();
  6689. return (
  6690. !!lastEventType &&
  6691. IGNORED_EVENTS.includes(lastEventType) &&
  6692. !!sinceLastEventTime &&
  6693. sinceLastEventTime < LAST_EVENT_TIMEOUT_MS
  6694. );
  6695. }
  6696. /**
  6697. * Stops event tracking by removing event listener.
  6698. */
  6699. stopTracking() {
  6700. this.trackedEvents.forEach((eventName) => {
  6701. document.documentElement.removeEventListener(
  6702. eventName,
  6703. this.trackEvent,
  6704. true
  6705. );
  6706. });
  6707. }
  6708. }
  6709. /**
  6710. * We are trying to limit the number of callback calls by not calling it on all kind of "hover" events.
  6711. * The rationale behind this is that "hover" events often cause attributes modification,
  6712. * but re-applying extCSS rules will be useless as these attribute changes are usually transient.
  6713. *
  6714. * @param mutations DOM elements mutation records.
  6715. * @returns True if all mutations are about attributes changes, otherwise false.
  6716. */
  6717. function shouldIgnoreMutations(mutations) {
  6718. // ignore if all mutations are about attributes changes
  6719. return !mutations.some((m) => m.type !== "attributes");
  6720. }
  6721. /**
  6722. * Adds new {@link context.domMutationObserver} instance and connect it to document.
  6723. *
  6724. * @param context ExtendedCss context.
  6725. */
  6726. function observeDocument(context) {
  6727. if (context.isDomObserved) {
  6728. return;
  6729. } // enable dynamically added elements handling
  6730. context.isDomObserved = true;
  6731. context.domMutationObserver = new natives.MutationObserver(
  6732. (mutations) => {
  6733. if (!mutations || mutations.length === 0) {
  6734. return;
  6735. }
  6736. const eventTracker = new EventTracker();
  6737. if (
  6738. eventTracker.isIgnoredEventType() &&
  6739. shouldIgnoreMutations(mutations)
  6740. ) {
  6741. return;
  6742. } // save instance of EventTracker to context
  6743. // for removing its event listeners on disconnectDocument() while mainDisconnect()
  6744. context.eventTracker = eventTracker;
  6745. context.scheduler.run();
  6746. }
  6747. );
  6748. context.domMutationObserver.observe(document, {
  6749. childList: true,
  6750. subtree: true,
  6751. attributes: true,
  6752. attributeFilter: ["id", "class"],
  6753. });
  6754. }
  6755. /**
  6756. * Disconnect from {@link context.domMutationObserver}.
  6757. *
  6758. * @param context ExtendedCss context.
  6759. */
  6760. function disconnectDocument(context) {
  6761. if (!context.isDomObserved) {
  6762. return;
  6763. } // disable dynamically added elements handling
  6764. context.isDomObserved = false;
  6765. if (context.domMutationObserver) {
  6766. context.domMutationObserver.disconnect();
  6767. } // clean up event listeners
  6768. if (context.eventTracker) {
  6769. context.eventTracker.stopTracking();
  6770. }
  6771. }
  6772. const CONTENT_ATTR_PREFIX_REGEXP = /^("|')adguard.+?/;
  6773. /**
  6774. * Removes affectedElement.node from DOM.
  6775. *
  6776. * @param context ExtendedCss context.
  6777. * @param affectedElement Affected element.
  6778. */
  6779. const removeElement = (context, affectedElement) => {
  6780. const { node } = affectedElement;
  6781. affectedElement.removed = true;
  6782. const elementSelector = getElementSelectorPath(node); // check if the element has been already removed earlier
  6783. const elementRemovalsCounter =
  6784. context.removalsStatistic[elementSelector] || 0; // if removals attempts happened more than specified we do not try to remove node again
  6785. if (elementRemovalsCounter > MAX_STYLE_PROTECTION_COUNT) {
  6786. logger.error(
  6787. `ExtendedCss: infinite loop protection for selector: '${elementSelector}'`
  6788. );
  6789. return;
  6790. }
  6791. if (node.parentElement) {
  6792. node.parentElement.removeChild(node);
  6793. context.removalsStatistic[elementSelector] = elementRemovalsCounter + 1;
  6794. }
  6795. };
  6796. /**
  6797. * Sets style to the specified DOM node.
  6798. *
  6799. * @param node DOM element.
  6800. * @param style Style to set.
  6801. */
  6802. const setStyleToElement = (node, style) => {
  6803. if (!(node instanceof HTMLElement)) {
  6804. return;
  6805. }
  6806. Object.keys(style).forEach((prop) => {
  6807. // Apply this style only to existing properties
  6808. // We cannot use hasOwnProperty here (does not work in FF)
  6809. if (
  6810. typeof node.style.getPropertyValue(prop.toString()) !== "undefined"
  6811. ) {
  6812. let value = style[prop];
  6813. if (!value) {
  6814. return;
  6815. } // do not apply 'content' style given by tsurlfilter
  6816. // which is needed only for BeforeStyleAppliedCallback
  6817. if (
  6818. prop === CONTENT_CSS_PROPERTY &&
  6819. value.match(CONTENT_ATTR_PREFIX_REGEXP)
  6820. ) {
  6821. return;
  6822. } // First we should remove !important attribute (or it won't be applied')
  6823. value = removeSuffix(value.trim(), "!important").trim();
  6824. node.style.setProperty(prop, value, "important");
  6825. }
  6826. });
  6827. };
  6828. /**
  6829. * Checks the required properties of `affectedElement`
  6830. * **before** `beforeStyleApplied()` execution.
  6831. *
  6832. * @param affectedElement Affected element.
  6833. *
  6834. * @returns False if there is no `node` or `rules`
  6835. * or `rules` is not an array.
  6836. */
  6837. const isIAffectedElement = (affectedElement) => {
  6838. return (
  6839. "node" in affectedElement &&
  6840. "rules" in affectedElement &&
  6841. affectedElement.rules instanceof Array
  6842. );
  6843. };
  6844. /**
  6845. * Checks the required properties of `affectedElement`
  6846. * **after** `beforeStyleApplied()` execution.
  6847. * These properties are needed for proper internal usage.
  6848. *
  6849. * @param affectedElement Affected element.
  6850. *
  6851. * @returns False if there is no `node` or `rules`
  6852. * or `rules` is not an array.
  6853. */
  6854. const isAffectedElement = (affectedElement) => {
  6855. return (
  6856. "node" in affectedElement &&
  6857. "originalStyle" in affectedElement &&
  6858. "rules" in affectedElement &&
  6859. affectedElement.rules instanceof Array
  6860. );
  6861. };
  6862. /**
  6863. * Applies style to the specified DOM node.
  6864. *
  6865. * @param context ExtendedCss context.
  6866. * @param rawAffectedElement Object containing DOM node and rule to be applied.
  6867. *
  6868. * @throws An error if affectedElement has no style to apply.
  6869. */
  6870. const applyStyle = (context, rawAffectedElement) => {
  6871. if (rawAffectedElement.protectionObserver) {
  6872. // style is already applied and protected by the observer
  6873. return;
  6874. }
  6875. let affectedElement;
  6876. if (context.beforeStyleApplied) {
  6877. if (!isIAffectedElement(rawAffectedElement)) {
  6878. throw new Error(
  6879. "Returned IAffectedElement should have 'node' and 'rules' properties"
  6880. );
  6881. }
  6882. affectedElement = context.beforeStyleApplied(rawAffectedElement);
  6883. if (!affectedElement) {
  6884. throw new Error(
  6885. "Callback 'beforeStyleApplied' should return IAffectedElement"
  6886. );
  6887. }
  6888. } else {
  6889. affectedElement = rawAffectedElement;
  6890. }
  6891. if (!isAffectedElement(affectedElement)) {
  6892. throw new Error(
  6893. "Returned IAffectedElement should have 'node' and 'rules' properties"
  6894. );
  6895. }
  6896. const { node, rules } = affectedElement;
  6897. for (let i = 0; i < rules.length; i += 1) {
  6898. const rule = rules[i];
  6899. const selector =
  6900. rule === null || rule === void 0 ? void 0 : rule.selector;
  6901. const style = rule === null || rule === void 0 ? void 0 : rule.style;
  6902. const debug = rule === null || rule === void 0 ? void 0 : rule.debug; // rule may not have style to apply
  6903. // e.g. 'div:has(> a) { debug: true }' -> means no style to apply, and enable debug mode
  6904. if (style) {
  6905. if (style[REMOVE_PSEUDO_MARKER] === PSEUDO_PROPERTY_POSITIVE_VALUE) {
  6906. removeElement(context, affectedElement);
  6907. return;
  6908. }
  6909. setStyleToElement(node, style);
  6910. } else if (!debug) {
  6911. // but rule should not have both style and debug properties
  6912. throw new Error(
  6913. `No style declaration in rule for selector: '${selector}'`
  6914. );
  6915. }
  6916. }
  6917. };
  6918. /**
  6919. * Reverts style for the affected object.
  6920. *
  6921. * @param affectedElement Affected element.
  6922. */
  6923. const revertStyle = (affectedElement) => {
  6924. if (affectedElement.protectionObserver) {
  6925. affectedElement.protectionObserver.disconnect();
  6926. }
  6927. affectedElement.node.style.cssText = affectedElement.originalStyle;
  6928. };
  6929. /**
  6930. * ExtMutationObserver is a wrapper over regular MutationObserver with one additional function:
  6931. * it keeps track of the number of times we called the "ProtectionCallback".
  6932. *
  6933. * We use an instance of this to monitor styles added by ExtendedCss
  6934. * and to make sure these styles are recovered if the page script attempts to modify them.
  6935. *
  6936. * However, we want to avoid endless loops of modification if the page script repeatedly modifies the styles.
  6937. * So we keep track of the number of calls and observe() makes a decision
  6938. * whether to continue recovering the styles or not.
  6939. */
  6940. class ExtMutationObserver {
  6941. /**
  6942. * Extra property for keeping 'style fix counts'.
  6943. */
  6944. /**
  6945. * Creates new ExtMutationObserver.
  6946. *
  6947. * @param protectionCallback Callback which execution should be counted.
  6948. */
  6949. constructor(protectionCallback) {
  6950. this.styleProtectionCount = 0;
  6951. this.observer = new natives.MutationObserver((mutations) => {
  6952. if (!mutations.length) {
  6953. return;
  6954. }
  6955. this.styleProtectionCount += 1;
  6956. protectionCallback(mutations, this);
  6957. });
  6958. }
  6959. /**
  6960. * Starts to observe target element,
  6961. * prevents infinite loop of observing due to the limited number of times of callback runs.
  6962. *
  6963. * @param target Target to observe.
  6964. * @param options Mutation observer options.
  6965. */
  6966. observe(target, options) {
  6967. if (this.styleProtectionCount < MAX_STYLE_PROTECTION_COUNT) {
  6968. this.observer.observe(target, options);
  6969. } else {
  6970. logger.error("ExtendedCss: infinite loop protection for style");
  6971. }
  6972. }
  6973. /**
  6974. * Stops ExtMutationObserver from observing any mutations.
  6975. * Until the `observe()` is used again, `protectionCallback` will not be invoked.
  6976. */
  6977. disconnect() {
  6978. this.observer.disconnect();
  6979. }
  6980. }
  6981. const PROTECTION_OBSERVER_OPTIONS = {
  6982. attributes: true,
  6983. attributeOldValue: true,
  6984. attributeFilter: ["style"],
  6985. };
  6986. /**
  6987. * Creates MutationObserver protection callback.
  6988. *
  6989. * @param styles Styles data object.
  6990. *
  6991. * @returns Callback for styles protection.
  6992. */
  6993. const createProtectionCallback = (styles) => {
  6994. const protectionCallback = (mutations, extObserver) => {
  6995. if (!mutations[0]) {
  6996. return;
  6997. }
  6998. const { target } = mutations[0];
  6999. extObserver.disconnect();
  7000. styles.forEach((style) => {
  7001. setStyleToElement(target, style);
  7002. });
  7003. extObserver.observe(target, PROTECTION_OBSERVER_OPTIONS);
  7004. };
  7005. return protectionCallback;
  7006. };
  7007. /**
  7008. * Sets up a MutationObserver which protects style attributes from changes.
  7009. *
  7010. * @param node DOM node.
  7011. * @param rules Rule data objects.
  7012. * @returns Mutation observer used to protect attribute or null if there's nothing to protect.
  7013. */
  7014. const protectStyleAttribute = (node, rules) => {
  7015. if (!natives.MutationObserver) {
  7016. return null;
  7017. }
  7018. const styles = [];
  7019. rules.forEach((ruleData) => {
  7020. const { style } = ruleData; // some rules might have only debug property in style declaration
  7021. // e.g. 'div:has(> a) { debug: true }' -> parsed to boolean `ruleData.debug`
  7022. // so no style is fine, and here we should collect only valid styles to protect
  7023. if (style) {
  7024. styles.push(style);
  7025. }
  7026. });
  7027. const protectionObserver = new ExtMutationObserver(
  7028. createProtectionCallback(styles)
  7029. );
  7030. protectionObserver.observe(node, PROTECTION_OBSERVER_OPTIONS);
  7031. return protectionObserver;
  7032. };
  7033. const STATS_DECIMAL_DIGITS_COUNT = 4;
  7034. /**
  7035. * A helper class for applied rule stats.
  7036. */
  7037. class TimingStats {
  7038. /**
  7039. * Creates new TimingStats.
  7040. */
  7041. constructor() {
  7042. this.appliesTimings = [];
  7043. this.appliesCount = 0;
  7044. this.timingsSum = 0;
  7045. this.meanTiming = 0;
  7046. this.squaredSum = 0;
  7047. this.standardDeviation = 0;
  7048. }
  7049. /**
  7050. * Observe target element and mark observer as active.
  7051. *
  7052. * @param elapsedTimeMs Time in ms.
  7053. */
  7054. push(elapsedTimeMs) {
  7055. this.appliesTimings.push(elapsedTimeMs);
  7056. this.appliesCount += 1;
  7057. this.timingsSum += elapsedTimeMs;
  7058. this.meanTiming = this.timingsSum / this.appliesCount;
  7059. this.squaredSum += elapsedTimeMs * elapsedTimeMs;
  7060. this.standardDeviation = Math.sqrt(
  7061. this.squaredSum / this.appliesCount - Math.pow(this.meanTiming, 2)
  7062. );
  7063. }
  7064. }
  7065. /**
  7066. * Makes the timestamps more readable.
  7067. *
  7068. * @param timestamp Raw timestamp.
  7069. *
  7070. * @returns Fine-looking timestamps.
  7071. */
  7072. const beautifyTimingNumber = (timestamp) => {
  7073. return Number(timestamp.toFixed(STATS_DECIMAL_DIGITS_COUNT));
  7074. };
  7075. /**
  7076. * Improves timing stats readability.
  7077. *
  7078. * @param rawTimings Collected timings with raw timestamp.
  7079. *
  7080. * @returns Fine-looking timing stats.
  7081. */
  7082. const beautifyTimings = (rawTimings) => {
  7083. return {
  7084. appliesTimings: rawTimings.appliesTimings.map((t) =>
  7085. beautifyTimingNumber(t)
  7086. ),
  7087. appliesCount: beautifyTimingNumber(rawTimings.appliesCount),
  7088. timingsSum: beautifyTimingNumber(rawTimings.timingsSum),
  7089. meanTiming: beautifyTimingNumber(rawTimings.meanTiming),
  7090. standardDeviation: beautifyTimingNumber(rawTimings.standardDeviation),
  7091. };
  7092. };
  7093. /**
  7094. * Prints timing information if debugging mode is enabled.
  7095. *
  7096. * @param context ExtendedCss context.
  7097. */
  7098. const printTimingInfo = (context) => {
  7099. if (context.areTimingsPrinted) {
  7100. return;
  7101. }
  7102. context.areTimingsPrinted = true;
  7103. const timingsLogData = {};
  7104. context.parsedRules.forEach((ruleData) => {
  7105. if (ruleData.timingStats) {
  7106. const { selector, style, debug, matchedElements } = ruleData; // style declaration for some rules is parsed to debug property and no style to apply
  7107. // e.g. 'div:has(> a) { debug: true }'
  7108. if (!style && !debug) {
  7109. throw new Error(
  7110. `Rule should have style declaration for selector: '${selector}'`
  7111. );
  7112. }
  7113. const selectorData = {
  7114. selectorParsed: selector,
  7115. timings: beautifyTimings(ruleData.timingStats),
  7116. }; // `ruleData.style` may contain `remove` pseudo-property
  7117. // and make logs look better
  7118. if (
  7119. style &&
  7120. style[REMOVE_PSEUDO_MARKER] === PSEUDO_PROPERTY_POSITIVE_VALUE
  7121. ) {
  7122. selectorData.removed = true; // no matchedElements for such case as they are removed after ExtendedCss applied
  7123. } else {
  7124. selectorData.styleApplied = style || null;
  7125. selectorData.matchedElements = matchedElements;
  7126. }
  7127. timingsLogData[selector] = selectorData;
  7128. }
  7129. });
  7130. if (Object.keys(timingsLogData).length === 0) {
  7131. return;
  7132. } // add location.href to the message to distinguish frames
  7133. logger.info(
  7134. "[ExtendedCss] Timings in milliseconds for %o:\n%o",
  7135. window.location.href,
  7136. timingsLogData
  7137. );
  7138. };
  7139. /**
  7140. * Finds affectedElement object for the specified DOM node.
  7141. *
  7142. * @param affElements Array of affected elements — context.affectedElements.
  7143. * @param domNode DOM node.
  7144. * @returns Found affectedElement or undefined.
  7145. */
  7146. const findAffectedElement = (affElements, domNode) => {
  7147. return affElements.find((affEl) => affEl.node === domNode);
  7148. };
  7149. /**
  7150. * Applies specified rule and returns list of elements affected.
  7151. *
  7152. * @param context ExtendedCss context.
  7153. * @param ruleData Rule to apply.
  7154. * @returns List of elements affected by the rule.
  7155. */
  7156. const applyRule = (context, ruleData) => {
  7157. // debugging mode can be enabled in two ways:
  7158. // 1. for separate rules - by `{ debug: true; }`
  7159. // 2. for all rules simultaneously by:
  7160. // - `{ debug: global; }` in any rule
  7161. // - positive `debug` property in ExtCssConfiguration
  7162. const isDebuggingMode = !!ruleData.debug || context.debug;
  7163. let startTime;
  7164. if (isDebuggingMode) {
  7165. startTime = performance.now();
  7166. }
  7167. const { ast } = ruleData;
  7168. const nodes = []; // selector can be successfully parser into ast with no error
  7169. // but its applying by native Document.querySelectorAll() still may throw an error
  7170. // e.g. 'div[..banner]'
  7171. try {
  7172. nodes.push(...selectElementsByAst(ast));
  7173. } catch (e) {
  7174. // log the error only in debug mode
  7175. if (context.debug) {
  7176. logger.error(getErrorMessage(e));
  7177. }
  7178. }
  7179. nodes.forEach((node) => {
  7180. let affectedElement = findAffectedElement(
  7181. context.affectedElements,
  7182. node
  7183. );
  7184. if (affectedElement) {
  7185. affectedElement.rules.push(ruleData);
  7186. applyStyle(context, affectedElement);
  7187. } else {
  7188. // Applying style first time
  7189. const originalStyle = node.style.cssText;
  7190. affectedElement = {
  7191. node,
  7192. // affected DOM node
  7193. rules: [ruleData],
  7194. // rule to be applied
  7195. originalStyle,
  7196. // original node style
  7197. protectionObserver: null, // style attribute observer
  7198. };
  7199.  
  7200. applyStyle(context, affectedElement);
  7201. context.affectedElements.push(affectedElement);
  7202. }
  7203. });
  7204. if (isDebuggingMode && startTime) {
  7205. const elapsedTimeMs = performance.now() - startTime;
  7206. if (!ruleData.timingStats) {
  7207. ruleData.timingStats = new TimingStats();
  7208. }
  7209. ruleData.timingStats.push(elapsedTimeMs);
  7210. }
  7211. return nodes;
  7212. };
  7213. /**
  7214. * Applies filtering rules.
  7215. *
  7216. * @param context ExtendedCss context.
  7217. */
  7218. const applyRules = (context) => {
  7219. const newSelectedElements = []; // some rules could make call - selector.querySelectorAll() temporarily to change node id attribute
  7220. // this caused MutationObserver to call recursively
  7221. // https://github.com/AdguardTeam/ExtendedCss/issues/81
  7222. disconnectDocument(context);
  7223. context.parsedRules.forEach((ruleData) => {
  7224. const nodes = applyRule(context, ruleData);
  7225. Array.prototype.push.apply(newSelectedElements, nodes); // save matched elements to ruleData as linked to applied rule
  7226. // only for debugging purposes
  7227. if (ruleData.debug) {
  7228. ruleData.matchedElements = nodes;
  7229. }
  7230. }); // Now revert styles for elements which are no more affected
  7231. let affLength = context.affectedElements.length; // do nothing if there is no elements to process
  7232. while (affLength) {
  7233. const affectedElement = context.affectedElements[affLength - 1];
  7234. if (!affectedElement) {
  7235. break;
  7236. }
  7237. if (!newSelectedElements.includes(affectedElement.node)) {
  7238. // Time to revert style
  7239. revertStyle(affectedElement);
  7240. context.affectedElements.splice(affLength - 1, 1);
  7241. } else if (!affectedElement.removed) {
  7242. // Add style protection observer
  7243. // Protect "style" attribute from changes
  7244. if (!affectedElement.protectionObserver) {
  7245. affectedElement.protectionObserver = protectStyleAttribute(
  7246. affectedElement.node,
  7247. affectedElement.rules
  7248. );
  7249. }
  7250. }
  7251. affLength -= 1;
  7252. } // After styles are applied we can start observe again
  7253. observeDocument(context);
  7254. printTimingInfo(context);
  7255. };
  7256. /**
  7257. * Result of selector validation.
  7258. */
  7259. /**
  7260. * Main class of ExtendedCss lib.
  7261. *
  7262. * Parses css stylesheet with any selectors (passed to its argument as styleSheet),
  7263. * and guarantee its applying as mutation observer is used to prevent the restyling of needed elements by other scripts.
  7264. * This style protection is limited to 50 times to avoid infinite loop (MAX_STYLE_PROTECTION_COUNT).
  7265. * Our own ThrottleWrapper is used for styles applying to avoid too often lib reactions on page mutations.
  7266. *
  7267. * Constructor creates the instance of class which should be run be `apply()` method to apply the rules,
  7268. * and the applying can be stopped by `dispose()`.
  7269. *
  7270. * Can be used to select page elements by selector with `query()` method (similar to `Document.querySelectorAll()`),
  7271. * which does not require instance creating.
  7272. */
  7273. class ExtendedCss {
  7274. /**
  7275. * Creates new ExtendedCss.
  7276. *
  7277. * @param configuration ExtendedCss configuration.
  7278. */
  7279. constructor(configuration) {
  7280. if (!configuration) {
  7281. throw new Error("ExtendedCss configuration should be provided.");
  7282. }
  7283. this.applyRulesCallbackListener =
  7284. this.applyRulesCallbackListener.bind(this);
  7285. this.context = {
  7286. beforeStyleApplied: configuration.beforeStyleApplied,
  7287. debug: false,
  7288. affectedElements: [],
  7289. isDomObserved: false,
  7290. removalsStatistic: {},
  7291. parsedRules: [],
  7292. scheduler: new ThrottleWrapper(this.applyRulesCallbackListener),
  7293. }; // TODO: throw an error instead of logging and handle it in related products.
  7294. if (!isBrowserSupported()) {
  7295. logger.error("Browser is not supported by ExtendedCss");
  7296. return;
  7297. } // at least 'styleSheet' or 'cssRules' should be provided
  7298. if (!configuration.styleSheet && !configuration.cssRules) {
  7299. throw new Error(
  7300. "ExtendedCss configuration should have 'styleSheet' or 'cssRules' defined."
  7301. );
  7302. } // 'styleSheet' and 'cssRules' are optional
  7303. // and both can be provided at the same time
  7304. // so both should be parsed and applied in such case
  7305. if (configuration.styleSheet) {
  7306. // stylesheet parsing can fail on some invalid selectors
  7307. try {
  7308. this.context.parsedRules.push(
  7309. ...parseStylesheet(configuration.styleSheet, extCssDocument)
  7310. );
  7311. } catch (e) {
  7312. // eslint-disable-next-line max-len
  7313. throw new Error(
  7314. `Pass the rules as configuration.cssRules since configuration.styleSheet cannot be parsed because of: '${getErrorMessage(
  7315. e
  7316. )}'`
  7317. );
  7318. }
  7319. }
  7320. if (configuration.cssRules) {
  7321. this.context.parsedRules.push(
  7322. ...parseRules$1(configuration.cssRules, extCssDocument)
  7323. );
  7324. } // true if set in configuration
  7325. // or any rule in styleSheet has `debug: global`
  7326. this.context.debug =
  7327. configuration.debug ||
  7328. this.context.parsedRules.some((ruleData) => {
  7329. return ruleData.debug === DEBUG_PSEUDO_PROPERTY_GLOBAL_VALUE;
  7330. });
  7331. if (
  7332. this.context.beforeStyleApplied &&
  7333. typeof this.context.beforeStyleApplied !== "function"
  7334. ) {
  7335. // eslint-disable-next-line max-len
  7336. throw new Error(
  7337. `Invalid configuration. Type of 'beforeStyleApplied' should be a function, received: '${typeof this
  7338. .context.beforeStyleApplied}'`
  7339. );
  7340. }
  7341. }
  7342. /**
  7343. * Invokes {@link applyRules} function with current app context.
  7344. *
  7345. * This method is bound to the class instance in the constructor because it is called
  7346. * in {@link ThrottleWrapper} and on the DOMContentLoaded event.
  7347. */
  7348. applyRulesCallbackListener() {
  7349. applyRules(this.context);
  7350. }
  7351. /**
  7352. * Initializes ExtendedCss.
  7353. *
  7354. * Should be executed on page ASAP,
  7355. * otherwise the :contains() pseudo-class may work incorrectly.
  7356. */
  7357. init() {
  7358. /**
  7359. * Native Node textContent getter must be intercepted as soon as possible,
  7360. * and stored as it is needed for proper work of :contains() pseudo-class
  7361. * because DOM Node prototype 'textContent' property may be mocked.
  7362. *
  7363. * @see {@link https://github.com/AdguardTeam/ExtendedCss/issues/127}
  7364. */
  7365. nativeTextContent.setGetter();
  7366. }
  7367. /**
  7368. * Applies stylesheet rules on page.
  7369. */
  7370. apply() {
  7371. applyRules(this.context);
  7372. if (document.readyState !== "complete") {
  7373. document.addEventListener(
  7374. "DOMContentLoaded",
  7375. this.applyRulesCallbackListener,
  7376. false
  7377. );
  7378. }
  7379. }
  7380. /**
  7381. * Disposes ExtendedCss and removes our styles from matched elements.
  7382. */
  7383. dispose() {
  7384. disconnectDocument(this.context);
  7385. this.context.affectedElements.forEach((el) => {
  7386. revertStyle(el);
  7387. });
  7388. document.removeEventListener(
  7389. "DOMContentLoaded",
  7390. this.applyRulesCallbackListener,
  7391. false
  7392. );
  7393. }
  7394. /**
  7395. * Exposed for testing purposes only.
  7396. *
  7397. * @returns Array of AffectedElement data objects.
  7398. */
  7399. getAffectedElements() {
  7400. return this.context.affectedElements;
  7401. }
  7402. /**
  7403. * Returns a list of the document's elements that match the specified selector.
  7404. * Uses ExtCssDocument.querySelectorAll().
  7405. *
  7406. * @param selector Selector text.
  7407. * @param [noTiming=true] If true — do not print the timings to the console.
  7408. *
  7409. * @throws An error if selector is not valid.
  7410. * @returns A list of elements that match the selector.
  7411. */
  7412. static query(selector) {
  7413. let noTiming =
  7414. arguments.length > 1 && arguments[1] !== undefined
  7415. ? arguments[1]
  7416. : true;
  7417. if (typeof selector !== "string") {
  7418. throw new Error("Selector should be defined as a string.");
  7419. }
  7420. const start = performance.now();
  7421. try {
  7422. return extCssDocument.querySelectorAll(selector);
  7423. } finally {
  7424. const end = performance.now();
  7425. if (!noTiming) {
  7426. logger.info(
  7427. `[ExtendedCss] Elapsed: ${Math.round((end - start) * 1000)} μs.`
  7428. );
  7429. }
  7430. }
  7431. }
  7432. /**
  7433. * Validates selector.
  7434. *
  7435. * @param inputSelector Selector text to validate.
  7436. *
  7437. * @returns Result of selector validation.
  7438. */
  7439. static validate(inputSelector) {
  7440. try {
  7441. // ExtendedCss in general supports :remove() in selector
  7442. // but ExtendedCss.query() does not support it as it should be parsed by stylesheet parser.
  7443. // so for validation we have to handle selectors with `:remove()` in it
  7444. const { selector } = parseRemoveSelector(inputSelector);
  7445. ExtendedCss.query(selector);
  7446. return {
  7447. ok: true,
  7448. error: null,
  7449. };
  7450. } catch (e) {
  7451. // not valid input `selector` should be logged eventually
  7452. const error = `Error: Invalid selector: '${inputSelector}' -- ${getErrorMessage(
  7453. e
  7454. )}`;
  7455. return {
  7456. ok: false,
  7457. error,
  7458. };
  7459. }
  7460. }
  7461. }
  7462. function parseBRules() {
  7463. var _a;
  7464. return __awaiter(this, void 0, void 0, function* () {
  7465. data.appliedLevel = 0;
  7466. const brules =
  7467. (_a = yield values.brules()) !== null && _a !== void 0
  7468. ? _a
  7469. : defaultValues.brules;
  7470. brules.forEach((br) => {
  7471. const level = bRuleParser(br);
  7472. if (level > 0) data.bRules.push(br);
  7473. if (level > data.appliedLevel) data.appliedLevel = level;
  7474. });
  7475. });
  7476. }
  7477. function canApplyCss(type) {
  7478. return (
  7479. (data.appliedLevel & (type >= 2 ? 2 : 1)) == 0 &&
  7480. data[styleBoxes[type]].length > 0
  7481. );
  7482. }
  7483. function cleanRules() {
  7484. if (
  7485. confirm(`是否清空存储规则 ?
  7486.  
  7487. 如果要卸载脚本,点击 确定 以后不要刷新,也不要打开任何新页面,
  7488. (如果可以)清空脚本存储(全选,删除,填 {},保存),然后删除脚本`)
  7489. ) {
  7490. values.rules(null);
  7491. values.time(null);
  7492. values.etags(null);
  7493. values.brules(null);
  7494. getSavedHosts().then((saves) =>
  7495. saves.forEach((host) => values.css(null, host))
  7496. );
  7497. data.isClean = true;
  7498. gmMenu("update");
  7499. gmMenu("export");
  7500. gmMenu("count", () => location.reload());
  7501. }
  7502. }
  7503. function reportRecord() {
  7504. let text = "";
  7505. function pushRecord(css) {
  7506. const match = cssToAbp(css);
  7507. if (match === null) return;
  7508. const [item, type, sel] = match,
  7509. count =
  7510. type % 2 === 1
  7511. ? ExtendedCss.query(sel).length
  7512. : document.querySelectorAll(sel).length;
  7513. if (count > 0) {
  7514. text += `
  7515. ! 匹配元素数量: ${count}
  7516. ${item}
  7517. `;
  7518. }
  7519. }
  7520. data.bRules.forEach((br) => {
  7521. if (br.level > 0) {
  7522. text += `
  7523. ! 禁用${["", "通用", "特定", "所有"][br.level]}元素隐藏
  7524. ${br.rule}
  7525. `;
  7526. }
  7527. });
  7528. styleBoxes.forEach((box, i) => {
  7529. if (canApplyCss(i)) {
  7530. data[box]
  7531. .split("\n")
  7532. .filter((css, i, csss) => csss.indexOf(css) === i)
  7533. .forEach((css) => pushRecord(css));
  7534. }
  7535. });
  7536. if (text.length > 0) {
  7537. downUrl(
  7538. URL.createObjectURL(
  7539. new Blob([
  7540. `[Adblock Plus 2.0]
  7541. ! 应用地址:
  7542. ! ${location.href}
  7543. ${text}`,
  7544. ])
  7545. ),
  7546. `拦截报告_${location.hostname}.txt`
  7547. );
  7548. } else {
  7549. alert("这个页面没有任何规则生效");
  7550. }
  7551. }
  7552. function switchDisabledStat() {
  7553. values.black().then((disaList) => {
  7554. const disas = disaList !== null && disaList !== void 0 ? disaList : [];
  7555. data.disabled = !disas.includes(location.hostname);
  7556. if (data.disabled) {
  7557. disas.push(location.hostname);
  7558. } else {
  7559. disas.splice(disas.indexOf(location.hostname), 1);
  7560. }
  7561. values.black(disas).finally(() => location.reload());
  7562. });
  7563. }
  7564. function getCustomHash(saveHash) {
  7565. var _a;
  7566. return __awaiter(this, void 0, void 0, function* () {
  7567. {
  7568. if (location.protocol === "https:") {
  7569. const hash = new Uint32Array(
  7570. yield window.crypto.subtle.digest(
  7571. "SHA-1",
  7572. yield new Blob([data.customRules]).arrayBuffer()
  7573. )
  7574. ).toString();
  7575. if (saveHash) yield values.hash(hash);
  7576. return hash;
  7577. } else {
  7578. return (_a = yield values.hash()) !== null && _a !== void 0
  7579. ? _a
  7580. : defaultValues.hash;
  7581. }
  7582. }
  7583. });
  7584. }
  7585. function initRules(apply) {
  7586. var _a;
  7587. return __awaiter(this, void 0, void 0, function* () {
  7588. let abpRules = {};
  7589. data.receivedRules = "";
  7590. abpRules =
  7591. (_a = yield values.rules()) !== null && _a !== void 0
  7592. ? _a
  7593. : defaultValues.rules;
  7594. {
  7595. yield Promise.all(
  7596. preset.onlineRules.map((rule) =>
  7597. __awaiter(this, void 0, void 0, function* () {
  7598. const resRule = yield getRuleFromResource(rule.标识);
  7599. if (resRule && !abpRules[rule.标识])
  7600. abpRules[rule.标识] = resRule;
  7601. })
  7602. )
  7603. );
  7604. }
  7605. Object.keys(abpRules).forEach((name) => {
  7606. data.receivedRules += "\n" + abpRules[name];
  7607. });
  7608. data.allRules = data.customRules + data.receivedRules;
  7609. if (apply) yield splitRules();
  7610. });
  7611. }
  7612. function styleApplyExec(type) {
  7613. if (canApplyCss(type)) {
  7614. const csss = data[styleBoxes[type]];
  7615. new ExtendedCss({
  7616. styleSheet: csss
  7617. .replaceAll(/\/\*\s*\d.+?\s*\*\//g, "")
  7618. .replaceAll("\n", ""),
  7619. }).apply();
  7620. if (!(type % 2 == 1)) addStyle(csss);
  7621. }
  7622. }
  7623. function styleApply() {
  7624. return __awaiter(this, void 0, void 0, function* () {
  7625. {
  7626. yield parseBRules();
  7627. if (data.appliedLevel == 3) return;
  7628. }
  7629. for (let type = 0; type < 4; type++) styleApplyExec(type);
  7630. gmMenu("export", reportRecord);
  7631. });
  7632. }
  7633. function parseRules() {
  7634. return __awaiter(this, void 0, void 0, function* () {
  7635. function addRule(rule, box, last) {
  7636. const [full, selector, isStyle] = ruleToCss(
  7637. rule,
  7638. data.preset,
  7639. box >= 2 && last
  7640. );
  7641. const index = (box % 2) + (rule.generic ? 0 : 2);
  7642. const checkResult = ExtendedCss.validate(selector);
  7643. const typeError = isStyle && rule.type < 2;
  7644. if (checkResult.ok && !typeError) {
  7645. data[styleBoxes[index]] += full;
  7646. data.appliedCount++;
  7647. } else {
  7648. console.error(
  7649. "选择器检查错误:",
  7650. rule,
  7651. typeError || checkResult.error
  7652. );
  7653. }
  7654. }
  7655. styleBoxes.forEach((box) => {
  7656. data[box] = "";
  7657. });
  7658. data.appliedCount = 0;
  7659. [
  7660. data.styles,
  7661. data.extStyles,
  7662. data.selectors,
  7663. data.extSelectors,
  7664. ].forEach((r, t) => {
  7665. const sels = new Set();
  7666. r.white.forEach((obj) => !sels.has(obj.sel) && sels.add(obj.sel));
  7667. r.black
  7668. .filter((obj) => !sels.has(obj.sel) && sels.add(obj.sel))
  7669. .forEach((s, i, a) => addRule(s, t, i == a.length - 1));
  7670. });
  7671. yield gmMenu("count", cleanRules);
  7672. saveCss();
  7673. if (!data.saved) styleApply();
  7674. });
  7675. }
  7676. function splitRules() {
  7677. const bRuleSet = new Set(),
  7678. sels = new Set();
  7679. dataBoxes.forEach((box) => {
  7680. data[box] = makeRuleBox();
  7681. });
  7682. data.allRules.split("\n").forEach((rule) => {
  7683. if (isBasicRule(rule)) {
  7684. const brule = bRuleSpliter(rule);
  7685. if (brule) {
  7686. if (rule.match(/,?badfilter,?/)) {
  7687. bRuleSet.delete(brule);
  7688. } else {
  7689. bRuleSet.add(brule);
  7690. }
  7691. }
  7692. } else {
  7693. const ruleObj = ruleLoader(rule);
  7694. if (typeof ruleObj !== "undefined") {
  7695. if (ruleObj.black === "black" && sels.has(ruleObj.sel)) return;
  7696. if (ruleObj.black === "white" && !sels.has(ruleObj.sel))
  7697. sels.add(ruleObj.sel);
  7698. data[dataBoxes[ruleObj.type]][ruleObj.black].push(ruleObj);
  7699. }
  7700. }
  7701. });
  7702. {
  7703. const bRules = [];
  7704. bRuleSet.forEach((brule) => bRules.push(brule));
  7705. values.brules(bRules);
  7706. }
  7707. return parseRules();
  7708. }
  7709. function makeInitMenu() {
  7710. return __awaiter(this, void 0, void 0, function* () {
  7711. yield gmMenu("count", cleanRules);
  7712. {
  7713. yield gmMenu("update", () => {
  7714. performUpdate(true).then(() => {
  7715. location.reload();
  7716. });
  7717. });
  7718. }
  7719. });
  7720. }
  7721. function extrEtag(resp) {
  7722. var _a, _b, _c;
  7723. const etag = getEtag(
  7724. typeof (resp === null || resp === void 0 ? void 0 : resp.headers) ==
  7725. "object"
  7726. ? // 海阔世界
  7727. (_b =
  7728. (_a =
  7729. resp === null || resp === void 0 ? void 0 : resp.headers) ===
  7730. null || _a === void 0
  7731. ? void 0
  7732. : _a.etag) === null || _b === void 0
  7733. ? void 0
  7734. : _b[0]
  7735. : typeof (resp === null || resp === void 0
  7736. ? void 0
  7737. : resp.responseHeaders) == "string"
  7738. ? // Tampermonkey
  7739. resp === null || resp === void 0
  7740. ? void 0
  7741. : resp.responseHeaders
  7742. : // Appara
  7743. (_c =
  7744. resp === null || resp === void 0
  7745. ? void 0
  7746. : resp.getAllResponseHeaders) === null || _c === void 0
  7747. ? void 0
  7748. : _c.call(resp)
  7749. );
  7750. return etag;
  7751. }
  7752. function storeRule(rule, resp) {
  7753. var _a, _c;
  7754. return __awaiter(this, void 0, void 0, function* () {
  7755. let savedRules = {};
  7756. savedRules =
  7757. (_a = yield values.rules()) !== null && _a !== void 0
  7758. ? _a
  7759. : defaultValues.rules;
  7760. if (resp.responseText) {
  7761. let parsed = resp.responseText;
  7762. if (rule.筛选后存储) {
  7763. parsed = resp.responseText
  7764. .split("\n")
  7765. .filter((rule) => CRRE.test(rule) || isBasicRule(rule))
  7766. .join("\n");
  7767. }
  7768. savedRules[rule.标识] = parsed;
  7769. {
  7770. yield values.rules(savedRules);
  7771. if (savedRules[rule.标识].length !== 0) {
  7772. const etag = extrEtag(resp),
  7773. savedEtags =
  7774. (_c = yield values.etags()) !== null && _c !== void 0
  7775. ? _c
  7776. : defaultValues.etags;
  7777. if (etag) {
  7778. savedEtags[rule.标识] = etag;
  7779. yield values.etags(savedEtags);
  7780. }
  7781. }
  7782. }
  7783. data.receivedRules += "\n" + savedRules[rule.标识];
  7784. }
  7785. return;
  7786. });
  7787. }
  7788. function fetchRuleBody(rule) {
  7789. var _a;
  7790. return __awaiter(this, void 0, void 0, function* () {
  7791. const url = addTimeParam(rule.地址);
  7792. const getResp = yield promiseXhr({
  7793. method: "GET",
  7794. responseType: "text",
  7795. url,
  7796. }).catch((error) => {
  7797. console.error("规则: ", url, " 下载错误: ", error);
  7798. });
  7799. if (
  7800. (_a =
  7801. getResp === null || getResp === void 0
  7802. ? void 0
  7803. : getResp.responseText) === null || _a === void 0
  7804. ? void 0
  7805. : _a.length
  7806. ) {
  7807. yield storeRule(rule, getResp);
  7808. return true;
  7809. } else return false;
  7810. });
  7811. }
  7812. function fetchRuleGet(resp, rule) {
  7813. var _a;
  7814. return __awaiter(this, void 0, void 0, function* () {
  7815. const etag = extrEtag(resp),
  7816. savedEtags = yield values.etags();
  7817. if (
  7818. (_a =
  7819. resp === null || resp === void 0 ? void 0 : resp.responseText) ===
  7820. null || _a === void 0
  7821. ? void 0
  7822. : _a.length
  7823. ) {
  7824. yield storeRule(rule, resp);
  7825. if (
  7826. etag !==
  7827. (savedEtags === null || savedEtags === void 0
  7828. ? void 0
  7829. : savedEtags[rule.标识])
  7830. ) {
  7831. return;
  7832. } else {
  7833. return Promise.reject("ETag 一致");
  7834. }
  7835. } else {
  7836. if (
  7837. etag !==
  7838. (savedEtags === null || savedEtags === void 0
  7839. ? void 0
  7840. : savedEtags[rule.标识])
  7841. ) {
  7842. if (yield fetchRuleBody(rule)) {
  7843. return;
  7844. } else {
  7845. return Promise.reject("GET 失败");
  7846. }
  7847. } else return Promise.reject("ETag 一致");
  7848. }
  7849. });
  7850. }
  7851. function fetchRule(rule) {
  7852. var _a;
  7853. return __awaiter(this, void 0, void 0, function* () {
  7854. let headRespError = {};
  7855. const url = addTimeParam(rule.地址);
  7856. const headResp = yield promiseXhr({
  7857. method: "HEAD",
  7858. responseType: "text",
  7859. url,
  7860. }).catch((error) => {
  7861. headRespError = error;
  7862. console.error("规则: ", url, " HEAD 错误: ", error);
  7863. });
  7864. if (!headResp) {
  7865. // Via HEAD 会超时,但可以得到 ETag
  7866. if (
  7867. (_a =
  7868. headRespError === null || headRespError === void 0
  7869. ? void 0
  7870. : headRespError.resp) === null || _a === void 0
  7871. ? void 0
  7872. : _a.responseHeaders
  7873. ) {
  7874. return yield fetchRuleGet(headRespError.resp, rule);
  7875. } else {
  7876. return Promise.reject("HEAD 失败");
  7877. }
  7878. } else {
  7879. return yield fetchRuleGet(headResp, rule);
  7880. }
  7881. });
  7882. }
  7883. function fetchRules() {
  7884. return __awaiter(this, void 0, void 0, function* () {
  7885. let hasUpdate = preset.onlineRules.length;
  7886. data.updating = true;
  7887. yield gmMenu("update", () => void 0);
  7888. for (const rule of preset.onlineRules) {
  7889. if (rule.在线更新) {
  7890. yield fetchRule(rule).catch((error) => {
  7891. console.error("获取规则 ", rule, " 发生错误: ", error);
  7892. hasUpdate--;
  7893. });
  7894. } else {
  7895. hasUpdate--;
  7896. }
  7897. }
  7898. values.time(new Date().toLocaleString("zh-CN"));
  7899. data.updating = false;
  7900. yield makeInitMenu();
  7901. if (hasUpdate > 0) {
  7902. yield Promise.all(
  7903. (yield getSavedHosts()).map((host) =>
  7904. __awaiter(this, void 0, void 0, function* () {
  7905. if (host === location.hostname) {
  7906. initRules(true);
  7907. } else {
  7908. const save = yield values.css(void 0, host);
  7909. if (save) {
  7910. save.needUpdate = true;
  7911. yield values.css(save, host);
  7912. }
  7913. }
  7914. })
  7915. )
  7916. );
  7917. }
  7918. });
  7919. }
  7920. function performUpdate(force) {
  7921. var _b;
  7922. return __awaiter(this, void 0, void 0, function* () {
  7923. if (data.isFrame) return Promise.reject();
  7924. return force ||
  7925. new Date(
  7926. (_b = yield values.time()) !== null && _b !== void 0
  7927. ? _b
  7928. : defaultValues.time
  7929. ).getDate() !== new Date().getDate()
  7930. ? fetchRules()
  7931. : Promise.resolve();
  7932. });
  7933. }
  7934. function main() {
  7935. var _a, _b;
  7936. return __awaiter(this, void 0, void 0, function* () {
  7937. if (!location.protocol.startsWith("http")) return;
  7938. // 初始化 data
  7939. data.disabled =
  7940. (_b =
  7941. (_a = yield values.black()) === null || _a === void 0
  7942. ? void 0
  7943. : _a.includes(location.hostname)) !== null && _b !== void 0
  7944. ? _b
  7945. : false;
  7946. data.preset = yield getUserConfig("css");
  7947. data.timeout = yield getUserConfig("timeout");
  7948. data.tryCount = yield getUserConfig("tryCount");
  7949. data.tryTimeout = yield getUserConfig("tryTimeout");
  7950. data.headTimeout = yield getUserConfig("headTimeout");
  7951. let finish = false;
  7952. gmMenu("disable", switchDisabledStat);
  7953. if (data.disabled) {
  7954. gmMenu("count", cleanRules);
  7955. return;
  7956. }
  7957. if (yield getSavedHosts(location.hostname)) yield readCss();
  7958. const hash = yield getCustomHash(false);
  7959. saved: {
  7960. yield makeInitMenu();
  7961. if ((yield values.hash()) !== hash) {
  7962. yield getCustomHash(true);
  7963. yield initRules(true);
  7964. break saved;
  7965. }
  7966. if (data.saved) {
  7967. styleApply();
  7968. if (!data.update) break saved;
  7969. }
  7970. yield initRules(false);
  7971. if (data.receivedRules.length === 0) {
  7972. yield performUpdate(true);
  7973. yield gmMenu("count");
  7974. yield initRules(true);
  7975. finish = true;
  7976. } else yield splitRules();
  7977. }
  7978. if (!finish) {
  7979. try {
  7980. yield performUpdate(false);
  7981. } catch (_error) {
  7982. console.warn("iframe: ", location.href, " 取消更新");
  7983. }
  7984. }
  7985. });
  7986. }
  7987. {
  7988. runOnce(data.mutex, main);
  7989. }
  7990. })($presets, $polyfills);
  7991. })();