|
| 1 | +import { relative } from 'pathe' |
| 2 | + |
| 3 | +export function isNodeModulePath(path: string) { |
| 4 | + return !!path.match(/[/\\]node_modules[/\\]/) || isPackageName(path) |
| 5 | +} |
| 6 | + |
| 7 | +export function isPackageName(name: string) { |
| 8 | + return name[0] === '#' || !!name.match(/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/) |
| 9 | +} |
| 10 | + |
| 11 | +export function getModuleNameFromPath(path: string) { |
| 12 | + if (isPackageName(path)) |
| 13 | + return path |
| 14 | + const match = path.replace(/\\/g, '/').match(/.*\/node_modules\/(.*)$/)?.[1] |
| 15 | + if (!match) |
| 16 | + return undefined |
| 17 | + if (match.startsWith('@')) |
| 18 | + return match.split('/').slice(0, 2).join('/') |
| 19 | + return match.split('/')[0] |
| 20 | +} |
| 21 | + |
| 22 | +function getModuleSubpathFromPath(path: string) { |
| 23 | + const match = path.match(/.*\/node_modules\/(.*)$/)?.[1] |
| 24 | + if (!match) |
| 25 | + return undefined |
| 26 | + return match |
| 27 | +} |
| 28 | + |
| 29 | +export function isBuiltInModule(name: string | undefined) { |
| 30 | + if (!name) |
| 31 | + return |
| 32 | + return ['nuxt', '#app', '#head', 'vue'].includes(name) |
| 33 | +} |
| 34 | + |
| 35 | +export function parseReadablePath(path: string, root: string) { |
| 36 | + path = path.replace(/\\/g, '/') |
| 37 | + if (isPackageName(path)) { |
| 38 | + return { |
| 39 | + moduleName: path, |
| 40 | + path, |
| 41 | + } |
| 42 | + } |
| 43 | + const moduleName = getModuleNameFromPath(path) |
| 44 | + const subpath = getModuleSubpathFromPath(path) |
| 45 | + if (moduleName && subpath) { |
| 46 | + return { |
| 47 | + moduleName, |
| 48 | + path: subpath, |
| 49 | + } |
| 50 | + } |
| 51 | + // Workaround https://github.com/unjs/pathe/issues/113 |
| 52 | + try { |
| 53 | + let result = relative(root, path) |
| 54 | + if (!result.startsWith('./') && !result.startsWith('../')) |
| 55 | + result = `./${result}` |
| 56 | + if (result.startsWith('./.nuxt/')) |
| 57 | + result = `#build${result.slice(7)}` |
| 58 | + return { path: result } |
| 59 | + } |
| 60 | + catch { |
| 61 | + return { path } |
| 62 | + } |
| 63 | +} |
0 commit comments