import type { CliCommandContext } from "../types/plugin"; import type { CliServicesContext, ConfigContext, MarketContext } from "./types"; type AsyncInitializer = () => Promise; async function withCleanup( initialize: AsyncInitializer, cleanup: (context: TContext) => void, operation: (context: TContext) => TResult | Promise, ): Promise { const context = await initialize(); try { return await operation(context); } finally { cleanup(context); } } export async function withConfigData( source: Pick | AsyncInitializer, operation: (context: ConfigContext) => TResult | Promise, ): Promise { const initialize = typeof source === "function" ? source : () => source.initConfigData(); return withCleanup(initialize, (context) => context.persistence.close(), operation); } export async function withMarketData( source: Pick | AsyncInitializer, operation: (context: MarketContext) => TResult | Promise, ): Promise { const initialize = typeof source === "function" ? source : () => source.initMarketData(); return withCleanup(initialize, (context) => context.persistence.close(), operation); } export async function withCliServices( source: Pick | AsyncInitializer, operation: (context: CliServicesContext) => TResult | Promise, ): Promise { const initialize = typeof source === "function" ? source : () => source.initServices(); return withCleanup(initialize, (context) => context.destroy(), operation); }