import { promises as fs } from "fs"; import path from "path"; import os from "os"; import { setTimeout as delay } from "timers/promises"; /** * Converts WSL or Unix-style Windows paths to Windows format * @param p The path to convert * @returns Converted Windows path */ export function convertToWindowsPath(p: string): string { // Handle WSL paths (/mnt/c/...) // NEVER convert WSL paths - they are valid Linux paths that work with Node.js fs operations in WSL // Converting them to Windows format (C:\...) breaks fs operations inside WSL if (p.startsWith("/mnt/")) { return p; // Leave WSL paths unchanged } // Handle Unix-style Windows paths (/c/...) // Only convert when running on Windows if (p.match(/^\/[a-zA-Z]\//) && process.platform === "win32") { const driveLetter = p.charAt(1).toUpperCase(); const pathPart = p.slice(2).replace(/\//g, "\\"); return `${driveLetter}:${pathPart}`; } // Handle standard Windows paths, ensuring backslashes if (p.match(/^[a-zA-Z]:/)) { return p.replace(/\//g, "\\"); } // Leave non-Windows paths unchanged return p; } /** * Normalizes path by standardizing format while preserving OS-specific behavior * @param p The path to normalize * @returns Normalized path */ export function normalizePath(p: string): string { // Remove any surrounding quotes and whitespace return normalizePathFormat(p.trim().replace(/^["']|["']$/g, "")); } /** * Normalizes a path's format exactly as normalizePath does, but without * stripping surrounding quotes or whitespace. Those are legal filename * characters, so stripping them names a different file: a path that a file * operation will use must be checked against the allow-list in this form. * @param p The path to normalize * @returns Normalized path */ export function normalizePathFormat(p: string): string { // Check if this is a Unix path that should not be converted // WSL paths (/mnt/) should ALWAYS be preserved as they work correctly in WSL with Node.js fs // Regular Unix paths should also be preserved const isUnixPath = p.startsWith("/") && // Always preserve WSL paths (/mnt/c/, /mnt/d/, etc.) (p.match(/^\/mnt\/[a-z]\//i) || // On non-Windows platforms, treat all absolute paths as Unix paths process.platform !== "win32" || // On Windows, preserve Unix paths that aren't Unix-style Windows paths (/c/, /d/, etc.) (process.platform === "win32" && !p.match(/^\/[a-zA-Z]\//))); if (isUnixPath) { // For Unix paths, just normalize without converting to Windows format // Replace double slashes with single slashes and remove trailing slashes return p.replace(/\/+/g, "/").replace(/(? { try { return await fs.realpath(p); } catch { await delay(retryDelayMs); return await fs.realpath(p); } }