@tokioapp/adblock 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +72 -2
  3. package/THIRD_PARTY_NOTICES.md +50 -0
  4. package/dist/content/cosmetics.d.ts +22 -0
  5. package/dist/content/cosmetics.js +173 -0
  6. package/dist/content/mainWorld.d.ts +8 -0
  7. package/dist/content/mainWorld.js +10 -0
  8. package/dist/content/preload.d.ts +1 -0
  9. package/dist/content/preload.js +34 -0
  10. package/dist/content/procedural.d.ts +19 -0
  11. package/dist/content/procedural.js +212 -0
  12. package/dist/cosmetic/engine.d.ts +95 -0
  13. package/dist/cosmetic/engine.js +268 -0
  14. package/dist/electron/blocker.d.ts +84 -0
  15. package/dist/electron/blocker.js +320 -0
  16. package/dist/electron/channels.d.ts +10 -0
  17. package/dist/electron/channels.js +6 -0
  18. package/dist/electron/scheme.d.ts +21 -0
  19. package/dist/electron/scheme.js +21 -0
  20. package/dist/engine.d.ts +86 -0
  21. package/dist/engine.js +163 -0
  22. package/dist/index.d.ts +13 -0
  23. package/dist/index.js +12 -0
  24. package/dist/lists/defaults.d.ts +6 -0
  25. package/dist/lists/defaults.js +59 -0
  26. package/dist/lists/manager.d.ts +86 -0
  27. package/dist/lists/manager.js +154 -0
  28. package/dist/lists/preprocessor.d.ts +21 -0
  29. package/dist/lists/preprocessor.js +152 -0
  30. package/dist/lists/storage.d.ts +37 -0
  31. package/dist/lists/storage.js +66 -0
  32. package/dist/network/engine.d.ts +105 -0
  33. package/dist/network/engine.js +431 -0
  34. package/dist/network/filterIndex.d.ts +40 -0
  35. package/dist/network/filterIndex.js +343 -0
  36. package/dist/network/modifiers.d.ts +23 -0
  37. package/dist/network/modifiers.js +192 -0
  38. package/dist/network/pattern.d.ts +7 -0
  39. package/dist/network/pattern.js +145 -0
  40. package/dist/network/request.d.ts +50 -0
  41. package/dist/network/request.js +136 -0
  42. package/dist/network/tokens.d.ts +5 -0
  43. package/dist/network/tokens.js +150 -0
  44. package/dist/parser/cosmetic.d.ts +21 -0
  45. package/dist/parser/cosmetic.js +171 -0
  46. package/dist/parser/hosts.d.ts +20 -0
  47. package/dist/parser/hosts.js +143 -0
  48. package/dist/parser/index.d.ts +40 -0
  49. package/dist/parser/index.js +158 -0
  50. package/dist/parser/network.d.ts +6 -0
  51. package/dist/parser/network.js +474 -0
  52. package/dist/parser/selector.d.ts +25 -0
  53. package/dist/parser/selector.js +522 -0
  54. package/dist/parser/types.d.ts +175 -0
  55. package/dist/parser/types.js +75 -0
  56. package/dist/preload.cjs +1988 -0
  57. package/dist/psl/psl.d.ts +32 -0
  58. package/dist/psl/psl.js +119 -0
  59. package/dist/resources/binary.d.ts +9 -0
  60. package/dist/resources/binary.js +54 -0
  61. package/dist/resources/defusers.d.ts +29 -0
  62. package/dist/resources/defusers.js +180 -0
  63. package/dist/resources/documents.d.ts +12 -0
  64. package/dist/resources/documents.js +56 -0
  65. package/dist/resources/ima.d.ts +6 -0
  66. package/dist/resources/ima.js +313 -0
  67. package/dist/resources/index.d.ts +14 -0
  68. package/dist/resources/index.js +85 -0
  69. package/dist/resources/surrogates.d.ts +30 -0
  70. package/dist/resources/surrogates.js +486 -0
  71. package/dist/scriptlets/abort.d.ts +5 -0
  72. package/dist/scriptlets/abort.js +97 -0
  73. package/dist/scriptlets/dom/attributes.d.ts +5 -0
  74. package/dist/scriptlets/dom/attributes.js +92 -0
  75. package/dist/scriptlets/dom/click.d.ts +2 -0
  76. package/dist/scriptlets/dom/click.js +107 -0
  77. package/dist/scriptlets/dom/cookies.d.ts +16 -0
  78. package/dist/scriptlets/dom/cookies.js +194 -0
  79. package/dist/scriptlets/dom/createHtml.d.ts +2 -0
  80. package/dist/scriptlets/dom/createHtml.js +27 -0
  81. package/dist/scriptlets/dom/dialogs.d.ts +3 -0
  82. package/dist/scriptlets/dom/dialogs.js +21 -0
  83. package/dist/scriptlets/dom/hrefSanitizer.d.ts +2 -0
  84. package/dist/scriptlets/dom/hrefSanitizer.js +91 -0
  85. package/dist/scriptlets/dom/index.d.ts +3 -0
  86. package/dist/scriptlets/dom/index.js +38 -0
  87. package/dist/scriptlets/dom/navigation.d.ts +5 -0
  88. package/dist/scriptlets/dom/navigation.js +60 -0
  89. package/dist/scriptlets/dom/nodeText.d.ts +3 -0
  90. package/dist/scriptlets/dom/nodeText.js +98 -0
  91. package/dist/scriptlets/dom/spoofCss.d.ts +2 -0
  92. package/dist/scriptlets/dom/spoofCss.js +58 -0
  93. package/dist/scriptlets/dom/storage.d.ts +5 -0
  94. package/dist/scriptlets/dom/storage.js +50 -0
  95. package/dist/scriptlets/dom/watch.d.ts +8 -0
  96. package/dist/scriptlets/dom/watch.js +41 -0
  97. package/dist/scriptlets/events.d.ts +2 -0
  98. package/dist/scriptlets/events.js +42 -0
  99. package/dist/scriptlets/helpers.d.ts +58 -0
  100. package/dist/scriptlets/helpers.js +206 -0
  101. package/dist/scriptlets/index.d.ts +6 -0
  102. package/dist/scriptlets/index.js +47 -0
  103. package/dist/scriptlets/network/edit.d.ts +9 -0
  104. package/dist/scriptlets/network/edit.js +104 -0
  105. package/dist/scriptlets/network/eval.d.ts +3 -0
  106. package/dist/scriptlets/network/eval.js +22 -0
  107. package/dist/scriptlets/network/fetch.d.ts +10 -0
  108. package/dist/scriptlets/network/fetch.js +145 -0
  109. package/dist/scriptlets/network/index.d.ts +3 -0
  110. package/dist/scriptlets/network/index.js +43 -0
  111. package/dist/scriptlets/network/jsonPath.d.ts +13 -0
  112. package/dist/scriptlets/network/jsonPath.js +482 -0
  113. package/dist/scriptlets/network/media.d.ts +3 -0
  114. package/dist/scriptlets/network/media.js +97 -0
  115. package/dist/scriptlets/network/methods.d.ts +5 -0
  116. package/dist/scriptlets/network/methods.js +139 -0
  117. package/dist/scriptlets/network/prune.d.ts +13 -0
  118. package/dist/scriptlets/network/prune.js +194 -0
  119. package/dist/scriptlets/network/rendering.d.ts +4 -0
  120. package/dist/scriptlets/network/rendering.js +46 -0
  121. package/dist/scriptlets/network/replace.d.ts +5 -0
  122. package/dist/scriptlets/network/replace.js +168 -0
  123. package/dist/scriptlets/network/request.d.ts +19 -0
  124. package/dist/scriptlets/network/request.js +124 -0
  125. package/dist/scriptlets/network/util.d.ts +19 -0
  126. package/dist/scriptlets/network/util.js +80 -0
  127. package/dist/scriptlets/network/webrtc.d.ts +3 -0
  128. package/dist/scriptlets/network/webrtc.js +62 -0
  129. package/dist/scriptlets/network/windowOpen.d.ts +2 -0
  130. package/dist/scriptlets/network/windowOpen.js +28 -0
  131. package/dist/scriptlets/network/xhr.d.ts +9 -0
  132. package/dist/scriptlets/network/xhr.js +177 -0
  133. package/dist/scriptlets/runner.d.ts +8 -0
  134. package/dist/scriptlets/runner.js +19 -0
  135. package/dist/scriptlets/setConstant.d.ts +5 -0
  136. package/dist/scriptlets/setConstant.js +117 -0
  137. package/dist/scriptlets/timers.d.ts +5 -0
  138. package/dist/scriptlets/timers.js +66 -0
  139. package/dist/scriptlets/types.d.ts +32 -0
  140. package/dist/scriptlets/types.js +1 -0
  141. package/dist/util.d.ts +5 -0
  142. package/dist/util.js +16 -0
  143. package/package.json +83 -4
