You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

277 lines
9.6 KiB

4 years ago
  1. var fs = require('fs');
  2. var path = require('path');
  3. var caller = require('./caller.js');
  4. var nodeModulesPaths = require('./node-modules-paths.js');
  5. var normalizeOptions = require('./normalize-options.js');
  6. var isCore = require('./is-core');
  7. var defaultIsFile = function isFile(file, cb) {
  8. fs.stat(file, function (err, stat) {
  9. if (!err) {
  10. return cb(null, stat.isFile() || stat.isFIFO());
  11. }
  12. if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
  13. return cb(err);
  14. });
  15. };
  16. var defaultIsDir = function isDirectory(dir, cb) {
  17. fs.stat(dir, function (err, stat) {
  18. if (!err) {
  19. return cb(null, stat.isDirectory());
  20. }
  21. if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
  22. return cb(err);
  23. });
  24. };
  25. var maybeUnwrapSymlink = function maybeUnwrapSymlink(x, opts, cb) {
  26. if (opts && opts.preserveSymlinks === false) {
  27. fs.realpath(x, function (realPathErr, realPath) {
  28. if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr);
  29. else cb(null, realPathErr ? x : realPath);
  30. });
  31. } else {
  32. cb(null, x);
  33. }
  34. };
  35. module.exports = function resolve(x, options, callback) {
  36. var cb = callback;
  37. var opts = options;
  38. if (typeof options === 'function') {
  39. cb = opts;
  40. opts = {};
  41. }
  42. if (typeof x !== 'string') {
  43. var err = new TypeError('Path must be a string.');
  44. return process.nextTick(function () {
  45. cb(err);
  46. });
  47. }
  48. opts = normalizeOptions(x, opts);
  49. var isFile = opts.isFile || defaultIsFile;
  50. var isDirectory = opts.isDirectory || defaultIsDir;
  51. var readFile = opts.readFile || fs.readFile;
  52. var extensions = opts.extensions || ['.js'];
  53. var basedir = opts.basedir || path.dirname(caller());
  54. var parent = opts.filename || basedir;
  55. opts.paths = opts.paths || [];
  56. // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
  57. var absoluteStart = path.resolve(basedir);
  58. maybeUnwrapSymlink(
  59. absoluteStart,
  60. opts,
  61. function (err, realStart) {
  62. if (err) cb(err);
  63. else init(realStart);
  64. }
  65. );
  66. var res;
  67. function init(basedir) {
  68. if ((/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/).test(x)) {
  69. res = path.resolve(basedir, x);
  70. if (x === '..' || x.slice(-1) === '/') res += '/';
  71. if ((/\/$/).test(x) && res === basedir) {
  72. loadAsDirectory(res, opts.package, onfile);
  73. } else loadAsFile(res, opts.package, onfile);
  74. } else loadNodeModules(x, basedir, function (err, n, pkg) {
  75. if (err) cb(err);
  76. else if (isCore(x)) return cb(null, x);
  77. else if (n) {
  78. return maybeUnwrapSymlink(n, opts, function (err, realN) {
  79. if (err) {
  80. cb(err);
  81. } else {
  82. cb(null, realN, pkg);
  83. }
  84. });
  85. } else {
  86. var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
  87. moduleError.code = 'MODULE_NOT_FOUND';
  88. cb(moduleError);
  89. }
  90. });
  91. }
  92. function onfile(err, m, pkg) {
  93. if (err) cb(err);
  94. else if (m) cb(null, m, pkg);
  95. else loadAsDirectory(res, function (err, d, pkg) {
  96. if (err) cb(err);
  97. else if (d) {
  98. maybeUnwrapSymlink(d, opts, function (err, realD) {
  99. if (err) {
  100. cb(err);
  101. } else {
  102. cb(null, realD, pkg);
  103. }
  104. });
  105. } else {
  106. var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
  107. moduleError.code = 'MODULE_NOT_FOUND';
  108. cb(moduleError);
  109. }
  110. });
  111. }
  112. function loadAsFile(x, thePackage, callback) {
  113. var loadAsFilePackage = thePackage;
  114. var cb = callback;
  115. if (typeof loadAsFilePackage === 'function') {
  116. cb = loadAsFilePackage;
  117. loadAsFilePackage = undefined;
  118. }
  119. var exts = [''].concat(extensions);
  120. load(exts, x, loadAsFilePackage);
  121. function load(exts, x, loadPackage) {
  122. if (exts.length === 0) return cb(null, undefined, loadPackage);
  123. var file = x + exts[0];
  124. var pkg = loadPackage;
  125. if (pkg) onpkg(null, pkg);
  126. else loadpkg(path.dirname(file), onpkg);
  127. function onpkg(err, pkg_, dir) {
  128. pkg = pkg_;
  129. if (err) return cb(err);
  130. if (dir && pkg && opts.pathFilter) {
  131. var rfile = path.relative(dir, file);
  132. var rel = rfile.slice(0, rfile.length - exts[0].length);
  133. var r = opts.pathFilter(pkg, x, rel);
  134. if (r) return load(
  135. [''].concat(extensions.slice()),
  136. path.resolve(dir, r),
  137. pkg
  138. );
  139. }
  140. isFile(file, onex);
  141. }
  142. function onex(err, ex) {
  143. if (err) return cb(err);
  144. if (ex) return cb(null, file, pkg);
  145. load(exts.slice(1), x, pkg);
  146. }
  147. }
  148. }
  149. function loadpkg(dir, cb) {
  150. if (dir === '' || dir === '/') return cb(null);
  151. if (process.platform === 'win32' && (/^\w:[/\\]*$/).test(dir)) {
  152. return cb(null);
  153. }
  154. if ((/[/\\]node_modules[/\\]*$/).test(dir)) return cb(null);
  155. maybeUnwrapSymlink(dir, opts, function (unwrapErr, pkgdir) {
  156. if (unwrapErr) return loadpkg(path.dirname(dir), cb);
  157. var pkgfile = path.join(pkgdir, 'package.json');
  158. isFile(pkgfile, function (err, ex) {
  159. // on err, ex is false
  160. if (!ex) return loadpkg(path.dirname(dir), cb);
  161. readFile(pkgfile, function (err, body) {
  162. if (err) cb(err);
  163. try { var pkg = JSON.parse(body); } catch (jsonErr) {}
  164. if (pkg && opts.packageFilter) {
  165. pkg = opts.packageFilter(pkg, pkgfile);
  166. }
  167. cb(null, pkg, dir);
  168. });
  169. });
  170. });
  171. }
  172. function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
  173. var cb = callback;
  174. var fpkg = loadAsDirectoryPackage;
  175. if (typeof fpkg === 'function') {
  176. cb = fpkg;
  177. fpkg = opts.package;
  178. }
  179. maybeUnwrapSymlink(x, opts, function (unwrapErr, pkgdir) {
  180. if (unwrapErr) return cb(unwrapErr);
  181. var pkgfile = path.join(pkgdir, 'package.json');
  182. isFile(pkgfile, function (err, ex) {
  183. if (err) return cb(err);
  184. if (!ex) return loadAsFile(path.join(x, 'index'), fpkg, cb);
  185. readFile(pkgfile, function (err, body) {
  186. if (err) return cb(err);
  187. try {
  188. var pkg = JSON.parse(body);
  189. } catch (jsonErr) {}
  190. if (pkg && opts.packageFilter) {
  191. pkg = opts.packageFilter(pkg, pkgfile);
  192. }
  193. if (pkg && pkg.main) {
  194. if (typeof pkg.main !== 'string') {
  195. var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
  196. mainError.code = 'INVALID_PACKAGE_MAIN';
  197. return cb(mainError);
  198. }
  199. if (pkg.main === '.' || pkg.main === './') {
  200. pkg.main = 'index';
  201. }
  202. loadAsFile(path.resolve(x, pkg.main), pkg, function (err, m, pkg) {
  203. if (err) return cb(err);
  204. if (m) return cb(null, m, pkg);
  205. if (!pkg) return loadAsFile(path.join(x, 'index'), pkg, cb);
  206. var dir = path.resolve(x, pkg.main);
  207. loadAsDirectory(dir, pkg, function (err, n, pkg) {
  208. if (err) return cb(err);
  209. if (n) return cb(null, n, pkg);
  210. loadAsFile(path.join(x, 'index'), pkg, cb);
  211. });
  212. });
  213. return;
  214. }
  215. loadAsFile(path.join(x, '/index'), pkg, cb);
  216. });
  217. });
  218. });
  219. }
  220. function processDirs(cb, dirs) {
  221. if (dirs.length === 0) return cb(null, undefined);
  222. var dir = dirs[0];
  223. isDirectory(dir, isdir);
  224. function isdir(err, isdir) {
  225. if (err) return cb(err);
  226. if (!isdir) return processDirs(cb, dirs.slice(1));
  227. var file = path.join(dir, x);
  228. loadAsFile(file, opts.package, onfile);
  229. }
  230. function onfile(err, m, pkg) {
  231. if (err) return cb(err);
  232. if (m) return cb(null, m, pkg);
  233. loadAsDirectory(path.join(dir, x), opts.package, ondir);
  234. }
  235. function ondir(err, n, pkg) {
  236. if (err) return cb(err);
  237. if (n) return cb(null, n, pkg);
  238. processDirs(cb, dirs.slice(1));
  239. }
  240. }
  241. function loadNodeModules(x, start, cb) {
  242. processDirs(cb, nodeModulesPaths(start, opts, x));
  243. }
  244. };