-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathhookDisposables.ts
65 lines (57 loc) · 1.52 KB
/
hookDisposables.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
type FunctionPropertyNames<T> = {
[K in keyof T]: T[K] extends Function ? K : never;
}[keyof T];
type Hook = {
disposeAll: () => void;
unHook: () => void;
};
function installHook<T, K extends FunctionPropertyNames<T>>(
obj: T,
method: K,
disposeSingle: (ret: ReturnType<T[K]>, args: IArguments) => void
): Hook {
const disposes: Array<() => void> = [];
const originalFunction = obj[method];
(obj[method] as any) = function (this: any) {
const args = arguments;
const ret = (originalFunction as any).apply(this, args); // TODO: fix any?
const ctx = this;
disposes.push(() => disposeSingle.call(ctx, ret, args));
return ret;
};
return {
disposeAll: () => {
disposes.forEach((d) => d());
},
unHook: () => {
obj[method] = originalFunction;
},
};
}
const wnd = typeof window === "undefined" ? global : window;
export function installHooks() {
const hooks: Hook[] = [];
hooks.push(installHook(wnd, "setTimeout", (ret) => clearTimeout(ret as any)));
hooks.push(
installHook(wnd, "setInterval", (ret) => clearInterval(ret as any))
);
if (typeof EventTarget !== "undefined") {
hooks.push(
installHook(
EventTarget.prototype,
"addEventListener",
function (this: any, ret, args: IArguments) {
this.removeEventListener(args[0], args[1]);
}
)
);
}
return {
disposeAll: () => {
hooks.forEach((h) => h.disposeAll());
},
unHookAll: () => {
hooks.forEach((h) => h.unHook());
},
};
}