@tokioapp/adblock 0.0.0-stage → 0.0.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 +68 -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,124 @@
1
+ import { matcher, resourceText } from "../helpers.js";
2
+ import { randomText } from "./util.js";
3
+ const random = Math.random;
4
+ // The names a `name:value` condition can use. Anything else with a colon,
5
+ // like `https://…`, is a URL to match.
6
+ const NAMES = new Set([
7
+ "url",
8
+ "method",
9
+ "headers",
10
+ "body",
11
+ "mode",
12
+ "credentials",
13
+ "cache",
14
+ "redirect",
15
+ "referrer",
16
+ "referrerPolicy",
17
+ "integrity",
18
+ "keepalive",
19
+ "signal",
20
+ "priority",
21
+ "duplex",
22
+ ]);
23
+ function asText(value) {
24
+ if (typeof value !== "object" || value === null)
25
+ return String(value);
26
+ if (typeof Headers === "function" && value instanceof Headers) {
27
+ const entries = {};
28
+ value.forEach((one, name) => (entries[name] = one));
29
+ return JSON.stringify(entries);
30
+ }
31
+ try {
32
+ return JSON.stringify(value);
33
+ }
34
+ catch {
35
+ // A cycle: nothing a condition can match.
36
+ return "";
37
+ }
38
+ }
39
+ /**
40
+ * A space-separated list of conditions a request must all meet: text or
41
+ * `/regex/` to find in its URL (`!` inverts, when `negatable`), or
42
+ * `name:value` for one of its options. Nothing, or `*`, matches any request.
43
+ */
44
+ export function requestMatcher(props = "", negatable = false) {
45
+ const tests = [];
46
+ for (const condition of props.split(/\s+/)) {
47
+ if (condition === "" || condition === "*")
48
+ continue;
49
+ const pair = /^(\w+):(.*)$/s.exec(condition);
50
+ if (pair !== null && NAMES.has(pair[1])) {
51
+ const name = pair[1];
52
+ const matches = matcher(pair[2]);
53
+ tests.push((details) => details[name] !== undefined && matches(asText(details[name])));
54
+ }
55
+ else {
56
+ const matches = matcher(condition, negatable);
57
+ tests.push((details) => matches(String(details.url)));
58
+ }
59
+ }
60
+ return (details) => tests.every((test) => test(details));
61
+ }
62
+ /** The URL as the request resolves it. */
63
+ export function absolute(url) {
64
+ try {
65
+ return new URL(String(url), document.baseURI).href;
66
+ }
67
+ catch {
68
+ return String(url);
69
+ }
70
+ }
71
+ const OPTIONS = [...NAMES].filter((name) => name !== "url");
72
+ /** What a call of `fetch(input, init)` asks for. */
73
+ export function fetchDetails(args) {
74
+ const [input, init] = args;
75
+ const details = { method: "GET" };
76
+ const request = typeof Request === "function" && input instanceof Request
77
+ ? input
78
+ : undefined;
79
+ for (const source of [request, init]) {
80
+ if (typeof source !== "object" || source === null)
81
+ continue;
82
+ for (const name of OPTIONS) {
83
+ const value = source[name];
84
+ if (value !== undefined)
85
+ details[name] = value;
86
+ }
87
+ }
88
+ details.url = absolute(request === undefined ? input : request.url);
89
+ return details;
90
+ }
91
+ /**
92
+ * The body a defused request answers with, from a directive. Trusted
93
+ * filters can give any text; for the others an unknown directive is empty.
94
+ * Call it while the scriptlet is set up: a `war:` resource is only there
95
+ * then. The function it returns gives the body of each answer.
96
+ */
97
+ export function responseBody(directive, trusted) {
98
+ if (directive.startsWith("war:")) {
99
+ const text = resourceText(directive.slice(4));
100
+ return () => text;
101
+ }
102
+ return () => bodyOf(directive, trusted);
103
+ }
104
+ function bodyOf(directive, trusted) {
105
+ switch (directive) {
106
+ case "":
107
+ case "emptyStr":
108
+ return "";
109
+ case "true":
110
+ return randomText(10);
111
+ case "emptyObj":
112
+ return "{}";
113
+ case "emptyArr":
114
+ return "[]";
115
+ }
116
+ const length = /^length:(\d+)(?:-(\d+))?$/.exec(directive);
117
+ if (length !== null) {
118
+ const min = Number(length[1]);
119
+ const max = Math.max(min, Number(length[2] ?? min));
120
+ const size = min + Math.floor(random() * (max - min + 1));
121
+ return randomText(Math.min(size, 500000));
122
+ }
123
+ return trusted ? directive : "";
124
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Like `wrapMethod`, but `new` calls go through `wrapper` too (with
3
+ * `self` undefined), for methods that are also constructors.
4
+ */
5
+ export declare function wrapCallable(owner: object, property: string, wrapper: (original: (...args: any[]) => any, self: unknown, args: any[]) => unknown): boolean;
6
+ /**
7
+ * Puts a function in front of a getter, as a Proxy so that it still reads
8
+ * as the browser's own. `wrapper` gets the original read and `this`.
9
+ */
10
+ export declare function wrapGetter(owner: object, property: string, wrapper: (read: () => unknown, self: unknown) => unknown): boolean;
11
+ /** Like `wrapGetter`, for a setter: `wrapper` gets the original write. */
12
+ export declare function wrapSetter(owner: object, property: string, wrapper: (write: (value: unknown) => void, self: unknown, value: unknown) => void): boolean;
13
+ /** Random letters and digits. */
14
+ export declare function randomText(length: number): string;
15
+ export declare function isObject(value: unknown): value is Record<string, unknown>;
16
+ /** An argument position: zero-based, negative from the end. */
17
+ export declare function position(text: string, length: number): number | undefined;
18
+ /** Wraps the method a chain like `a.b.c` names from `window`, if it exists. */
19
+ export declare function onMethod(chain: string, wrapper: Parameters<typeof wrapCallable>[2]): boolean;
@@ -0,0 +1,80 @@
1
+ // What the network scriptlets share beyond `../helpers.js`.
2
+ import { lookUp } from "../helpers.js";
3
+ const { apply, construct } = Reflect;
4
+ const { defineProperty, getOwnPropertyDescriptor } = Object;
5
+ const random = Math.random;
6
+ /**
7
+ * Like `wrapMethod`, but `new` calls go through `wrapper` too (with
8
+ * `self` undefined), for methods that are also constructors.
9
+ */
10
+ export function wrapCallable(owner, property, wrapper) {
11
+ const target = owner[property];
12
+ if (typeof target !== "function")
13
+ return false;
14
+ owner[property] = new Proxy(target, {
15
+ apply: (fn, self, args) => wrapper((...inner) => apply(fn, self, inner), self, args),
16
+ construct: (fn, args, newTarget) => wrapper((...inner) => construct(fn, inner, newTarget), undefined, args),
17
+ });
18
+ return true;
19
+ }
20
+ /**
21
+ * Puts a function in front of a getter, as a Proxy so that it still reads
22
+ * as the browser's own. `wrapper` gets the original read and `this`.
23
+ */
24
+ export function wrapGetter(owner, property, wrapper) {
25
+ const descriptor = getOwnPropertyDescriptor(owner, property);
26
+ const get = descriptor?.get;
27
+ if (get === undefined || descriptor?.configurable === false)
28
+ return false;
29
+ defineProperty(owner, property, {
30
+ ...descriptor,
31
+ get: new Proxy(get, {
32
+ apply: (fn, self, args) => wrapper(() => apply(fn, self, args), self),
33
+ }),
34
+ });
35
+ return true;
36
+ }
37
+ /** Like `wrapGetter`, for a setter: `wrapper` gets the original write. */
38
+ export function wrapSetter(owner, property, wrapper) {
39
+ const descriptor = getOwnPropertyDescriptor(owner, property);
40
+ const set = descriptor?.set;
41
+ if (set === undefined || descriptor?.configurable === false)
42
+ return false;
43
+ defineProperty(owner, property, {
44
+ ...descriptor,
45
+ set: new Proxy(set, {
46
+ apply: (fn, self, args) => wrapper((value) => apply(fn, self, [value]), self, args[0]),
47
+ }),
48
+ });
49
+ return true;
50
+ }
51
+ /** Random letters and digits. */
52
+ export function randomText(length) {
53
+ let text = "";
54
+ while (text.length < length)
55
+ text += random().toString(36).slice(2);
56
+ return text.slice(0, length);
57
+ }
58
+ export function isObject(value) {
59
+ return typeof value === "object" && value !== null;
60
+ }
61
+ /** An argument position: zero-based, negative from the end. */
62
+ export function position(text, length) {
63
+ if (!/^-?\d+$/.test(text))
64
+ return undefined;
65
+ const index = Number(text);
66
+ return index < 0 ? length + index : index;
67
+ }
68
+ /** Wraps the method a chain like `a.b.c` names from `window`, if it exists. */
69
+ export function onMethod(chain, wrapper) {
70
+ const target = lookUp(chain);
71
+ if (target === undefined)
72
+ return false;
73
+ const { owner, property } = target;
74
+ // Storage keeps what is assigned to it as an item: wrap the method where
75
+ // it lives, for this one object.
76
+ if (typeof Storage === "function" && owner instanceof Storage) {
77
+ return wrapCallable(Storage.prototype, property, (original, self, args) => self === owner ? wrapper(original, self, args) : original(...args));
78
+ }
79
+ return wrapCallable(owner, property, wrapper);
80
+ }
@@ -0,0 +1,3 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ export declare const noWebrtc: Scriptlet;
3
+ export declare const webrtcIf: Scriptlet;
@@ -0,0 +1,62 @@
1
+ import { matcher } from "../helpers.js";
2
+ import { isObject, wrapCallable } from "./util.js";
3
+ const NAMES = ["RTCPeerConnection", "webkitRTCPeerConnection"];
4
+ /** A connection that never connects: what pages get in place of WebRTC. */
5
+ function deadConnection() {
6
+ const connection = new EventTarget();
7
+ const nothing = () => undefined;
8
+ const later = () => Promise.resolve();
9
+ const channel = Object.assign(new EventTarget(), {
10
+ close: nothing,
11
+ send: nothing,
12
+ });
13
+ return Object.assign(connection, {
14
+ close: nothing,
15
+ addTrack: nothing,
16
+ removeTrack: nothing,
17
+ addTransceiver: nothing,
18
+ createDataChannel: () => channel,
19
+ createOffer: later,
20
+ createAnswer: later,
21
+ setLocalDescription: later,
22
+ setRemoteDescription: later,
23
+ addIceCandidate: later,
24
+ getStats: () => Promise.resolve(new Map()),
25
+ getSenders: () => [],
26
+ getReceivers: () => [],
27
+ getTransceivers: () => [],
28
+ });
29
+ }
30
+ export const noWebrtc = {
31
+ name: "nowebrtc",
32
+ run() {
33
+ for (const name of NAMES) {
34
+ wrapCallable(window, name, () => deadConnection());
35
+ }
36
+ },
37
+ };
38
+ export const webrtcIf = {
39
+ name: "webrtc-if",
40
+ run(needle = "") {
41
+ if (needle === "")
42
+ return;
43
+ const matches = matcher(needle);
44
+ // The connection keeps only the servers the filter allows.
45
+ const allowed = (server) => isObject(server) &&
46
+ [server.urls, server.username, server.credential]
47
+ .flat()
48
+ .some((value) => typeof value === "string" && matches(value));
49
+ for (const name of NAMES) {
50
+ wrapCallable(window, name, (original, _self, args) => {
51
+ const [config] = args;
52
+ if (isObject(config) && Array.isArray(config.iceServers)) {
53
+ args[0] = {
54
+ ...config,
55
+ iceServers: config.iceServers.filter(allowed),
56
+ };
57
+ }
58
+ return original(...args);
59
+ });
60
+ }
61
+ },
62
+ };
@@ -0,0 +1,2 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ export declare const preventWindowOpen: Scriptlet;
@@ -0,0 +1,28 @@
1
+ import { matcher, wrapMethod } from "../helpers.js";
2
+ export const preventWindowOpen = {
3
+ name: "prevent-window-open",
4
+ aliases: ["nowoif", "no-window-open-if", "window.open-defuser"],
5
+ run(pattern = "", delay = "", decoy = "") {
6
+ // Unlike most scriptlets, no pattern means every call.
7
+ const matches = matcher(pattern, true);
8
+ const seconds = /^\d+$/.test(delay) ? Number(delay) : 0;
9
+ const wait = setTimeout;
10
+ wrapMethod(window, "open", (original, _self, args) => {
11
+ if (!matches(args.map(String).join(" ")))
12
+ return original(...args);
13
+ if (decoy === "blank")
14
+ return original("about:blank", ...args.slice(1));
15
+ if (seconds === 0)
16
+ return null;
17
+ // A page that needs a window gets the one of a hidden frame, for a
18
+ // while: nothing loads in it.
19
+ const frame = document.createElement(decoy === "obj" ? "object" : "iframe");
20
+ if (frame instanceof HTMLObjectElement)
21
+ frame.data = "about:blank";
22
+ frame.style.setProperty("display", "none", "important");
23
+ (document.body ?? document.documentElement).append(frame);
24
+ wait(() => frame.remove(), seconds * 1000);
25
+ return frame.contentWindow;
26
+ });
27
+ },
28
+ };
@@ -0,0 +1,9 @@
1
+ import type { Scriptlet } from "../types.js";
2
+ import type { TextEdit } from "./fetch.js";
3
+ import { type Details } from "./request.js";
4
+ /** Hands the text of each response that matches to `edit`. */
5
+ export declare function editXhrResponses(matches: (details: Details) => boolean, edit: TextEdit): void;
6
+ /** Hands the text body of each request that matches to `edit`. */
7
+ export declare function editXhrRequests(matches: (details: Details) => boolean, edit: TextEdit): void;
8
+ export declare const preventXhrScriptlet: Scriptlet;
9
+ export declare const trustedPreventXhr: Scriptlet;
@@ -0,0 +1,177 @@
1
+ import { wrapMethod } from "../helpers.js";
2
+ import { absolute, requestMatcher, responseBody, } from "./request.js";
3
+ import { wrapGetter } from "./util.js";
4
+ const { apply } = Reflect;
5
+ const { parse, stringify } = JSON;
6
+ const kind = Object.prototype.toString;
7
+ const later = queueMicrotask;
8
+ // What defused requests read, by property, in place of the browser's.
9
+ const faked = new WeakMap();
10
+ let fakes = false;
11
+ /**
12
+ * Watches `open()`: the map holds what each request that matches asked
13
+ * for, until it is opened again.
14
+ */
15
+ function watchOpens(matches) {
16
+ const matched = new WeakMap();
17
+ wrapMethod(XMLHttpRequest.prototype, "open", (original, self, args) => {
18
+ const [method, url, async] = args;
19
+ const details = {
20
+ method: String(method),
21
+ url: absolute(url),
22
+ async: args.length < 3 || Boolean(async),
23
+ };
24
+ faked.delete(self);
25
+ if (matches(details))
26
+ matched.set(self, details);
27
+ else
28
+ matched.delete(self);
29
+ return original(...args);
30
+ });
31
+ return matched;
32
+ }
33
+ /** Hands the text of each response that matches to `edit`. */
34
+ export function editXhrResponses(matches, edit) {
35
+ if (typeof XMLHttpRequest !== "function")
36
+ return;
37
+ const matched = watchOpens(matches);
38
+ const readyState = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, "readyState")?.get;
39
+ // The edit runs once per response, on its first read.
40
+ const cache = new WeakMap();
41
+ const edited = (self, source) => {
42
+ const cached = cache.get(self);
43
+ if (cached !== undefined && cached.source === source)
44
+ return cached.result;
45
+ let result = source;
46
+ try {
47
+ if (typeof source === "string")
48
+ result = edit(source) ?? source;
49
+ else if (Array.isArray(source) ||
50
+ apply(kind, source, []) === "[object Object]") {
51
+ // A `json` response: the edit works on its text.
52
+ const text = edit(stringify(source));
53
+ if (text !== undefined)
54
+ result = parse(text);
55
+ }
56
+ }
57
+ catch {
58
+ result = source;
59
+ }
60
+ cache.set(self, { source, result });
61
+ return result;
62
+ };
63
+ for (const name of ["response", "responseText"]) {
64
+ wrapGetter(XMLHttpRequest.prototype, name, (read, self) => {
65
+ const value = read();
66
+ return matched.has(self) &&
67
+ readyState !== undefined &&
68
+ apply(readyState, self, []) === 4
69
+ ? edited(self, value)
70
+ : value;
71
+ });
72
+ }
73
+ }
74
+ /** Hands the text body of each request that matches to `edit`. */
75
+ export function editXhrRequests(matches, edit) {
76
+ if (typeof XMLHttpRequest !== "function")
77
+ return;
78
+ const matched = watchOpens(matches);
79
+ wrapMethod(XMLHttpRequest.prototype, "send", (original, self, args) => {
80
+ if (matched.has(self) && typeof args[0] === "string") {
81
+ try {
82
+ args[0] = edit(args[0]) ?? args[0];
83
+ }
84
+ catch {
85
+ // The body stays as the page wrote it.
86
+ }
87
+ }
88
+ return original(...args);
89
+ });
90
+ }
91
+ function fakeGetters() {
92
+ if (fakes)
93
+ return;
94
+ fakes = true;
95
+ for (const name of [
96
+ "readyState",
97
+ "status",
98
+ "statusText",
99
+ "responseURL",
100
+ "response",
101
+ "responseText",
102
+ ]) {
103
+ wrapGetter(XMLHttpRequest.prototype, name, (read, self) => {
104
+ const fake = faked.get(self);
105
+ return fake === undefined ? read() : fake[name];
106
+ });
107
+ }
108
+ }
109
+ function typed(body, type) {
110
+ switch (type) {
111
+ case "json":
112
+ try {
113
+ return parse(body);
114
+ }
115
+ catch {
116
+ return null;
117
+ }
118
+ case "arraybuffer":
119
+ return new TextEncoder().encode(body).buffer;
120
+ case "blob":
121
+ return new Blob([body]);
122
+ case "document":
123
+ return null;
124
+ }
125
+ return body;
126
+ }
127
+ function preventXhr(args, trusted) {
128
+ // Without arguments the scriptlet only logs, and there is no logger.
129
+ if (args.every((arg) => arg === ""))
130
+ return;
131
+ if (typeof XMLHttpRequest !== "function")
132
+ return;
133
+ const [props = "", directive = ""] = args;
134
+ const answer = responseBody(directive, trusted);
135
+ const matched = watchOpens(requestMatcher(props, true));
136
+ fakeGetters();
137
+ const dispatch = EventTarget.prototype.dispatchEvent;
138
+ const NativeEvent = Event;
139
+ const NativeProgressEvent = ProgressEvent;
140
+ wrapMethod(XMLHttpRequest.prototype, "send", (original, self, callArgs) => {
141
+ const details = matched.get(self);
142
+ if (details === undefined)
143
+ return original(...callArgs);
144
+ // Nothing goes out: the request answers with the directive's body.
145
+ const xhr = self;
146
+ const finish = () => {
147
+ const body = answer();
148
+ faked.set(xhr, {
149
+ readyState: 4,
150
+ status: 200,
151
+ statusText: "OK",
152
+ responseURL: details.url,
153
+ responseText: body,
154
+ response: typed(body, xhr.responseType),
155
+ });
156
+ apply(dispatch, xhr, [new NativeEvent("readystatechange")]);
157
+ for (const type of ["load", "loadend"]) {
158
+ apply(dispatch, xhr, [new NativeProgressEvent(type)]);
159
+ }
160
+ };
161
+ if (details.async)
162
+ later(finish);
163
+ else
164
+ finish();
165
+ return undefined;
166
+ });
167
+ }
168
+ export const preventXhrScriptlet = {
169
+ name: "prevent-xhr",
170
+ aliases: ["no-xhr-if"],
171
+ run: (...args) => preventXhr(args, false),
172
+ };
173
+ export const trustedPreventXhr = {
174
+ name: "trusted-prevent-xhr",
175
+ trusted: true,
176
+ run: (...args) => preventXhr(args, true),
177
+ };
@@ -0,0 +1,8 @@
1
+ import type { ScriptletCall } from "./types.js";
2
+ /**
3
+ * Runs a page's scriptlets, in the page's own world. The build bundles this
4
+ * file into one self-contained function for the preload to hand to the page
5
+ * (`scripts/build`). One scriptlet failing never stops the next, and never
6
+ * reaches the page.
7
+ */
8
+ export declare function run(calls: readonly ScriptletCall[]): void;
@@ -0,0 +1,19 @@
1
+ import { setResources } from "./helpers.js";
2
+ import { findScriptlet } from "./index.js";
3
+ /**
4
+ * Runs a page's scriptlets, in the page's own world. The build bundles this
5
+ * file into one self-contained function for the preload to hand to the page
6
+ * (`scripts/build`). One scriptlet failing never stops the next, and never
7
+ * reaches the page.
8
+ */
9
+ export function run(calls) {
10
+ for (const { name, args, resources } of calls) {
11
+ setResources(resources);
12
+ try {
13
+ findScriptlet(name)?.run(...args);
14
+ }
15
+ catch {
16
+ // A page that breaks a scriptlet only loses that scriptlet.
17
+ }
18
+ }
19
+ }
@@ -0,0 +1,5 @@
1
+ import type { Scriptlet } from "./types.js";
2
+ /** One of the values `set-constant` may set, or `INVALID`. */
3
+ export declare function safeConstant(text: string): unknown;
4
+ export declare const setConstantScriptlet: Scriptlet;
5
+ export declare const trustedSetConstant: Scriptlet;
@@ -0,0 +1,117 @@
1
+ import { onChain, runAt, tokens, trap } from "./helpers.js";
2
+ const INVALID = Symbol("invalid");
3
+ /** One of the values `set-constant` may set, or `INVALID`. */
4
+ export function safeConstant(text) {
5
+ switch (text) {
6
+ case "undefined":
7
+ return undefined;
8
+ case "false":
9
+ return false;
10
+ case "true":
11
+ return true;
12
+ case "null":
13
+ return null;
14
+ case "noopFunc":
15
+ return function () { };
16
+ case "trueFunc":
17
+ return function () {
18
+ return true;
19
+ };
20
+ case "falseFunc":
21
+ return function () {
22
+ return false;
23
+ };
24
+ case "throwFunc":
25
+ return function () {
26
+ throw new Error();
27
+ };
28
+ case "''":
29
+ case "":
30
+ return "";
31
+ case "[]":
32
+ return [];
33
+ case "{}":
34
+ return {};
35
+ }
36
+ return /^\d+$/.test(text) && Number(text) <= 0x7fff ? Number(text) : INVALID;
37
+ }
38
+ /** Anything a trusted filter says: text, or JSON after `json:` or in `{}`. */
39
+ function trustedConstant(text) {
40
+ try {
41
+ if (text.startsWith("json:"))
42
+ return JSON.parse(text.slice(5));
43
+ if (text.startsWith("{") && text.endsWith("}")) {
44
+ const parsed = JSON.parse(text);
45
+ if (typeof parsed === "object" && parsed !== null && "value" in parsed) {
46
+ return parsed.value;
47
+ }
48
+ }
49
+ }
50
+ catch {
51
+ // Not JSON after all: it is the text itself.
52
+ }
53
+ const safe = safeConstant(text);
54
+ return safe === INVALID ? text : safe;
55
+ }
56
+ function setConstant(args, parse) {
57
+ const [chain = "", raw = "", third] = args;
58
+ let constant = parse(raw);
59
+ if (chain === "" || constant === INVALID)
60
+ return;
61
+ // The third argument used to be when to run; now it is a token.
62
+ const options = tokens(args, /^(?:runAt|as)$/.test(third ?? "") ? 2 : 3);
63
+ const value = constant;
64
+ switch (options.as) {
65
+ case "function":
66
+ constant = () => value;
67
+ break;
68
+ case "callback":
69
+ constant = () => () => value;
70
+ break;
71
+ case "resolved":
72
+ constant = Promise.resolve(value);
73
+ break;
74
+ case "rejected":
75
+ constant = Promise.reject(value);
76
+ break;
77
+ }
78
+ const isNothing = (one) => one === undefined || one === null;
79
+ runAt(options.runAt ?? third, () => {
80
+ onChain(window, chain, (owner, property) => {
81
+ // A property that already holds another kind of value stays the
82
+ // page's: the constant would break what uses it.
83
+ const current = owner[property];
84
+ if (!isNothing(current) &&
85
+ !isNothing(constant) &&
86
+ typeof current !== typeof constant) {
87
+ return;
88
+ }
89
+ let overwritten = false;
90
+ trap(owner, property, {
91
+ get: (stored) => (overwritten ? stored : constant),
92
+ set(next, stored) {
93
+ // The page can only replace the constant with another kind of
94
+ // value, which no longer is what the filter meant to pin.
95
+ if (!isNothing(constant) &&
96
+ !isNothing(next) &&
97
+ typeof next !== typeof constant) {
98
+ overwritten = true;
99
+ return next;
100
+ }
101
+ return stored;
102
+ },
103
+ });
104
+ });
105
+ });
106
+ }
107
+ export const setConstantScriptlet = {
108
+ name: "set-constant",
109
+ aliases: ["set"],
110
+ run: (...args) => setConstant(args, safeConstant),
111
+ };
112
+ export const trustedSetConstant = {
113
+ name: "trusted-set-constant",
114
+ aliases: ["trusted-set"],
115
+ trusted: true,
116
+ run: (...args) => setConstant(args, trustedConstant),
117
+ };
@@ -0,0 +1,5 @@
1
+ import type { Scriptlet } from "./types.js";
2
+ export declare const preventSetTimeout: Scriptlet;
3
+ export declare const preventSetInterval: Scriptlet;
4
+ export declare const adjustSetTimeout: Scriptlet;
5
+ export declare const adjustSetInterval: Scriptlet;