UNPKG

@monitoro/herd

Version:

Automate your browser, build AI web tools and MCP servers with Monitoro Herd

47 lines (46 loc) 1.91 kB
import * as fs from 'fs'; import * as path from 'path'; /** * Find package.json by walking up the directory tree from a starting directory * @param startDir - Directory to start searching from (defaults to current file's directory) * @returns Path to the found package.json file * @throws Error if package.json is not found */ export function findPackageJson(startDir) { let currentDir = startDir || path.dirname(new URL(import.meta.url).pathname); while (currentDir !== path.dirname(currentDir)) { // Stop at filesystem root const packageJsonPath = path.join(currentDir, 'package.json'); if (fs.existsSync(packageJsonPath)) { return packageJsonPath; } currentDir = path.dirname(currentDir); } throw new Error('package.json not found in directory tree'); } /** * Read and parse package.json from the directory tree * @param startDir - Directory to start searching from (defaults to current file's directory) * @returns Parsed package.json object * @throws Error if package.json is not found or cannot be parsed */ export function readPackageJson(startDir) { const packageJsonPath = findPackageJson(startDir); const content = fs.readFileSync(packageJsonPath, 'utf-8'); return JSON.parse(content); } /** * Get the version from package.json with fallback * @param startDir - Directory to start searching from (defaults to current file's directory) * @param fallbackVersion - Version to use if package.json cannot be read (defaults to '0.0.0') * @returns Version string */ export function getPackageVersion(startDir, fallbackVersion = '0.0.0') { try { const packageJson = readPackageJson(startDir); return packageJson.version || fallbackVersion; } catch (error) { console.warn('Warning: Could not read version from package.json, using fallback'); return fallbackVersion; } }