| 1 |
/** |
| 2 |
* Instance of this class is useful in a context of a proxy trap handler. |
| 3 |
* A trap handler's main purpose is to introduce a new behavior which is prone to |
| 4 |
* being recursive. In this case, to avoid infinite recursion, we should be able to track the |
| 5 |
* stack of calls and allow the handler to call the default behavior via the Reflect API. |
| 6 |
* |
| 7 |
* The idea is that when a block of code is called via the `call` method, we increment a counter. |
| 8 |
* If the counter is greater than 0, then we know that we are in a recursive call. We can then |
| 9 |
* use the `isDisabled` method to check if we should call the default behavior or not. |
| 10 |
*/ |
| 11 |
export class TrapDisabler { |
| 12 |
constructor() { |
| 13 |
this.disabled = 0; |
| 14 |
} |
| 15 |
isDisabled() { |
| 16 |
return this.disabled > 0; |
| 17 |
} |
| 18 |
call(fn, ...args) { |
| 19 |
try { |
| 20 |
this.disabled += 1; |
| 21 |
return fn(...args); |
| 22 |
} finally { |
| 23 |
this.disabled -= 1; |
| 24 |
} |
| 25 |
} |
| 26 |
} |
| 27 |
|
| 28 |
const disablerCaches = new WeakMap(); |
| 29 |
|
| 30 |
export function getDisabler(target, prop) { |
| 31 |
if (!disablerCaches.has(target)) { |
| 32 |
disablerCaches.set(target, new Map()); |
| 33 |
} |
| 34 |
const disablerCache = disablerCaches.get(target); |
| 35 |
if (!disablerCache.has(prop)) { |
| 36 |
disablerCache.set(prop, new TrapDisabler()); |
| 37 |
} |
| 38 |
return disablerCache.get(prop); |
| 39 |
} |