| 1 |
// Returns CJS module (sync or async) path resolver |
| 2 |
|
| 3 |
"use strict"; |
| 4 |
|
| 5 |
var dirname = function (path) { return path.slice(0, path.lastIndexOf("/")) || "/"; }; |
| 6 |
var join = function (path1, path2) { return path1 === "/" ? path1 + path2 : path1 + "/" + path2; }; |
| 7 |
|
| 8 |
module.exports = function (extensions, confirmFile, resolvePackageMain) { |
| 9 |
var resolveFile = function (path, extIndex) { |
| 10 |
var targetPath = path + (extIndex == null ? "" : extensions[extIndex]); |
| 11 |
return confirmFile(targetPath).then(function (result) { |
| 12 |
if (result) return result; |
| 13 |
if (extIndex == null) extIndex = 0; |
| 14 |
else ++extIndex; |
| 15 |
if (!extensions[extIndex]) return null; |
| 16 |
return resolveFile(path, extIndex); |
| 17 |
}); |
| 18 |
}; |
| 19 |
var resolveDirectory = function (path) { |
| 20 |
return resolvePackageMain(path).then(function (result) { |
| 21 |
if (result) { |
| 22 |
var mainPath = join(path, result); |
| 23 |
return resolveFile(mainPath).then(function (mainResult) { |
| 24 |
if (mainResult) return mainResult; |
| 25 |
return resolveFile(join(mainPath, "index"), 0).then(function (mainDirResult) { |
| 26 |
if (mainDirResult) return mainDirResult; |
| 27 |
return resolveFile(join(path, "index"), 0); |
| 28 |
}); |
| 29 |
}); |
| 30 |
} |
| 31 |
return resolveFile(join(path, "index"), 0); |
| 32 |
}); |
| 33 |
}; |
| 34 |
var resolveLocal = function (path) { |
| 35 |
var pathChar = path.charAt(path.length - 1); |
| 36 |
if (pathChar === "/") return resolveDirectory(path); |
| 37 |
if (pathChar === ".") { |
| 38 |
pathChar = path.charAt(path.length - 2); |
| 39 |
if (pathChar === "/") return resolveDirectory(path); |
| 40 |
if (pathChar === ".") { |
| 41 |
if (path.charAt(path.length - 3) === "/") return resolveDirectory(path); |
| 42 |
} |
| 43 |
} |
| 44 |
return resolveFile(path).then(function (result) { |
| 45 |
return result || resolveDirectory(path); |
| 46 |
}); |
| 47 |
}; |
| 48 |
var resolveExternal = function (dir, path) { |
| 49 |
return resolveLocal(join(dir, "node_modules") + "/" + path).then(function (result) { |
| 50 |
if (result) return result; |
| 51 |
if (dir === "/") return null; |
| 52 |
return resolveExternal(dirname(dir), path); |
| 53 |
}); |
| 54 |
}; |
| 55 |
return function (dir, path) { |
| 56 |
var pathChar; |
| 57 |
if (path.charAt(0) === "/") return resolveLocal(path); |
| 58 |
if (path.charAt(0) === ".") { |
| 59 |
pathChar = path.charAt(1); |
| 60 |
if (!pathChar || pathChar === "/") return resolveLocal(join(dir, path)); |
| 61 |
if (pathChar === ".") { |
| 62 |
pathChar = path.charAt(2); |
| 63 |
if (!pathChar || pathChar === "/") return resolveLocal(join(dir, path)); |
| 64 |
} |
| 65 |
} |
| 66 |
return resolveExternal(dir, path); |
| 67 |
}; |
| 68 |
}; |