@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,98 @@
1
+ import { matcher, parseRegex, tokens } from "../helpers.js";
2
+ import { isOn } from "./cookies.js";
3
+ const { apply } = Reflect;
4
+ const replace = String.prototype.replace;
5
+ // There is no Node when the main process loads this file for the names.
6
+ const textContent = typeof Node === "undefined"
7
+ ? undefined
8
+ : Object.getOwnPropertyDescriptor(Node.prototype, "textContent");
9
+ /**
10
+ * Edits the text of the nodes named `nodeName` (`#text`, `script`…) as the
11
+ * document gets them. `edit` returns the new text, or undefined to leave
12
+ * it. Quits at `DOMContentLoaded`, `quitAfter` ms after it, after
13
+ * `sedCount` edits, or never with `stay`.
14
+ */
15
+ function editNodes(nodeName, options, edit) {
16
+ const wanted = nodeName.toLowerCase();
17
+ if (wanted === "")
18
+ return;
19
+ // `condition` is what the wiki's examples call `includes`.
20
+ const includes = matcher(options.includes ?? options.condition);
21
+ const excludes = options.excludes === undefined ? () => false : matcher(options.excludes);
22
+ let left = Number(options.sedCount) || 0;
23
+ let done = false;
24
+ const handle = (node) => {
25
+ if (done || node.nodeName.toLowerCase() !== wanted)
26
+ return;
27
+ const text = String(apply(textContent.get, node, []));
28
+ if (!includes(text) || excludes(text))
29
+ return;
30
+ const next = edit(text);
31
+ if (next === undefined || next === text)
32
+ return;
33
+ apply(textContent.set, node, [next]);
34
+ if (left > 0 && --left === 0)
35
+ quit();
36
+ };
37
+ const visit = (node) => {
38
+ // The parser adds a script's text after the script itself.
39
+ if (node.nodeType === Node.TEXT_NODE && node.parentNode !== null) {
40
+ handle(node.parentNode);
41
+ }
42
+ handle(node);
43
+ if (!node.hasChildNodes())
44
+ return;
45
+ const walker = document.createTreeWalker(node, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT);
46
+ const found = [];
47
+ while (walker.nextNode() !== null)
48
+ found.push(walker.currentNode);
49
+ for (const one of found)
50
+ handle(one);
51
+ };
52
+ const observer = new MutationObserver((records) => {
53
+ for (const record of records) {
54
+ for (const node of record.addedNodes)
55
+ visit(node);
56
+ }
57
+ // What changed in there is our own editing.
58
+ observer.takeRecords();
59
+ });
60
+ const quit = () => {
61
+ done = true;
62
+ observer.disconnect();
63
+ };
64
+ visit(document);
65
+ if (done)
66
+ return;
67
+ observer.observe(document, { childList: true, subtree: true });
68
+ if (isOn(options.stay))
69
+ return;
70
+ const delay = Number(options.quitAfter) || 0;
71
+ const later = () => (delay > 0 ? setTimeout(quit, delay) : quit());
72
+ if (document.readyState === "loading") {
73
+ document.addEventListener("DOMContentLoaded", later, { once: true });
74
+ }
75
+ else
76
+ later();
77
+ }
78
+ export const removeNodeText = {
79
+ name: "remove-node-text",
80
+ aliases: ["rmnt"],
81
+ run(...args) {
82
+ const [nodeName = "", needle = ""] = args;
83
+ const matches = matcher(needle);
84
+ editNodes(nodeName, tokens(args, 2), (text) => matches(text) ? "" : undefined);
85
+ },
86
+ };
87
+ export const trustedReplaceNodeText = {
88
+ name: "trusted-replace-node-text",
89
+ aliases: ["trusted-rpnt", "replace-node-text", "rpnt"],
90
+ trusted: true,
91
+ run(...args) {
92
+ const [nodeName = "", needle = "", replacement = ""] = args;
93
+ if (needle === "")
94
+ return;
95
+ const pattern = parseRegex(needle) ?? needle;
96
+ editNodes(nodeName, tokens(args, 3), (text) => String(apply(replace, text, [pattern, replacement])));
97
+ },
98
+ };
@@ -0,0 +1,2 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ export declare const spoofCss: Scriptlet;
@@ -0,0 +1,58 @@
1
+ import { wrapMethod } from "../helpers.js";
2
+ const { apply, get } = Reflect;
3
+ function camelCase(name) {
4
+ return name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
5
+ }
6
+ export const spoofCss = {
7
+ name: "spoof-css",
8
+ run(selector = "", ...pairs) {
9
+ if (selector === "" || pairs.length === 0)
10
+ return;
11
+ const Rect = DOMRect;
12
+ const spoofed = new Map();
13
+ for (let i = 0; i < pairs.length; i += 2) {
14
+ spoofed.set(camelCase(pairs[i]), pairs[i + 1] ?? "");
15
+ }
16
+ const matches = (element) => {
17
+ try {
18
+ return element instanceof Element && element.matches(selector);
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ };
24
+ wrapMethod(window, "getComputedStyle", (original, _self, args) => {
25
+ const style = original(...args);
26
+ if (!matches(args[0]))
27
+ return style;
28
+ const getPropertyValue = (name) => spoofed.get(camelCase(name)) ?? style.getPropertyValue(name);
29
+ return new Proxy(style, {
30
+ get(target, property) {
31
+ if (property === "getPropertyValue")
32
+ return getPropertyValue;
33
+ if (typeof property === "string" && spoofed.has(camelCase(property)))
34
+ return spoofed.get(camelCase(property));
35
+ // The declaration's own getters and methods need it as `this`.
36
+ const value = get(target, property, target);
37
+ return typeof value === "function"
38
+ ? (...inner) => apply(value, target, inner)
39
+ : value;
40
+ },
41
+ });
42
+ });
43
+ wrapMethod(Element.prototype, "getBoundingClientRect", (original, self) => {
44
+ const rect = original();
45
+ if (!matches(self))
46
+ return rect;
47
+ const pick = (current, ...names) => {
48
+ for (const name of names) {
49
+ const value = Number.parseFloat(spoofed.get(name) ?? "");
50
+ if (!Number.isNaN(value))
51
+ return value;
52
+ }
53
+ return current;
54
+ };
55
+ return new Rect(pick(rect.x, "_rectx"), pick(rect.y, "_recty"), pick(rect.width, "_rectw", "width"), pick(rect.height, "_recth", "height"));
56
+ });
57
+ },
58
+ };
@@ -0,0 +1,5 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ export declare const setLocalStorageItem: Scriptlet;
3
+ export declare const setSessionStorageItem: Scriptlet;
4
+ export declare const trustedSetLocalStorageItem: Scriptlet;
5
+ export declare const trustedSetSessionStorageItem: Scriptlet;
@@ -0,0 +1,50 @@
1
+ import { isSafeCookieValue, unquoted, withDates } from "./cookies.js";
2
+ /**
3
+ * One of the values `set-local-storage-item` may set, as stored, or
4
+ * undefined. Double quotes around an allowed value stay in what is stored.
5
+ */
6
+ function safeValue(text) {
7
+ if (text === "''")
8
+ return "";
9
+ if (["undefined", "null", "{}", "[]", '""'].includes(text))
10
+ return text;
11
+ return isSafeCookieValue(unquoted(text)) ? text : undefined;
12
+ }
13
+ function trustedValue(text) {
14
+ return text === "''" ? "" : withDates(text);
15
+ }
16
+ function setItem(area, key = "", raw = "", parse) {
17
+ if (key === "")
18
+ return;
19
+ const value = raw === "$remove$" ? null : parse(raw);
20
+ if (value === undefined)
21
+ return;
22
+ try {
23
+ const storage = window[area];
24
+ if (value === null)
25
+ storage.removeItem(key);
26
+ else
27
+ storage.setItem(key, value);
28
+ }
29
+ catch {
30
+ // No storage here, or it is full.
31
+ }
32
+ }
33
+ export const setLocalStorageItem = {
34
+ name: "set-local-storage-item",
35
+ run: (key, value) => setItem("localStorage", key, value, safeValue),
36
+ };
37
+ export const setSessionStorageItem = {
38
+ name: "set-session-storage-item",
39
+ run: (key, value) => setItem("sessionStorage", key, value, safeValue),
40
+ };
41
+ export const trustedSetLocalStorageItem = {
42
+ name: "trusted-set-local-storage-item",
43
+ trusted: true,
44
+ run: (key, value) => setItem("localStorage", key, value, trustedValue),
45
+ };
46
+ export const trustedSetSessionStorageItem = {
47
+ name: "trusted-set-session-storage-item",
48
+ trusted: true,
49
+ run: (key, value) => setItem("sessionStorage", key, value, trustedValue),
50
+ };
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Calls `act` on every element `selector` matches: now, and again after each
3
+ * change to the document (and to the `attributes` named), until the
4
+ * observer it returns is disconnected. Undefined for a selector that isn't
5
+ * one. `act` must leave alone what is already done, since its own changes
6
+ * are changes to the document too.
7
+ */
8
+ export declare function watch(selector: string, act: (element: Element) => void, attributes?: readonly string[]): MutationObserver | undefined;
@@ -0,0 +1,41 @@
1
+ const { apply } = Reflect;
2
+ /**
3
+ * Calls `act` on every element `selector` matches: now, and again after each
4
+ * change to the document (and to the `attributes` named), until the
5
+ * observer it returns is disconnected. Undefined for a selector that isn't
6
+ * one. `act` must leave alone what is already done, since its own changes
7
+ * are changes to the document too.
8
+ */
9
+ export function watch(selector, act, attributes) {
10
+ try {
11
+ document.querySelector(selector);
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ // Taken now, while it is the browser's: the page's scripts run later.
17
+ // (Not when this file loads: the main process loads it too, for the names.)
18
+ const querySelectorAll = Document.prototype.querySelectorAll;
19
+ // shortcut: rescans the whole document per batch of changes; walk only
20
+ // the added nodes if a busy page shows it in a profile.
21
+ const scan = () => {
22
+ for (const element of apply(querySelectorAll, document, [selector])) {
23
+ try {
24
+ act(element);
25
+ }
26
+ catch {
27
+ // One element the page made odd doesn't stop the rest.
28
+ }
29
+ }
30
+ };
31
+ scan();
32
+ const observer = new MutationObserver(scan);
33
+ observer.observe(document, {
34
+ childList: true,
35
+ subtree: true,
36
+ ...(attributes === undefined
37
+ ? {}
38
+ : { attributes: true, attributeFilter: [...attributes] }),
39
+ });
40
+ return observer;
41
+ }
@@ -0,0 +1,2 @@
1
+ import type { Scriptlet } from "./types.js";
2
+ export declare const addEventListenerDefuser: Scriptlet;
@@ -0,0 +1,42 @@
1
+ import { matcher, runAt, tokens, wrapMethod } from "./helpers.js";
2
+ /** Whether a listener is being added to what an `elements` token names. */
3
+ function isTarget(target, selector) {
4
+ if (selector === "window")
5
+ return target === window;
6
+ if (selector === "document")
7
+ return target === document;
8
+ try {
9
+ return target instanceof Element && target.matches(selector);
10
+ }
11
+ catch {
12
+ return false;
13
+ }
14
+ }
15
+ export const addEventListenerDefuser = {
16
+ name: "addEventListener-defuser",
17
+ aliases: ["aeld", "prevent-addEventListener"],
18
+ run(...args) {
19
+ const [type, needle] = args;
20
+ // Without arguments the scriptlet only logs, and there is no logger.
21
+ if (type === undefined && needle === undefined)
22
+ return;
23
+ const options = tokens(args, 2);
24
+ const typeMatches = matcher(type);
25
+ const handlerMatches = matcher(needle);
26
+ runAt(options.runAt, () => {
27
+ wrapMethod(EventTarget.prototype, "addEventListener", (original, self, callArgs) => {
28
+ const [eventType, listener] = callArgs;
29
+ const handler = typeof listener === "object" && listener !== null
30
+ ? listener.handleEvent
31
+ : listener;
32
+ if (typeMatches(String(eventType)) &&
33
+ handlerMatches(String(handler)) &&
34
+ (options.elements === undefined ||
35
+ isTarget(self ?? window, options.elements))) {
36
+ return undefined;
37
+ }
38
+ return original(...callArgs);
39
+ });
40
+ });
41
+ },
42
+ };
@@ -0,0 +1,58 @@
1
+ type Matcher = (text: string) => boolean;
2
+ /** Sets what main sent with the scriptlet that is about to run. */
3
+ export declare function setResources(given: Readonly<Record<string, string>> | undefined): void;
4
+ /**
5
+ * The text of the redirect resource a `war:<name>` argument names, or empty.
6
+ * Only while the scriptlet is being set up: later it is another's.
7
+ */
8
+ export declare function resourceText(name: string): string;
9
+ /** The regular expression of `/source/flags`, or undefined for anything else. */
10
+ export declare function parseRegex(text: string): RegExp | undefined;
11
+ /**
12
+ * How scriptlets read a "string or regular expression" argument: `/…/` is a
13
+ * regular expression, anything else is text to find, and nothing matches
14
+ * everything. With `negatable`, a leading `!` inverts the result.
15
+ */
16
+ export declare function matcher(pattern?: string, negatable?: boolean): Matcher;
17
+ /**
18
+ * The name and value pairs that follow a scriptlet's positional arguments
19
+ * (`…, runAt, idle, elements, a.promo`).
20
+ */
21
+ export declare function tokens(args: readonly string[], from: number): Record<string, string | undefined>;
22
+ /**
23
+ * Runs `task` once the document is at least in the state a `runAt` token
24
+ * names: now (the default), `interactive` or `end`, `complete` or `idle`.
25
+ */
26
+ export declare function runAt(when: string | undefined, task: () => void): void;
27
+ /** What an aborted script gets: an error no handler of the page expects. */
28
+ export declare function abort(): never;
29
+ /**
30
+ * Calls `install(owner, property)` for the last property of a chain like
31
+ * `a.b.c`, on the object that holds it: now when `a.b` exists, and again
32
+ * each time the page assigns `a` or `a.b`, since most chains don't exist
33
+ * yet when a scriptlet runs.
34
+ */
35
+ export declare function onChain(root: object, chain: string, install: (owner: Record<string, unknown>, property: string) => void): void;
36
+ /**
37
+ * Replaces a property with an accessor, when the page lets it. `get` and
38
+ * `set` receive the value the property would have without the trap.
39
+ */
40
+ export declare function trap(owner: Record<string, unknown>, property: string, handlers: {
41
+ get?: (value: unknown) => unknown;
42
+ set?: (next: unknown, value: unknown) => unknown;
43
+ }): boolean;
44
+ /**
45
+ * Puts a function in front of a method, as a Proxy so that the method still
46
+ * reads as the browser's own (`toString()`, `name`, `length`). `wrapper`
47
+ * gets the original, `this` and the arguments, and returns the result.
48
+ * Returns false when there is no such method.
49
+ */
50
+ export declare function wrapMethod(owner: object, property: string, wrapper: (original: (...args: any[]) => any, self: unknown, args: any[]) => unknown): boolean;
51
+ /** The object a chain like `a.b` names, from `window`, or undefined. */
52
+ export declare function lookUp(chain: string): {
53
+ owner: Record<string, unknown>;
54
+ property: string;
55
+ } | undefined;
56
+ /** Whether the call stack matches a `stack` argument (`!` inverts). */
57
+ export declare function stackMatches(pattern: string | undefined): boolean;
58
+ export {};
@@ -0,0 +1,206 @@
1
+ // What scriptlets share. This file runs in pages: it is bundled with the
2
+ // scriptlets, so it can't import from outside this folder.
3
+ //
4
+ // The page's scripts run after ours and may replace built-ins, so what the
5
+ // traps call later is taken here, while it is still the browser's own.
6
+ const { defineProperty, getOwnPropertyDescriptor } = Object;
7
+ const { apply } = Reflect;
8
+ const test = RegExp.prototype.test;
9
+ const includes = String.prototype.includes;
10
+ let resources = {};
11
+ /** Sets what main sent with the scriptlet that is about to run. */
12
+ export function setResources(given) {
13
+ resources = given ?? {};
14
+ }
15
+ /**
16
+ * The text of the redirect resource a `war:<name>` argument names, or empty.
17
+ * Only while the scriptlet is being set up: later it is another's.
18
+ */
19
+ export function resourceText(name) {
20
+ return resources[name] ?? "";
21
+ }
22
+ /** The regular expression of `/source/flags`, or undefined for anything else. */
23
+ export function parseRegex(text) {
24
+ const match = /^\/(.+)\/([dgimsuvy]*)$/s.exec(text);
25
+ if (match === null)
26
+ return undefined;
27
+ try {
28
+ return new RegExp(match[1], match[2]);
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
34
+ /**
35
+ * How scriptlets read a "string or regular expression" argument: `/…/` is a
36
+ * regular expression, anything else is text to find, and nothing matches
37
+ * everything. With `negatable`, a leading `!` inverts the result.
38
+ */
39
+ export function matcher(pattern = "", negatable = false) {
40
+ const negated = negatable && pattern.startsWith("!");
41
+ if (negated)
42
+ pattern = pattern.slice(1);
43
+ const regex = parseRegex(pattern);
44
+ const matches = pattern === ""
45
+ ? () => true
46
+ : regex === undefined
47
+ ? (text) => apply(includes, text, [pattern])
48
+ : (text) => {
49
+ regex.lastIndex = 0;
50
+ return apply(test, regex, [text]);
51
+ };
52
+ return negated ? (text) => !matches(text) : matches;
53
+ }
54
+ /**
55
+ * The name and value pairs that follow a scriptlet's positional arguments
56
+ * (`…, runAt, idle, elements, a.promo`).
57
+ */
58
+ export function tokens(args, from) {
59
+ const found = {};
60
+ for (let i = from; i < args.length; i += 2)
61
+ found[args[i]] = args[i + 1] ?? "";
62
+ return found;
63
+ }
64
+ const STATES = {
65
+ loading: 1,
66
+ asap: 1,
67
+ "1": 1,
68
+ interactive: 2,
69
+ end: 2,
70
+ "2": 2,
71
+ complete: 3,
72
+ idle: 3,
73
+ "3": 3,
74
+ };
75
+ /**
76
+ * Runs `task` once the document is at least in the state a `runAt` token
77
+ * names: now (the default), `interactive` or `end`, `complete` or `idle`.
78
+ */
79
+ export function runAt(when, task) {
80
+ const wanted = STATES[when ?? ""] ?? 1;
81
+ const reached = () => (STATES[document.readyState] ?? 1) >= wanted;
82
+ if (reached()) {
83
+ task();
84
+ return;
85
+ }
86
+ const listener = () => {
87
+ if (!reached())
88
+ return;
89
+ document.removeEventListener("readystatechange", listener, true);
90
+ task();
91
+ };
92
+ document.addEventListener("readystatechange", listener, true);
93
+ }
94
+ /** What an aborted script gets: an error no handler of the page expects. */
95
+ export function abort() {
96
+ throw new ReferenceError(`${Math.random().toString(36).slice(2, 10)} is not defined`);
97
+ }
98
+ function isObject(value) {
99
+ return ((typeof value === "object" && value !== null) || typeof value === "function");
100
+ }
101
+ /**
102
+ * Calls `install(owner, property)` for the last property of a chain like
103
+ * `a.b.c`, on the object that holds it: now when `a.b` exists, and again
104
+ * each time the page assigns `a` or `a.b`, since most chains don't exist
105
+ * yet when a scriptlet runs.
106
+ */
107
+ export function onChain(root, chain, install) {
108
+ const owner = root;
109
+ const dot = chain.indexOf(".");
110
+ if (dot === -1) {
111
+ install(owner, chain);
112
+ return;
113
+ }
114
+ const property = chain.slice(0, dot);
115
+ const rest = chain.slice(dot + 1);
116
+ let value = owner[property];
117
+ if (isObject(value))
118
+ onChain(value, rest, install);
119
+ const descriptor = getOwnPropertyDescriptor(owner, property);
120
+ // An accessor is the page's or the browser's business: leave it alone.
121
+ if (descriptor !== undefined && !("value" in descriptor))
122
+ return;
123
+ if (descriptor?.configurable === false)
124
+ return;
125
+ defineProperty(owner, property, {
126
+ configurable: true,
127
+ enumerable: descriptor?.enumerable ?? true,
128
+ get: () => value,
129
+ set(next) {
130
+ value = next;
131
+ if (isObject(next))
132
+ onChain(next, rest, install);
133
+ },
134
+ });
135
+ }
136
+ /**
137
+ * Replaces a property with an accessor, when the page lets it. `get` and
138
+ * `set` receive the value the property would have without the trap.
139
+ */
140
+ export function trap(owner, property, handlers) {
141
+ const descriptor = getOwnPropertyDescriptor(owner, property);
142
+ if (descriptor?.configurable === false)
143
+ return false;
144
+ let value = descriptor === undefined ? owner[property] : descriptor.value;
145
+ if (descriptor?.get !== undefined)
146
+ value = apply(descriptor.get, owner, []);
147
+ defineProperty(owner, property, {
148
+ configurable: true,
149
+ enumerable: descriptor?.enumerable ?? true,
150
+ get: () => (handlers.get === undefined ? value : handlers.get(value)),
151
+ set(next) {
152
+ value = handlers.set === undefined ? next : handlers.set(next, value);
153
+ },
154
+ });
155
+ return true;
156
+ }
157
+ /**
158
+ * Puts a function in front of a method, as a Proxy so that the method still
159
+ * reads as the browser's own (`toString()`, `name`, `length`). `wrapper`
160
+ * gets the original, `this` and the arguments, and returns the result.
161
+ * Returns false when there is no such method.
162
+ */
163
+ export function wrapMethod(owner, property, wrapper) {
164
+ const original = owner[property];
165
+ if (typeof original !== "function")
166
+ return false;
167
+ owner[property] = new Proxy(original, {
168
+ apply: (target, self, args) => wrapper((...inner) => apply(target, self, inner), self, args),
169
+ });
170
+ return true;
171
+ }
172
+ /** The object a chain like `a.b` names, from `window`, or undefined. */
173
+ export function lookUp(chain) {
174
+ const names = chain.split(".");
175
+ const property = names.pop();
176
+ let owner = window;
177
+ for (const name of names) {
178
+ if (!isObject(owner))
179
+ return undefined;
180
+ owner = owner[name];
181
+ }
182
+ return isObject(owner) ? { owner, property } : undefined;
183
+ }
184
+ /**
185
+ * The text of the call stack, one frame after the other separated by tabs,
186
+ * for scriptlets that only act when called from some code. A frame of the
187
+ * page's own inline scripts reads `inlineScript`.
188
+ */
189
+ function stackTrace() {
190
+ const lines = (new Error().stack ?? "").split("\n").slice(1);
191
+ const here = location.href.split("#")[0];
192
+ const frames = lines
193
+ .map((line) => line.trim().replace(/^at\s+/, ""))
194
+ .filter((frame) => frame !== "")
195
+ .map((frame) => frame
196
+ .split(here)
197
+ .join("inlineScript")
198
+ .replace(/:(\d+):\d+\)?$/, ":$1:1"));
199
+ return `stackDepth:${frames.length}\t${frames.join("\t")}`;
200
+ }
201
+ /** Whether the call stack matches a `stack` argument (`!` inverts). */
202
+ export function stackMatches(pattern) {
203
+ return pattern === undefined || pattern === ""
204
+ ? true
205
+ : matcher(pattern, true)(stackTrace());
206
+ }
@@ -0,0 +1,6 @@
1
+ import type { Scriptlet } from "./types.js";
2
+ /** Every scriptlet the library has. A new one is added here. */
3
+ export declare const SCRIPTLETS: readonly Scriptlet[];
4
+ /** The scriptlet a filter names, by its name or an alias, with or without `.js`. */
5
+ export declare function findScriptlet(token: string): Scriptlet | undefined;
6
+ export type { Scriptlet, ScriptletCall } from "./types.js";
@@ -0,0 +1,47 @@
1
+ import { DEFUSERS } from "../resources/defusers.js";
2
+ import { abortCurrentScript, abortOnPropertyRead, abortOnPropertyWrite, abortOnStackTrace, } from "./abort.js";
3
+ import { DOM_SCRIPTLETS } from "./dom/index.js";
4
+ import { addEventListenerDefuser } from "./events.js";
5
+ import { NETWORK_SCRIPTLETS } from "./network/index.js";
6
+ import { setConstantScriptlet, trustedSetConstant } from "./setConstant.js";
7
+ import { adjustSetInterval, adjustSetTimeout, preventSetInterval, preventSetTimeout, } from "./timers.js";
8
+ // The names lists call the defusers by, besides their own.
9
+ const DEFUSER_ALIASES = {
10
+ ampproject_v0: ["ampproject.org/v0"],
11
+ nobab: ["bab-defuser"],
12
+ nofab: ["fuckadblock.js-3.2.0"],
13
+ popads: ["popads.net"],
14
+ };
15
+ /** Every scriptlet the library has. A new one is added here. */
16
+ export const SCRIPTLETS = [
17
+ abortCurrentScript,
18
+ abortOnPropertyRead,
19
+ abortOnPropertyWrite,
20
+ abortOnStackTrace,
21
+ addEventListenerDefuser,
22
+ adjustSetInterval,
23
+ adjustSetTimeout,
24
+ preventSetInterval,
25
+ preventSetTimeout,
26
+ setConstantScriptlet,
27
+ trustedSetConstant,
28
+ ...DOM_SCRIPTLETS,
29
+ ...NETWORK_SCRIPTLETS,
30
+ // The redirect resources that work as scriptlets too.
31
+ ...Object.entries(DEFUSERS).map(([name, run]) => ({
32
+ name,
33
+ aliases: DEFUSER_ALIASES[name],
34
+ run,
35
+ })),
36
+ ];
37
+ const byName = new Map();
38
+ for (const scriptlet of SCRIPTLETS) {
39
+ for (const name of [scriptlet.name, ...(scriptlet.aliases ?? [])]) {
40
+ byName.set(name, scriptlet);
41
+ }
42
+ }
43
+ /** The scriptlet a filter names, by its name or an alias, with or without `.js`. */
44
+ export function findScriptlet(token) {
45
+ return (byName.get(token) ??
46
+ byName.get(token.endsWith(".js") ? token.slice(0, -3) : token));
47
+ }
@@ -0,0 +1,9 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ import { type TextEdit } from "./fetch.js";
3
+ /** An edit of a value in place: the new root, or undefined for no change. */
4
+ export type ValueEdit = (data: unknown) => {
5
+ root: unknown;
6
+ } | undefined;
7
+ /** A text edit that parses JSON, edits it and gives its text back. */
8
+ export declare function jsonTextEdit(edit: ValueEdit): TextEdit;
9
+ export declare const EDIT_SCRIPTLETS: readonly Scriptlet[];