diff --git a/src/channels/plugins/bundled.ts b/src/channels/plugins/bundled.ts index ec367cbeb2a..67af22f3298 100644 --- a/src/channels/plugins/bundled.ts +++ b/src/channels/plugins/bundled.ts @@ -88,6 +88,8 @@ type BundledChannelLoadContext = { }; const log = createSubsystemLogger("channels"); +const MAX_BUNDLED_CHANNEL_LOAD_CONTEXTS = 32; +const bundledChannelLoadContextsByRoot = new Map(); function resolveChannelPluginModuleEntry( moduleExport: unknown, @@ -310,9 +312,27 @@ function resolveActiveBundledChannelLoadScope(): { loadContext: BundledChannelLoadContext; } { const rootScope = resolveBundledChannelRootScope(); + const cachedContext = bundledChannelLoadContextsByRoot.get(rootScope.cacheKey); + if (cachedContext) { + bundledChannelLoadContextsByRoot.delete(rootScope.cacheKey); + bundledChannelLoadContextsByRoot.set(rootScope.cacheKey, cachedContext); + return { + rootScope, + loadContext: cachedContext, + }; + } + const loadContext = createBundledChannelLoadContext(); + bundledChannelLoadContextsByRoot.set(rootScope.cacheKey, loadContext); + while (bundledChannelLoadContextsByRoot.size > MAX_BUNDLED_CHANNEL_LOAD_CONTEXTS) { + const oldestKey = bundledChannelLoadContextsByRoot.keys().next().value; + if (oldestKey === undefined) { + break; + } + bundledChannelLoadContextsByRoot.delete(oldestKey); + } return { rootScope, - loadContext: createBundledChannelLoadContext(), + loadContext, }; }