import { access } from 'fs/promises';
import { logger } from './logger.js';
import { ProjectState, ProjectStateSchema } from '../types/schema.js';
/**
* File validation utilities
*/
/**
* Checks if a file exists and is accessible
*/
export async function fileExists(filePath: string): Promise<boolean> {
try {
await access(filePath);
return true;
} catch {
return false;
}
}
/**
* Validates an array of file paths and returns existing/missing files
*/
export async function validateFiles(filePaths: string[]): Promise<{
existing: string[];
missing: string[];
}> {
const results = await Promise.all(
filePaths.map(async (path) => ({
path,
exists: await fileExists(path),
}))
);
const existing = results.filter((r) => r.exists).map((r) => r.path);
const missing = results.filter((r) => !r.exists).map((r) => r.path);
if (missing.length > 0) {
logger.warn('Some files no longer exist', { missing });
}
return { existing, missing };
}
/**
* Filters out non-existent files from a list
*/
export async function filterExistingFiles(filePaths: string[]): Promise<string[]> {
const { existing } = await validateFiles(filePaths);
return existing;
}
/**
* Validates project state against schema
*/
export function validateProjectState(data: unknown): ProjectState {
const parsed = ProjectStateSchema.safeParse(data);
if (!parsed.success) {
logger.error('Invalid project state schema', { error: parsed.error });
throw new Error(`Schema validation failed: ${parsed.error.message}`);
}
return parsed.data;
}