@@ -0,0 +1,107 @@
1
+ import { matcher, parseRegex } from "../helpers.js";
2
+ import { readCookies } from "./cookies.js";
3
+ /** The element a directive names: a selector, `xpath:…`, `>>>` into shadow roots. */
4
+ function find(directive) {
5
+ if (directive.startsWith("xpath:")) {
6
+ const node = document.evaluate(directive.slice(6), document, null, XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue;
7
+ return node instanceof Element ? node : null;
8
+ }
9
+ let root = document;
10
+ let found = null;
11
+ for (const part of directive.split(">>>")) {
12
+ found = root?.querySelector(part.trim()) ?? null;
13
+ root = found?.shadowRoot ?? null;
14
+ }
15
+ return found;
16
+ }
17
+ function isVisible(element) {
18
+ return element.getClientRects().length > 0;
19
+ }
20
+ /**
21
+ * Whether the page's cookies or local storage meet one `cookie:key[=value]`
22
+ * or `localStorage:key[=value]` condition. A regex is tested against each
23
+ * `key=value`; `!` wants no match.
24
+ */
25
+ function meets(condition) {
26
+ const negated = condition.startsWith("!");
27
+ const match = /^(cookie|localStorage):(.+)$/.exec(negated ? condition.slice(1) : condition);
28
+ if (match === null)
29
+ return false;
30
+ let pairs;
31
+ try {
32
+ pairs =
33
+ match[1] === "cookie"
34
+ ? readCookies()
35
+ : Object.keys(localStorage).map((key) => [
36
+ key,
37
+ localStorage.getItem(key) ?? "",
38
+ ]);
39
+ }
40
+ catch {
41
+ pairs = [];
42
+ }
43
+ const test = match[2];
44
+ const equals = test.indexOf("=");
45
+ const matches = parseRegex(test) === undefined
46
+ ? ([key, value]) => equals === -1
47
+ ? key === test
48
+ : key === test.slice(0, equals) && value === test.slice(equals + 1)
49
+ : ([key, value]) => matcher(test)(`${key}=${value}`);
50
+ const found = pairs.some(matches);
51
+ return found !== negated;
52
+ }
53
+ export const trustedClickElement = {
54
+ name: "trusted-click-element",
55
+ trusted: true,
56
+ run(list = "", conditions = "", delay = "") {
57
+ const directives = list
58
+ .split(",")
59
+ .map((one) => one.trim())
60
+ .filter((one) => one !== "");
61
+ if (directives.length === 0)
62
+ return;
63
+ const start = () => {
64
+ if (!conditions
65
+ .split(",")
66
+ .map((one) => one.trim())
67
+ .filter((one) => one !== "")
68
+ .every(meets)) {
69
+ return;
70
+ }
71
+ const deadline = Date.now() + 10_000;
72
+ const next = (index) => {
73
+ const directive = directives[index];
74
+ if (directive === undefined || Date.now() > deadline)
75
+ return;
76
+ if (/^\d+$/.test(directive)) {
77
+ setTimeout(() => next(index + 1), Number(directive));
78
+ return;
79
+ }
80
+ const visible = directive.startsWith("when-visible:");
81
+ let element;
82
+ try {
83
+ element = find(visible ? directive.slice(13) : directive);
84
+ }
85
+ catch {
86
+ return;
87
+ }
88
+ if (element === null || (visible && !isVisible(element))) {
89
+ // shortcut: polls; an observer would click sooner on busy pages.
90
+ setTimeout(() => next(index), 100);
91
+ return;
92
+ }
93
+ if (element instanceof HTMLElement)
94
+ element.click();
95
+ else
96
+ element.dispatchEvent(new MouseEvent("click", { bubbles: true }));
97
+ next(index + 1);
98
+ };
99
+ next(0);
100
+ };
101
+ const ms = Number(delay);
102
+ if (ms > 0)
103
+ setTimeout(start, ms);
104
+ else
105
+ start();
106
+ },
107
+ };
@@ -0,0 +1,16 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ /** The page's cookies, as name and value pairs. */
3
+ export declare function readCookies(): [string, string][];
4
+ /** Whether a token like `reload, 1` is on. */
5
+ export declare function isOn(value: string | undefined): boolean;
6
+ /** `$now$`, `$currentDate$` and `$currentISODate$`, anywhere in the text. */
7
+ export declare function withDates(text: string): string;
8
+ /** One of the values `set-cookie` may set: a small integer or a constant in any case. */
9
+ export declare function isSafeCookieValue(value: string): boolean;
10
+ /** The value inside double quotes, or the value itself. */
11
+ export declare function unquoted(value: string): string;
12
+ export declare const removeCookie: Scriptlet;
13
+ export declare const setCookieScriptlet: Scriptlet;
14
+ export declare const setCookieReload: Scriptlet;
15
+ export declare const trustedSetCookieScriptlet: Scriptlet;
16
+ export declare const trustedSetCookieReload: Scriptlet;
@@ -0,0 +1,194 @@
1
+ import { matcher, parseRegex, tokens } from "../helpers.js";
2
+ const { apply } = Reflect;
3
+ // The page may replace `document.cookie` with its own accessor. (There is
4
+ // no Document when the main process loads this file for the names.)
5
+ const cookieAccessor = typeof Document === "undefined"
6
+ ? undefined
7
+ : Object.getOwnPropertyDescriptor(Document.prototype, "cookie");
8
+ /** The page's cookies, as name and value pairs. */
9
+ export function readCookies() {
10
+ return String(apply(cookieAccessor.get, document, []))
11
+ .split(";")
12
+ .map((pair) => pair.trim())
13
+ .filter((pair) => pair !== "")
14
+ .map((pair) => {
15
+ const equals = pair.indexOf("=");
16
+ return equals === -1
17
+ ? ["", pair]
18
+ : [pair.slice(0, equals), pair.slice(equals + 1)];
19
+ });
20
+ }
21
+ function writeCookie(text) {
22
+ apply(cookieAccessor.set, document, [text]);
23
+ }
24
+ /** The value of a cookie, or undefined when the page has none by that name. */
25
+ function cookieValue(name) {
26
+ return readCookies().find(([one]) => one === name)?.[1];
27
+ }
28
+ /** Whether a token like `reload, 1` is on. */
29
+ export function isOn(value) {
30
+ return value !== undefined && value !== "" && value !== "0";
31
+ }
32
+ /** `$now$`, `$currentDate$` and `$currentISODate$`, anywhere in the text. */
33
+ export function withDates(text) {
34
+ return text
35
+ .replaceAll("$now$", String(Date.now()))
36
+ .replaceAll("$currentDate$", String(new Date()))
37
+ .replaceAll("$currentISODate$", new Date().toISOString());
38
+ }
39
+ const SAFE_COOKIE_VALUES = new Set(("accept reject accepted rejected notaccepted allow disallow deny allowed " +
40
+ "denied approved disapproved checked unchecked dismiss dismissed enable " +
41
+ "disable enabled disabled essential nonessential forbidden forever hide " +
42
+ "hidden necessary required ok on off true t false f yes y no n all none " +
43
+ "functional granted done decline declined closed next mandatory " +
44
+ "disagree agree").split(" "));
45
+ /** One of the values `set-cookie` may set: a small integer or a constant in any case. */
46
+ export function isSafeCookieValue(value) {
47
+ if (/^-?\d+$/.test(value))
48
+ return Math.abs(Number(value)) <= 32767;
49
+ return SAFE_COOKIE_VALUES.has(value.toLowerCase());
50
+ }
51
+ /** The value inside double quotes, or the value itself. */
52
+ export function unquoted(value) {
53
+ return /^"(.*)"$/s.exec(value)?.[1] ?? value;
54
+ }
55
+ const EXPIRED = "; expires=Thu, 01 Jan 1970 00:00:00 GMT";
56
+ function secure(name) {
57
+ return /^__(?:Secure|Host)-/.test(name) ? "; secure" : "";
58
+ }
59
+ function removeCookies(needle) {
60
+ const matches = matcher(needle);
61
+ const host = location.hostname;
62
+ const domains = ["", `; domain=${host}`];
63
+ if (host.startsWith("www."))
64
+ domains.push(`; domain=${host.slice(4)}`);
65
+ // Every path a cookie the page sees can have: the prefixes of its own.
66
+ const paths = ["/"];
67
+ let path = "";
68
+ for (const part of location.pathname.split("/").slice(1)) {
69
+ if (part === "")
70
+ continue;
71
+ path += `/${part}`;
72
+ paths.push(path);
73
+ }
74
+ for (const [name] of readCookies()) {
75
+ if (name === "" || !matches(name))
76
+ continue;
77
+ for (const domain of domains) {
78
+ for (const one of paths) {
79
+ writeCookie(`${name}=${EXPIRED}; path=${one}${domain}${secure(name)}`);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ export const removeCookie = {
85
+ name: "remove-cookie",
86
+ aliases: ["cookie-remover"],
87
+ run(...args) {
88
+ const [needle] = args;
89
+ const when = tokens(args, 1).when;
90
+ const remove = () => {
91
+ try {
92
+ removeCookies(needle);
93
+ }
94
+ catch {
95
+ // No cookies here (a sandboxed frame).
96
+ }
97
+ };
98
+ remove();
99
+ addEventListener("load", remove);
100
+ addEventListener("beforeunload", remove);
101
+ let pending = false;
102
+ for (const type of (when ?? "").split(/\s+/)) {
103
+ if (type !== "scroll" && type !== "keydown")
104
+ continue;
105
+ addEventListener(type, () => {
106
+ if (pending)
107
+ return;
108
+ pending = true;
109
+ setTimeout(() => {
110
+ pending = false;
111
+ remove();
112
+ }, 500);
113
+ }, { capture: true, passive: true });
114
+ }
115
+ },
116
+ };
117
+ /** `path` argument: `/` (the default) or `none`. Undefined for anything else. */
118
+ function pathAttribute(path = "") {
119
+ if (path === "" || path === "/")
120
+ return "; path=/";
121
+ return path === "none" ? "" : undefined;
122
+ }
123
+ /**
124
+ * Sets a cookie, then reloads the page when `reload` is on and the cookie
125
+ * wasn't there with that value before. It reloads only once the cookie
126
+ * reads back, so a page that refuses the cookie doesn't reload forever.
127
+ */
128
+ function putCookie(name, value, attributes, options, reload) {
129
+ const before = cookieValue(name);
130
+ if (before !== undefined && isOn(options.dontOverwrite))
131
+ return;
132
+ writeCookie(`${name}=${value}${attributes}${secure(name)}`);
133
+ // `history.go(0)` reloads, like `location.reload()`, and tests can stub it.
134
+ if (reload && before !== value && cookieValue(name) === value)
135
+ history.go(0);
136
+ }
137
+ function setCookie(args, reload) {
138
+ const [name = "", raw = "", path] = args;
139
+ const value = unquoted(raw);
140
+ const attributes = pathAttribute(path);
141
+ if (name === "" || !isSafeCookieValue(value) || attributes === undefined)
142
+ return;
143
+ const options = tokens(args, 3);
144
+ const encoded = value === raw
145
+ ? encodeURIComponent(value)
146
+ : `"${encodeURIComponent(value)}"`;
147
+ putCookie(encodeURIComponent(name), encoded, attributes, options, reload || isOn(options.reload));
148
+ }
149
+ const DAY = 86_400;
150
+ function trustedSetCookie(args, reload) {
151
+ const [name = "", raw = "", offset = "", path] = args;
152
+ let attributes = pathAttribute(path);
153
+ if (name === "" || attributes === undefined)
154
+ return;
155
+ if (offset !== "") {
156
+ const seconds = offset === "1year"
157
+ ? 365 * DAY
158
+ : offset === "1day"
159
+ ? DAY
160
+ : /^\d+$/.test(offset)
161
+ ? Number(offset)
162
+ : undefined;
163
+ if (seconds === undefined)
164
+ return;
165
+ attributes += `; max-age=${seconds}`;
166
+ }
167
+ const options = tokens(args, 4);
168
+ if (options.domain !== undefined && options.domain !== "") {
169
+ const regex = parseRegex(options.domain);
170
+ const domain = regex === undefined ? options.domain : regex.exec(location.hostname)?.[0];
171
+ if (domain === undefined)
172
+ return;
173
+ attributes += `; domain=${domain}`;
174
+ }
175
+ putCookie(name, withDates(raw), attributes, options, reload || isOn(options.reload));
176
+ }
177
+ export const setCookieScriptlet = {
178
+ name: "set-cookie",
179
+ run: (...args) => setCookie(args, false),
180
+ };
181
+ export const setCookieReload = {
182
+ name: "set-cookie-reload",
183
+ run: (...args) => setCookie(args, true),
184
+ };
185
+ export const trustedSetCookieScriptlet = {
186
+ name: "trusted-set-cookie",
187
+ trusted: true,
188
+ run: (...args) => trustedSetCookie(args, false),
189
+ };
190
+ export const trustedSetCookieReload = {
191
+ name: "trusted-set-cookie-reload",
192
+ trusted: true,
193
+ run: (...args) => trustedSetCookie(args, true),
194
+ };
@@ -0,0 +1,2 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ export declare const trustedCreateHtml: Scriptlet;
@@ -0,0 +1,27 @@
1
+ import { runAt } from "../helpers.js";
2
+ export const trustedCreateHtml = {
3
+ name: "trusted-create-html",
4
+ aliases: ["trusted-create-HTML"],
5
+ trusted: true,
6
+ run(parent = "", html = "", duration = "") {
7
+ if (parent === "" || html === "")
8
+ return;
9
+ // The parent is often one the parser hasn't reached when this runs.
10
+ runAt("interactive", () => {
11
+ const target = document.querySelector(parent);
12
+ if (target === null)
13
+ return;
14
+ const parsed = new DOMParser().parseFromString(html, "text/html");
15
+ // A lone `<style>` or `<meta>` lands in the head.
16
+ const nodes = [...parsed.head.childNodes, ...parsed.body.childNodes];
17
+ target.append(...nodes);
18
+ const ms = Number(duration);
19
+ if (ms > 0) {
20
+ setTimeout(() => {
21
+ for (const node of nodes)
22
+ node.parentNode?.removeChild(node);
23
+ }, ms);
24
+ }
25
+ });
26
+ },
27
+ };
@@ -0,0 +1,3 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ export declare const preventDialog: Scriptlet;
3
+ export declare const alertBuster: Scriptlet;
@@ -0,0 +1,21 @@
1
+ import { wrapMethod } from "../helpers.js";
2
+ import { watch } from "./watch.js";
3
+ const { apply } = Reflect;
4
+ export const preventDialog = {
5
+ name: "prevent-dialog",
6
+ run(selector = "") {
7
+ watch(`dialog${selector}`, (dialog) => {
8
+ if (dialog instanceof HTMLDialogElement && dialog.open)
9
+ dialog.close();
10
+ }, ["open"]);
11
+ },
12
+ };
13
+ export const alertBuster = {
14
+ name: "alert-buster",
15
+ run() {
16
+ const info = console.info;
17
+ wrapMethod(window, "alert", (_original, _self, args) => {
18
+ apply(info, console, args);
19
+ });
20
+ },
21
+ };
@@ -0,0 +1,2 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ export declare const hrefSanitizer: Scriptlet;
@@ -0,0 +1,91 @@
1
+ import { parseRegex } from "../helpers.js";
2
+ import { watch } from "./watch.js";
3
+ function queryOf(text) {
4
+ const query = text.indexOf("?");
5
+ if (query === -1)
6
+ return undefined;
7
+ const hash = text.indexOf("#", query);
8
+ return new URLSearchParams(text.slice(query + 1, hash === -1 ? undefined : hash));
9
+ }
10
+ function decodeBase64(text) {
11
+ return new TextDecoder().decode(Uint8Array.from(atob(text), (char) => char.charCodeAt(0)));
12
+ }
13
+ /**
14
+ * One `urlskip=` step (Static filter syntax) applied to the text, or
15
+ * undefined when it can't be.
16
+ */
17
+ function step(text, directive) {
18
+ if (directive.startsWith("?"))
19
+ return queryOf(text)?.get(directive.slice(1)) ?? undefined;
20
+ if (directive.startsWith("&")) {
21
+ return [...(queryOf(text)?.keys() ?? [])][Number(directive.slice(1)) - 1];
22
+ }
23
+ if (directive === "#") {
24
+ const hash = text.indexOf("#");
25
+ return hash === -1 ? undefined : text.slice(hash + 1);
26
+ }
27
+ if (directive === "+https") {
28
+ return /^https?:\/\//i.test(text)
29
+ ? text.replace(/^http:/i, "https:")
30
+ : `https://${text}`;
31
+ }
32
+ if (directive === "-base64")
33
+ return decodeBase64(text);
34
+ if (directive === "-safebase64") {
35
+ return decodeBase64(text.replaceAll("-", "+").replaceAll("_", "/"));
36
+ }
37
+ if (directive === "-uricomponent")
38
+ return decodeURIComponent(text);
39
+ return parseRegex(directive)?.exec(text)?.[1];
40
+ }
41
+ /** Applies the steps in turn: undefined when one fails or gives nothing. */
42
+ function skip(text, steps) {
43
+ let current = text;
44
+ for (const directive of steps) {
45
+ try {
46
+ current = step(current, directive);
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ if (current === undefined || current === "")
52
+ return undefined;
53
+ }
54
+ return current;
55
+ }
56
+ export const hrefSanitizer = {
57
+ name: "href-sanitizer",
58
+ run(selector = "", source = "") {
59
+ if (selector === "")
60
+ return;
61
+ // A `/regex/` step may hold spaces; `?a?b` is `?a ?b`.
62
+ const steps = (source.match(/\/(?:\\.|[^\\])+?\/(?=\s|$)|\S+/g) ?? []).flatMap((one) => /^\?[^?]+\?/.test(one)
63
+ ? one
64
+ .split("?")
65
+ .filter((name) => name !== "")
66
+ .map((name) => `?${name}`)
67
+ : [one]);
68
+ const attribute = /^\[(.+)\]$/.exec(steps[0] ?? "")?.[1];
69
+ if (attribute !== undefined)
70
+ steps.shift();
71
+ watch(selector, (element) => {
72
+ const href = element.getAttribute("href");
73
+ if (element.localName !== "a" || href === null)
74
+ return;
75
+ // The steps unwrap the link's own URL, unless something else is named.
76
+ const start = attribute !== undefined
77
+ ? element.getAttribute(attribute)
78
+ : steps.length > 0
79
+ ? href
80
+ : (element.textContent ?? "").trim();
81
+ const url = start === null ? undefined : skip(start, steps);
82
+ if (url === undefined ||
83
+ url === href ||
84
+ !/^https?:\/\//i.test(url) ||
85
+ !URL.canParse(url)) {
86
+ return;
87
+ }
88
+ element.setAttribute("href", url);
89
+ }, attribute === undefined ? ["href"] : ["href", attribute]);
90
+ },
91
+ };
@@ -0,0 +1,3 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ /** The scriptlets that act on the document, its cookies and its storage. */
3
+ export declare const DOM_SCRIPTLETS: readonly Scriptlet[];
@@ -0,0 +1,38 @@
1
+ import { removeAttr, removeClass, setAttrScriptlet, trustedSetAttr, } from "./attributes.js";
2
+ import { trustedClickElement } from "./click.js";
3
+ import { removeCookie, setCookieReload, setCookieScriptlet, trustedSetCookieReload, trustedSetCookieScriptlet, } from "./cookies.js";
4
+ import { trustedCreateHtml } from "./createHtml.js";
5
+ import { alertBuster, preventDialog } from "./dialogs.js";
6
+ import { hrefSanitizer } from "./hrefSanitizer.js";
7
+ import { closeWindow, disableNewtabLinks, preventRefresh, windowNameDefuser, } from "./navigation.js";
8
+ import { removeNodeText, trustedReplaceNodeText } from "./nodeText.js";
9
+ import { spoofCss } from "./spoofCss.js";
10
+ import { setLocalStorageItem, setSessionStorageItem, trustedSetLocalStorageItem, trustedSetSessionStorageItem, } from "./storage.js";
11
+ /** The scriptlets that act on the document, its cookies and its storage. */
12
+ export const DOM_SCRIPTLETS = [
13
+ alertBuster,
14
+ closeWindow,
15
+ disableNewtabLinks,
16
+ hrefSanitizer,
17
+ preventDialog,
18
+ preventRefresh,
19
+ removeAttr,
20
+ removeClass,
21
+ removeCookie,
22
+ removeNodeText,
23
+ setAttrScriptlet,
24
+ setCookieReload,
25
+ setCookieScriptlet,
26
+ setLocalStorageItem,
27
+ setSessionStorageItem,
28
+ spoofCss,
29
+ trustedClickElement,
30
+ trustedCreateHtml,
31
+ trustedReplaceNodeText,
32
+ trustedSetAttr,
33
+ trustedSetCookieReload,
34
+ trustedSetCookieScriptlet,
35
+ trustedSetLocalStorageItem,
36
+ trustedSetSessionStorageItem,
37
+ windowNameDefuser,
38
+ ];
@@ -0,0 +1,5 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ export declare const preventRefresh: Scriptlet;
3
+ export declare const disableNewtabLinks: Scriptlet;
4
+ export declare const closeWindow: Scriptlet;
5
+ export declare const windowNameDefuser: Scriptlet;
@@ -0,0 +1,60 @@
1
+ import { matcher, parseRegex, runAt } from "../helpers.js";
2
+ const { apply } = Reflect;
3
+ export const preventRefresh = {
4
+ name: "prevent-refresh",
5
+ aliases: ["refresh-defuser"],
6
+ run(seconds = "") {
7
+ const stop = window.stop;
8
+ // A refresh counts its delay from the end of the load, and stopping
9
+ // only cancels a navigation already under way: stop just after it.
10
+ runAt("complete", () => {
11
+ const content = document
12
+ .querySelector('meta[http-equiv="refresh" i]')
13
+ ?.getAttribute("content");
14
+ const delay = Number.parseFloat(seconds || (content ?? ""));
15
+ if (!(delay >= 0))
16
+ return;
17
+ setTimeout(() => apply(stop, window, []), delay * 1000 + 50);
18
+ });
19
+ },
20
+ };
21
+ export const disableNewtabLinks = {
22
+ name: "disable-newtab-links",
23
+ run() {
24
+ document.addEventListener("click", (event) => {
25
+ const target = event.target;
26
+ if (!(target instanceof Element))
27
+ return;
28
+ const link = target.closest("a[target]");
29
+ // These open in the same tab.
30
+ if (link === null ||
31
+ /^(?:|_self|_parent|_top)$/i.test(link.getAttribute("target") ?? "")) {
32
+ return;
33
+ }
34
+ event.preventDefault();
35
+ event.stopPropagation();
36
+ }, true);
37
+ },
38
+ };
39
+ export const closeWindow = {
40
+ name: "close-window",
41
+ aliases: ["window-close-if"],
42
+ run(needle = "") {
43
+ // In a browser this closes a tab a page opened. Here a window no page
44
+ // opened is the host app's own, and a filter must not close that.
45
+ if (!window.opener || window.top !== window)
46
+ return;
47
+ // A regex reads the whole URL, text the path and query.
48
+ const subject = parseRegex(needle) === undefined
49
+ ? location.pathname + location.search
50
+ : location.href;
51
+ if (matcher(needle)(subject))
52
+ window.close();
53
+ },
54
+ };
55
+ export const windowNameDefuser = {
56
+ name: "window.name-defuser",
57
+ run() {
58
+ window.name = "";
59
+ },
60
+ };
@@ -0,0 +1,3 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ export declare const removeNodeText: Scriptlet;
3
+ export declare const trustedReplaceNodeText: Scriptlet;