1import { existsSync } from 'fs';
2import { dirname, join } from 'path';
3import { fileURLToPath } from 'url';
4
5export function findWorkspaceRoot(): string {
6 const __dirname = dirname(fileURLToPath(import.meta.url));
7
8 let currentDir = __dirname;
9
10 while (currentDir !== '/') {
11 const packageJsonPath = join(currentDir, 'package.json');
12 const pnpmWorkspacePath = join(currentDir, 'pnpm-workspace.yaml');
13
14 if (existsSync(packageJsonPath) && existsSync(pnpmWorkspacePath)) {
15 return currentDir;
16 }
17
18 currentDir = dirname(currentDir);
19 }
20
21 throw new Error('Could not find workspace root (looking for pnpm-workspace.yaml)');
22}
23
24export function getRelativePath(from: string, to: string): string {
25 const fromParts = from.split('/');
26 const toParts = to.split('/');
27
28 let commonLength = 0;
29 while (
30 commonLength < fromParts.length &&
31 commonLength < toParts.length &&
32 fromParts[commonLength] === toParts[commonLength]
33 ) {
34 commonLength++;
35 }
36
37 const upLevels = fromParts.length - commonLength;
38 const relativeParts = Array(upLevels).fill('..').concat(toParts.slice(commonLength));
39
40 return relativeParts.join('/') || '.';
41}