nodeModulesPaths.js 2.2 KB

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