From e48e45226f71db9d754350c9d0c1620543d76c85 Mon Sep 17 00:00:00 2001 From: PalmDevs Date: Mon, 14 Jul 2025 09:53:06 +0700 Subject: [PATCH] fix(utils/proxy): accept nested options in `destructure` --- lib/externals/src/react-native-clipboard.ts | 17 +++++--- lib/utils/src/proxy.ts | 43 ++++++++++++++------- 2 files changed, 40 insertions(+), 20 deletions(-) diff --git a/lib/externals/src/react-native-clipboard.ts b/lib/externals/src/react-native-clipboard.ts index e474687..6e375a6 100644 --- a/lib/externals/src/react-native-clipboard.ts +++ b/lib/externals/src/react-native-clipboard.ts @@ -49,9 +49,14 @@ let ClipboardModule: typeof import('@react-native-clipboard/clipboard') = }, )! -export const { useClipboard } = destructure(ClipboardModule, { - hint: () => {}, -}) -export const { default: Clipboard } = destructure(ClipboardModule, { - hint: {}, -}) +export const { default: Clipboard, useClipboard } = destructure( + ClipboardModule, + { + default: { + hint: {}, + }, + useClipboard: { + hint: () => {}, + }, + }, +) diff --git a/lib/utils/src/proxy.ts b/lib/utils/src/proxy.ts index c1b9ec4..2686559 100644 --- a/lib/utils/src/proxy.ts +++ b/lib/utils/src/proxy.ts @@ -181,6 +181,17 @@ function unproxifyFromHint(hint: object) { return meta[0]() as any } +export type DestructureOptions = { + [K in keyof T]?: ProxifyOptions +} + +export type DestructureResult< + T extends object, + O extends DestructureOptions, +> = { + [K in keyof T]: O[K] extends ProxifyOptions ? T[K] : never +} + /** * Destructure a proxified value. * @@ -208,25 +219,29 @@ function unproxifyFromHint(hint: object) { * z // TypeError: Cannot destructure and proxify null (reading 'z') * ``` */ -export function destructure( - proxified: T, - options?: ProxifyOptions, -): T { +export function destructure< + T extends object, + const O extends DestructureOptions, +>(proxified: T, options?: O): DestructureResult { return new Proxy({} as T, { get: (_, p, r) => - proxify(() => { - const v = Reflect.get(unproxify(proxified), p, r) + proxify( + () => { + const v = Reflect.get(unproxify(proxified), p, r) - if (v == null) + if (v == null) + throw new TypeError( + `Cannot destructure and proxify ${v} (reading '${String(p)}')`, + ) + if (typeof v === 'function' || typeof v === 'object') + return v throw new TypeError( - `Cannot destructure and proxify ${v} (reading '${String(p)}')`, + `Cannot destructure and proxify a primitive (reading '${String(p)}')`, ) - if (typeof v === 'function' || typeof v === 'object') return v - throw new TypeError( - `Cannot destructure and proxify a primitive (reading '${String(p)}')`, - ) - }, options), - }) + }, + options?.[p as keyof T], + ), + }) as DestructureResult } /**