async.js 11 KB

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