MCPcopy Create free account
hub / github.com/middleapi/orpc / preventNativeAwait

Function preventNativeAwait

packages/shared/src/proxy.ts:10–46  ·  view source on GitHub ↗
(target: T)

Source from the content-addressed store, hash-verified

8 * accidental awaiting of objects that aren't meant to be promises.
9 */
10export function preventNativeAwait<T extends object>(target: T): T {
11 return new Proxy(target, {
12 get(target, prop, receiver) {
13 const value = Reflect.get(target, prop, receiver)
14
15 if (prop !== 'then' || typeof value !== 'function') {
16 return value
17 }
18
19 return new Proxy(value, {
20 apply(targetFn, thisArg, args) {
21 /**
22 * Do nothing if .then not triggered by `await`
23 */
24 if (args.length !== 2 || args.some(arg => !isNativeFunction(arg))) {
25 return Reflect.apply(targetFn, thisArg, args)
26 }
27
28 let shouldOmit = true
29 args[0].call(thisArg, preventNativeAwait(new Proxy(target, {
30 get: (target, prop, receiver) => {
31 /**
32 * Only omit `then` once, in `await` resolution, afterwards it should become normal
33 */
34 if (shouldOmit && prop === 'then') {
35 shouldOmit = false
36 return undefined
37 }
38
39 return Reflect.get(target, prop, receiver)
40 },
41 })))
42 },
43 })
44 },
45 })
46}
47
48const NATIVE_FUNCTION_REGEX = /^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/
49function isNativeFunction(fn: unknown): fn is AnyFunction {

Callers 3

createORPCClientFunction · 0.90
proxy.test.tsFile · 0.90
applyFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected