-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmonkey-patch.ts
22 lines (18 loc) · 955 Bytes
/
monkey-patch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* eslint-disable @typescript-eslint/no-unsafe-argument, @typescript-eslint/ban-types, prefer-rest-params, @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-unsafe-return */
export type Trampoline = Function & { disabled?: boolean }
const trampolines: Trampoline[] = []
export function patch(object: any, method: string, patcher: (f: Function) => Function, mem?: Trampoline[]): void {
if (typeof object[method] !== 'function') throw new Error(`monkey-patch: ${method} is not a function`)
const orig = object[method]
const patched = patcher(orig)
object[method] = function trampoline() {
return (trampoline as Trampoline).disabled ? orig.apply(this, arguments) : patched.apply(this, arguments)
}
trampolines.push(object[method])
if (mem) mem.push(object[method])
}
export function unpatch(functions?: Trampoline[]) {
for (const trampoline of (functions || trampolines)) {
trampoline.disabled = true
}
}