node_modules_paths.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = nodeModulesPaths;
  6. var _path;
  7. function _load_path() {
  8. return (_path = _interopRequireDefault(require('path')));
  9. }
  10. var _realpathNative;
  11. function _load_realpathNative() {
  12. return (_realpathNative = require('realpath-native'));
  13. }
  14. function _interopRequireDefault(obj) {
  15. return obj && obj.__esModule ? obj : {default: obj};
  16. }
  17. function nodeModulesPaths(basedir, options) {
  18. const modules =
  19. options && options.moduleDirectory
  20. ? [].concat(options.moduleDirectory)
  21. : ['node_modules'];
  22. // ensure that `basedir` is an absolute path at this point,
  23. // resolving against the process' current working directory
  24. const basedirAbs = (_path || _load_path()).default.resolve(basedir);
  25. let prefix = '/';
  26. if (/^([A-Za-z]:)/.test(basedirAbs)) {
  27. prefix = '';
  28. } else if (/^\\\\/.test(basedirAbs)) {
  29. prefix = '\\\\';
  30. }
  31. // The node resolution algorithm (as implemented by NodeJS and TypeScript)
  32. // traverses parents of the physical path, not the symlinked path
  33. let physicalBasedir;
  34. try {
  35. physicalBasedir = (0, (_realpathNative || _load_realpathNative()).sync)(
  36. basedirAbs
  37. );
  38. } catch (err) {
  39. // realpath can throw, e.g. on mapped drives
  40. physicalBasedir = basedirAbs;
  41. }
  42. const paths = [physicalBasedir];
  43. let parsed = (_path || _load_path()).default.parse(physicalBasedir);
  44. while (parsed.dir !== paths[paths.length - 1]) {
  45. paths.push(parsed.dir);
  46. parsed = (_path || _load_path()).default.parse(parsed.dir);
  47. }
  48. const dirs = paths
  49. .reduce(
  50. (dirs, aPath) =>
  51. dirs.concat(
  52. modules.map(
  53. moduleDir =>
  54. (_path || _load_path()).default.isAbsolute(moduleDir)
  55. ? aPath === basedirAbs
  56. ? moduleDir
  57. : ''
  58. : (_path || _load_path()).default.join(prefix, aPath, moduleDir)
  59. )
  60. ),
  61. []
  62. )
  63. .filter(dir => dir !== '');
  64. return options.paths ? dirs.concat(options.paths) : dirs;
  65. }
  66. /**
  67. * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
  68. *
  69. * This source code is licensed under the MIT license found in the
  70. * LICENSE file in the root directory of this source tree.
  71. *
  72. * Adapted from: https://github.com/substack/node-resolve
  73. *
  74. *
  75. */