2025-04-08 22:49:22 +07:00
|
|
|
import { _targets } from '../../init/src/patches/proxy'
|
2025-03-21 19:59:16 +07:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Returns whether the object is a proxy
|
|
|
|
|
* @param obj The object to check
|
|
|
|
|
*/
|
|
|
|
|
export function isProxy(obj: object) {
|
2025-04-08 22:49:22 +07:00
|
|
|
return _targets.has(obj)
|
2025-03-21 19:59:16 +07:00
|
|
|
}
|
|
|
|
|
|
2025-04-03 23:26:13 +07:00
|
|
|
/**
|
|
|
|
|
* Returns the target of the proxy
|
|
|
|
|
* @param obj The proxy
|
|
|
|
|
* @returns The target of the proxy
|
|
|
|
|
*/
|
2025-03-30 23:28:03 +07:00
|
|
|
export function getProxyTarget(obj: object) {
|
|
|
|
|
return _targets.get(obj)
|
|
|
|
|
}
|
2025-04-03 23:26:13 +07:00
|
|
|
|
2025-04-08 22:49:22 +07:00
|
|
|
const proxifyMetadatas = new WeakMap<object, [() => unknown, cacheable: boolean, cache?: unknown]>()
|
|
|
|
|
|
|
|
|
|
const proxifyHandler = Object.fromEntries(
|
|
|
|
|
Object.entries(Reflect).map(([k, fn]) => [
|
|
|
|
|
k,
|
|
|
|
|
(hint: object, ...args: any[]) => {
|
|
|
|
|
const m = proxifyMetadatas.get(hint)!
|
|
|
|
|
// @ts-expect-error
|
|
|
|
|
if (m[1]) return fn(m[2] ?? (m[2] = m[0]()), ...args)
|
|
|
|
|
// @ts-expect-error
|
|
|
|
|
return fn(m[0](), ...args)
|
|
|
|
|
},
|
|
|
|
|
]),
|
|
|
|
|
) as ProxyHandler<object>
|
|
|
|
|
|
2025-04-03 23:26:13 +07:00
|
|
|
export type ProxifyOptions = {
|
|
|
|
|
/**
|
|
|
|
|
* The hint for the proxified value.
|
|
|
|
|
*
|
|
|
|
|
* @default 'function'
|
|
|
|
|
*/
|
|
|
|
|
hint?: 'object' | 'function'
|
2025-04-08 22:49:22 +07:00
|
|
|
/**
|
|
|
|
|
* Whether the proxified value should be cached.
|
|
|
|
|
*/
|
|
|
|
|
cache?: boolean
|
2025-04-03 23:26:13 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Proxify a value.
|
|
|
|
|
* @param signal The signal to use to get the value.
|
|
|
|
|
* @param options The options to use for the proxified value.
|
|
|
|
|
* @returns A proxified value that will be updated when the signal is updated.
|
|
|
|
|
*/
|
|
|
|
|
export function proxify(signal: () => unknown, options?: ProxifyOptions) {
|
|
|
|
|
// biome-ignore lint/complexity/useArrowFunction: We need a function with a constructor
|
2025-04-08 22:49:22 +07:00
|
|
|
const hint = (options?.hint === 'object' ? {} : function () {}) as any
|
|
|
|
|
proxifyMetadatas.set(hint, [signal, options?.cache ?? false])
|
|
|
|
|
return new Proxy(hint, proxifyHandler)
|
2025-04-03 23:26:13 +07:00
|
|
|
}
|