From 64bb0e366a33e098756bf7b110aea3378cc90af8 Mon Sep 17 00:00:00 2001 From: Ajay Ghanwat Date: Sun, 9 Aug 2026 12:57:37 +0530 Subject: [PATCH] perf(compiler): deduplicate client peer state synchronization --- packages/compiler/src/client-codegen.ts | 39 ++++++++++++------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/packages/compiler/src/client-codegen.ts b/packages/compiler/src/client-codegen.ts index 08eef0b5..9e7660ca 100644 --- a/packages/compiler/src/client-codegen.ts +++ b/packages/compiler/src/client-codegen.ts @@ -240,29 +240,28 @@ function functionEntry( const syncStateFromContext = stateNames .map((name) => `${name} = context.state.${name};`) .join(" "); - const peerAliases = functionAliases - .map((name) => { - const call = `context.functions[${JSON.stringify(name)}](...__wrnexusPeerArgs)`; - if (!stateNames.length) { - return `const ${name} = (...__wrnexusPeerArgs) => ${call};`; - } - return `const ${name} = (...__wrnexusPeerArgs) => { - ${syncStateToContext} - let __wrnexusPeerResult; + const peerAliases = !stateNames.length + ? functionAliases + .map((name) => `const ${name} = (...__wrnexusPeerArgs) => context.functions[${JSON.stringify(name)}](...__wrnexusPeerArgs);`) + .join("\n") + : `const __wrnexusFlush = () => { ${syncStateToContext} }; + const __wrnexusRestore = () => { ${syncStateFromContext} }; + const __wrnexusPeer = (name, args) => { + __wrnexusFlush(); + let result; try { - __wrnexusPeerResult = ${call}; - } catch (__wrnexusPeerError) { - ${syncStateFromContext} - throw __wrnexusPeerError; + result = context.functions[name](...args); + } catch (error) { + __wrnexusRestore(); + throw error; } - if (__wrnexusPeerResult && typeof __wrnexusPeerResult.then === "function") { - return Promise.resolve(__wrnexusPeerResult).finally(() => { ${syncStateFromContext} }); + if (result && typeof result.then === "function") { + return Promise.resolve(result).finally(__wrnexusRestore); } - ${syncStateFromContext} - return __wrnexusPeerResult; - };`; - }) - .join("\n"); + __wrnexusRestore(); + return result; + }; + ${functionAliases.map((name) => `const ${name} = (...__wrnexusPeerArgs) => __wrnexusPeer(${JSON.stringify(name)}, __wrnexusPeerArgs);`).join("\n")}`; const copyBack = stateNames .map( (name) =>