套壳油猴的广告拦截脚本

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

目前为 2024-05-09 提交的版本。查看 最新版本

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