import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; export interface HostDirectoryListing { currentPath: string; parentPath: string | null; commonPaths: Array<{ name: string; path: string }>; directories: Array<{ name: string; path: string }>; } export async function listHostDirectories(targetPath?: string): Promise { const home = os.homedir(); const raw = targetPath?.trim(); let requestedPath = home; if (raw) { if (raw === "~") { requestedPath = home; } else if (raw.startsWith("~/")) { requestedPath = path.join(home, raw.slice(2)); } else { requestedPath = path.resolve(raw); } } else { // Default: prioritize ~/Projects if it exists, otherwise home directory const projectsCandidate = path.join(home, "Projects"); try { const stat = await fs.stat(projectsCandidate); if (stat.isDirectory()) { requestedPath = projectsCandidate; } } catch { requestedPath = home; } } let currentPath: string; try { currentPath = await fs.realpath(requestedPath); const stat = await fs.stat(currentPath); if (!stat.isDirectory()) { currentPath = home; } } catch { currentPath = home; } const parsed = path.parse(currentPath); const parentPath = currentPath === parsed.root ? null : path.dirname(currentPath); const commonCandidates = [ { name: "Projects", path: path.join(home, "Projects") }, { name: "Home (~)", path: home }, { name: "Desktop", path: path.join(home, "Desktop") }, { name: "Documents", path: path.join(home, "Documents") }, { name: "Downloads", path: path.join(home, "Downloads") }, ]; const commonPaths: Array<{ name: string; path: string }> = []; for (const candidate of commonCandidates) { try { const s = await fs.stat(candidate.path); if (s.isDirectory()) { commonPaths.push(candidate); } } catch { // not present on host } } const directories: Array<{ name: string; path: string }> = []; try { const entries = await fs.readdir(currentPath, { withFileTypes: true }); for (const entry of entries) { if (!entry.isDirectory()) continue; // Skip hidden folders (.git, .Trash, etc.) and node_modules if (entry.name.startsWith(".") || entry.name === "node_modules") continue; directories.push({ name: entry.name, path: path.join(currentPath, entry.name), }); } directories.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: "base" })); } catch { // Unreadable directory returns empty list } return { currentPath, parentPath, commonPaths, directories, }; }