-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
index.ts
59 lines (54 loc) · 1.56 KB
/
index.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
interface ProxyCallbackOptions {
path: string[];
args: unknown[];
}
type ProxyCallback = (opts: ProxyCallbackOptions) => unknown;
const noop = () => {
// noop
};
function createInnerProxy(callback: ProxyCallback, path: string[]) {
const proxy: unknown = new Proxy(noop, {
get(_obj, key) {
if (typeof key !== 'string' || key === 'then') {
// special case for if the proxy is accidentally treated
// like a PromiseLike (like in `Promise.resolve(proxy)`)
return undefined;
}
return createInnerProxy(callback, [...path, key]);
},
apply(_1, _2, args) {
const isApply = path[path.length - 1] === 'apply';
return callback({
args: isApply ? (args.length >= 2 ? args[1] : []) : args,
path: isApply ? path.slice(0, -1) : path,
});
},
});
return proxy;
}
/**
* Creates a proxy that calls the callback with the path and arguments
*
* @internal
*/
export const createRecursiveProxy = (callback: ProxyCallback) =>
createInnerProxy(callback, []);
/**
* Used in place of `new Proxy` where each handler will map 1 level deep to another value.
*
* @internal
*/
export const createFlatProxy = <TFaux>(
callback: (path: string & keyof TFaux) => any,
): TFaux => {
return new Proxy(noop, {
get(_obj, name) {
if (typeof name !== 'string' || name === 'then') {
// special case for if the proxy is accidentally treated
// like a PromiseLike (like in `Promise.resolve(proxy)`)
return undefined;
}
return callback(name as any);
},
}) as TFaux;
};