(url)
| 12 | * fileURLToPath('file:///hello world') → '/hello world' (decoded) |
| 13 | */ |
| 14 | export function fileURLToPath(url) { |
| 15 | const urlStr = typeof url === 'string' ? url : url.toString(); |
| 16 | |
| 17 | if (!urlStr.startsWith('file://')) { |
| 18 | return urlStr; |
| 19 | } |
| 20 | |
| 21 | // Parse the URL to handle all components properly |
| 22 | let parsed; |
| 23 | try { |
| 24 | parsed = new URL(urlStr); |
| 25 | } catch { |
| 26 | // If URL parsing fails, fall back to string manipulation |
| 27 | return decodeURIComponent(urlStr.slice(7)); |
| 28 | } |
| 29 | |
| 30 | const { hostname, pathname } = parsed; |
| 31 | |
| 32 | // UNC path: file://hostname/path → \\hostname\path |
| 33 | if (hostname && hostname !== 'localhost') { |
| 34 | // Decode the pathname and replace forward slashes with backslashes |
| 35 | const decodedPath = decodeURIComponent(pathname).replace(/\//g, '\\'); |
| 36 | return `\\\\${hostname}${decodedPath}`; |
| 37 | } |
| 38 | |
| 39 | // Decode the pathname to handle encoded characters |
| 40 | const path = decodeURIComponent(pathname); |
| 41 | |
| 42 | // Windows drive letter: file:///C:/path → C:\path |
| 43 | // The pathname will be /C:/path, we need to remove leading / and convert slashes |
| 44 | if (path.match(/^\/[A-Za-z]:/)) { |
| 45 | // Remove leading slash and convert to Windows backslashes |
| 46 | return path.slice(1).replace(/\//g, '\\'); |
| 47 | } |
| 48 | |
| 49 | // Unix path: file:///path → /path (already has leading slash) |
| 50 | return path; |
| 51 | } |
no test coverage detected