套壳油猴的广告拦截脚本

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

目前为 2024-02-04 提交的版本。查看 最新版本

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