diff --git a/packages/contentstack-utilities/src/chalk.ts b/packages/contentstack-utilities/src/chalk.ts index 593b9b8ddb..7c2cae623e 100644 --- a/packages/contentstack-utilities/src/chalk.ts +++ b/packages/contentstack-utilities/src/chalk.ts @@ -1,17 +1,30 @@ /** * Chalk 5 is ESM-only. We load it via dynamic import and cache for use in CommonJS. + * + * More than one physical copy of this package can load in one process (e.g. pnpm). + * Cache on globalThis via Symbol.for so loadChalk() from any copy warms getChalk() for all. */ -let chalkInstance: typeof import('chalk').default | null = null; - export type ChalkInstance = typeof import('chalk').default; +const chalkGlobal = Symbol.for('@contentstack/cli-utilities/chalk'); + +function readCached(): ChalkInstance | undefined { + return (globalThis as unknown as Record)[chalkGlobal]; +} + +function writeCached(chalkInstance: ChalkInstance): void { + (globalThis as unknown as Record)[chalkGlobal] = chalkInstance; +} + /** * Load chalk (ESM) and cache it. Call this once during CLI init before any chalk usage. */ export async function loadChalk(): Promise { + let chalkInstance = readCached(); if (!chalkInstance) { const chalkModule = await import('chalk'); chalkInstance = chalkModule.default; + writeCached(chalkInstance); } return chalkInstance; } @@ -20,6 +33,7 @@ export async function loadChalk(): Promise { * Get the cached chalk instance. Must call loadChalk() first (e.g. in init hook). */ export function getChalk(): ChalkInstance { + const chalkInstance = readCached(); if (!chalkInstance) { throw new Error('Chalk not loaded. Ensure loadChalk() is called during init (e.g. in utils-init hook).'); }