import { execFileSync } from 'node:child_process'; import { resolve } from 'node:path'; type YarnWorkspaceInfo = { readonly name: string; readonly location: string; }; export type WorkspaceEntry = { readonly name: string; readonly dir: string; }; const workspacesCache = new Map>(); const workspaceDirectoryMapCache = new Map>(); /** * Parses `yarn workspaces list --json` output (one object per line), root workspace included. * Workspace dirs are resolved against `repoRoot`; a relative `repoRoot` is resolved against the * process cwd first. */ export const parseYarnWorkspacesList = ( output: string, repoRoot: string, ): ReadonlyArray => { const root = resolve(repoRoot); return output .trim() .split('\n') .filter(Boolean) .map(line => JSON.parse(line) as YarnWorkspaceInfo) .map(workspace => ({ name: workspace.name, dir: resolve(root, workspace.location), })); }; export const listAllWorkspaces = (repoRoot: string): ReadonlyArray => { const cacheKey = resolve(repoRoot); const cached = workspacesCache.get(cacheKey); if (cached !== undefined) { return cached; } let rawOutput: string; try { rawOutput = execFileSync('yarn', ['workspaces', 'list', '--json'], { cwd: cacheKey, encoding: 'utf-8', }); } catch (error) { const message = error instanceof Error ? error.message : String(error); throw new Error(`Failed to list workspaces in ${cacheKey}: ${message}`, { cause: error }); } const workspaces = parseYarnWorkspacesList(rawOutput, cacheKey); workspacesCache.set(cacheKey, workspaces); return workspaces; }; export const getWorkspaceDirectoryMap = (repoRoot: string): ReadonlyMap => { const cacheKey = resolve(repoRoot); const cached = workspaceDirectoryMapCache.get(cacheKey); if (cached !== undefined) { return cached; } const map = new Map( listAllWorkspaces(cacheKey).map(workspace => [workspace.name, workspace.dir]), ); workspaceDirectoryMapCache.set(cacheKey, map); return map; };