From 5b5d72ad0208528dfdbe1ced1af88c78b6ff16e7 Mon Sep 17 00:00:00 2001 From: SKYJAMES777 <3886190@qq.com> Date: Tue, 23 Jun 2026 08:41:51 +0800 Subject: [PATCH] feat: cache withTrim wrapped functions --- server/ServerSession.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/server/ServerSession.ts b/server/ServerSession.ts index 92ad563..7454f4c 100644 --- a/server/ServerSession.ts +++ b/server/ServerSession.ts @@ -2967,8 +2967,10 @@ export type UnknownFunction = (...args: unknown[]) => unknown * } * */ +// Cache to reuse wrapped functions and avoid creating new instances every call +const withTrimCache = new WeakMap(); + export function withTrim(callbackFn: CB, trimArguments= true, trimResult= true, useSignatureFrom?: UnknownFunction): CB { - // Validity checks: if (typeof callbackFn !== "function") { throw new Error("Unsupported resource type") } @@ -2976,20 +2978,18 @@ export function withTrim(callbackFn: CB, trimArgumen throw new Error("The passed argument is not a client callback function."); } + const cached = withTrimCache.get(callbackFn as object); + if (cached) return cached as CB; + const clientCallback = callbackFn as any as ClientCallback; - //@ts-ignore - return (...args: unknown[]) => { + const wrapped = (...args: unknown[]) => { return clientCallback._validateAndCall(args, trimArguments, trimResult, useSignatureFrom); - } -} + }; -/** - * - * @param params: pre-computed origin and destination - * @param errorHints Error messages will be added here - * @return if origin and destination are allowed by the "allowedOrigins" option - */ + withTrimCache.set(callbackFn as object, wrapped as object); + return wrapped as CB; +} export function originIsAllowed(params: { origin?: string, destination?: string, allowedOrigins: AllowedOriginsOptions }, errorHints?: string[]): boolean { function isSameOrigin() { return params.destination !== undefined && params.origin !== undefined && (params.origin === params.destination);