resolver.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. function path() {
  7. const data = _interopRequireWildcard(require('path'));
  8. path = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _chalk() {
  14. const data = _interopRequireDefault(require('chalk'));
  15. _chalk = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. function _slash() {
  21. const data = _interopRequireDefault(require('slash'));
  22. _slash = function () {
  23. return data;
  24. };
  25. return data;
  26. }
  27. function _jestUtil() {
  28. const data = require('jest-util');
  29. _jestUtil = function () {
  30. return data;
  31. };
  32. return data;
  33. }
  34. var _ModuleNotFoundError = _interopRequireDefault(
  35. require('./ModuleNotFoundError')
  36. );
  37. var _defaultResolver = _interopRequireDefault(require('./defaultResolver'));
  38. var _fileWalkers = require('./fileWalkers');
  39. var _isBuiltinModule = _interopRequireDefault(require('./isBuiltinModule'));
  40. var _nodeModulesPaths = _interopRequireDefault(require('./nodeModulesPaths'));
  41. var _shouldLoadAsEsm = _interopRequireWildcard(require('./shouldLoadAsEsm'));
  42. function _interopRequireDefault(obj) {
  43. return obj && obj.__esModule ? obj : {default: obj};
  44. }
  45. function _getRequireWildcardCache(nodeInterop) {
  46. if (typeof WeakMap !== 'function') return null;
  47. var cacheBabelInterop = new WeakMap();
  48. var cacheNodeInterop = new WeakMap();
  49. return (_getRequireWildcardCache = function (nodeInterop) {
  50. return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
  51. })(nodeInterop);
  52. }
  53. function _interopRequireWildcard(obj, nodeInterop) {
  54. if (!nodeInterop && obj && obj.__esModule) {
  55. return obj;
  56. }
  57. if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
  58. return {default: obj};
  59. }
  60. var cache = _getRequireWildcardCache(nodeInterop);
  61. if (cache && cache.has(obj)) {
  62. return cache.get(obj);
  63. }
  64. var newObj = {};
  65. var hasPropertyDescriptor =
  66. Object.defineProperty && Object.getOwnPropertyDescriptor;
  67. for (var key in obj) {
  68. if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
  69. var desc = hasPropertyDescriptor
  70. ? Object.getOwnPropertyDescriptor(obj, key)
  71. : null;
  72. if (desc && (desc.get || desc.set)) {
  73. Object.defineProperty(newObj, key, desc);
  74. } else {
  75. newObj[key] = obj[key];
  76. }
  77. }
  78. }
  79. newObj.default = obj;
  80. if (cache) {
  81. cache.set(obj, newObj);
  82. }
  83. return newObj;
  84. }
  85. function _defineProperty(obj, key, value) {
  86. if (key in obj) {
  87. Object.defineProperty(obj, key, {
  88. value: value,
  89. enumerable: true,
  90. configurable: true,
  91. writable: true
  92. });
  93. } else {
  94. obj[key] = value;
  95. }
  96. return obj;
  97. }
  98. const NATIVE_PLATFORM = 'native'; // We might be inside a symlink.
  99. const resolvedCwd = (0, _jestUtil().tryRealpath)(process.cwd());
  100. const {NODE_PATH} = process.env;
  101. const nodePaths = NODE_PATH
  102. ? NODE_PATH.split(path().delimiter)
  103. .filter(Boolean) // The resolver expects absolute paths.
  104. .map(p => path().resolve(resolvedCwd, p))
  105. : undefined;
  106. class Resolver {
  107. constructor(moduleMap, options) {
  108. _defineProperty(this, '_options', void 0);
  109. _defineProperty(this, '_moduleMap', void 0);
  110. _defineProperty(this, '_moduleIDCache', void 0);
  111. _defineProperty(this, '_moduleNameCache', void 0);
  112. _defineProperty(this, '_modulePathCache', void 0);
  113. _defineProperty(this, '_supportsNativePlatform', void 0);
  114. this._options = {
  115. defaultPlatform: options.defaultPlatform,
  116. extensions: options.extensions,
  117. hasCoreModules:
  118. options.hasCoreModules === undefined ? true : options.hasCoreModules,
  119. moduleDirectories: options.moduleDirectories || ['node_modules'],
  120. moduleNameMapper: options.moduleNameMapper,
  121. modulePaths: options.modulePaths,
  122. platforms: options.platforms,
  123. resolver: options.resolver,
  124. rootDir: options.rootDir
  125. };
  126. this._supportsNativePlatform = options.platforms
  127. ? options.platforms.includes(NATIVE_PLATFORM)
  128. : false;
  129. this._moduleMap = moduleMap;
  130. this._moduleIDCache = new Map();
  131. this._moduleNameCache = new Map();
  132. this._modulePathCache = new Map();
  133. }
  134. static tryCastModuleNotFoundError(error) {
  135. if (error instanceof _ModuleNotFoundError.default) {
  136. return error;
  137. }
  138. const casted = error;
  139. if (casted.code === 'MODULE_NOT_FOUND') {
  140. return _ModuleNotFoundError.default.duckType(casted);
  141. }
  142. return null;
  143. }
  144. static clearDefaultResolverCache() {
  145. (0, _fileWalkers.clearFsCache)();
  146. (0, _shouldLoadAsEsm.clearCachedLookups)();
  147. }
  148. static findNodeModule(path, options) {
  149. const resolver = options.resolver
  150. ? require(options.resolver)
  151. : _defaultResolver.default;
  152. const paths = options.paths;
  153. try {
  154. return resolver(path, {
  155. basedir: options.basedir,
  156. browser: options.browser,
  157. conditions: options.conditions,
  158. defaultResolver: _defaultResolver.default,
  159. extensions: options.extensions,
  160. moduleDirectory: options.moduleDirectory,
  161. paths: paths ? (nodePaths || []).concat(paths) : nodePaths,
  162. rootDir: options.rootDir
  163. });
  164. } catch (e) {
  165. if (options.throwIfNotFound) {
  166. throw e;
  167. }
  168. }
  169. return null;
  170. } // unstable as it should be replaced by https://github.com/nodejs/modules/issues/393, and we don't want people to use it
  171. resolveModuleFromDirIfExists(dirname, moduleName, options) {
  172. const paths =
  173. (options === null || options === void 0 ? void 0 : options.paths) ||
  174. this._options.modulePaths;
  175. const moduleDirectory = this._options.moduleDirectories;
  176. const stringifiedOptions = options ? JSON.stringify(options) : '';
  177. const key = dirname + path().delimiter + moduleName + stringifiedOptions;
  178. const defaultPlatform = this._options.defaultPlatform;
  179. const extensions = this._options.extensions.slice();
  180. let module;
  181. if (this._supportsNativePlatform) {
  182. extensions.unshift(
  183. ...this._options.extensions.map(ext => '.' + NATIVE_PLATFORM + ext)
  184. );
  185. }
  186. if (defaultPlatform) {
  187. extensions.unshift(
  188. ...this._options.extensions.map(ext => '.' + defaultPlatform + ext)
  189. );
  190. } // 1. If we have already resolved this module for this directory name,
  191. // return a value from the cache.
  192. const cacheResult = this._moduleNameCache.get(key);
  193. if (cacheResult) {
  194. return cacheResult;
  195. } // 2. Check if the module is a haste module.
  196. module = this.getModule(moduleName);
  197. if (module) {
  198. this._moduleNameCache.set(key, module);
  199. return module;
  200. } // 3. Check if the module is a node module and resolve it based on
  201. // the node module resolution algorithm. If skipNodeResolution is given we
  202. // ignore all modules that look like node modules (ie. are not relative
  203. // requires). This enables us to speed up resolution when we build a
  204. // dependency graph because we don't have to look at modules that may not
  205. // exist and aren't mocked.
  206. const skipResolution =
  207. options && options.skipNodeResolution && !moduleName.includes(path().sep);
  208. const resolveNodeModule = (name, throwIfNotFound = false) => {
  209. if (this.isCoreModule(name)) {
  210. return name;
  211. }
  212. return Resolver.findNodeModule(name, {
  213. basedir: dirname,
  214. conditions:
  215. options === null || options === void 0 ? void 0 : options.conditions,
  216. extensions,
  217. moduleDirectory,
  218. paths,
  219. resolver: this._options.resolver,
  220. rootDir: this._options.rootDir,
  221. throwIfNotFound
  222. });
  223. };
  224. if (!skipResolution) {
  225. module = resolveNodeModule(moduleName, Boolean(process.versions.pnp));
  226. if (module) {
  227. this._moduleNameCache.set(key, module);
  228. return module;
  229. }
  230. } // 4. Resolve "haste packages" which are `package.json` files outside of
  231. // `node_modules` folders anywhere in the file system.
  232. const parts = moduleName.split('/');
  233. const hastePackage = this.getPackage(parts.shift());
  234. if (hastePackage) {
  235. try {
  236. const module = path().join.apply(
  237. path(),
  238. [path().dirname(hastePackage)].concat(parts)
  239. ); // try resolving with custom resolver first to support extensions,
  240. // then fallback to require.resolve
  241. const resolvedModule =
  242. resolveNodeModule(module) || require.resolve(module);
  243. this._moduleNameCache.set(key, resolvedModule);
  244. return resolvedModule;
  245. } catch {}
  246. }
  247. return null;
  248. }
  249. resolveModule(from, moduleName, options) {
  250. const dirname = path().dirname(from);
  251. const module =
  252. this.resolveStubModuleName(from, moduleName) ||
  253. this.resolveModuleFromDirIfExists(dirname, moduleName, options);
  254. if (module) return module; // 5. Throw an error if the module could not be found. `resolve.sync` only
  255. // produces an error based on the dirname but we have the actual current
  256. // module name available.
  257. const relativePath =
  258. (0, _slash().default)(path().relative(this._options.rootDir, from)) ||
  259. '.';
  260. throw new _ModuleNotFoundError.default(
  261. `Cannot find module '${moduleName}' from '${relativePath}'`,
  262. moduleName
  263. );
  264. }
  265. _isAliasModule(moduleName) {
  266. const moduleNameMapper = this._options.moduleNameMapper;
  267. if (!moduleNameMapper) {
  268. return false;
  269. }
  270. return moduleNameMapper.some(({regex}) => regex.test(moduleName));
  271. }
  272. isCoreModule(moduleName) {
  273. return (
  274. this._options.hasCoreModules &&
  275. ((0, _isBuiltinModule.default)(moduleName) ||
  276. (moduleName.startsWith('node:') &&
  277. (0, _isBuiltinModule.default)(moduleName.slice('node:'.length)))) &&
  278. !this._isAliasModule(moduleName)
  279. );
  280. }
  281. getModule(name) {
  282. return this._moduleMap.getModule(
  283. name,
  284. this._options.defaultPlatform,
  285. this._supportsNativePlatform
  286. );
  287. }
  288. getModulePath(from, moduleName) {
  289. if (moduleName[0] !== '.' || path().isAbsolute(moduleName)) {
  290. return moduleName;
  291. }
  292. return path().normalize(path().dirname(from) + '/' + moduleName);
  293. }
  294. getPackage(name) {
  295. return this._moduleMap.getPackage(
  296. name,
  297. this._options.defaultPlatform,
  298. this._supportsNativePlatform
  299. );
  300. }
  301. getMockModule(from, name) {
  302. const mock = this._moduleMap.getMockModule(name);
  303. if (mock) {
  304. return mock;
  305. } else {
  306. const moduleName = this.resolveStubModuleName(from, name);
  307. if (moduleName) {
  308. return this.getModule(moduleName) || moduleName;
  309. }
  310. }
  311. return null;
  312. }
  313. getModulePaths(from) {
  314. const cachedModule = this._modulePathCache.get(from);
  315. if (cachedModule) {
  316. return cachedModule;
  317. }
  318. const moduleDirectory = this._options.moduleDirectories;
  319. const paths = (0, _nodeModulesPaths.default)(from, {
  320. moduleDirectory
  321. });
  322. if (paths[paths.length - 1] === undefined) {
  323. // circumvent node-resolve bug that adds `undefined` as last item.
  324. paths.pop();
  325. }
  326. this._modulePathCache.set(from, paths);
  327. return paths;
  328. }
  329. getModuleID(virtualMocks, from, moduleName = '', options) {
  330. const stringifiedOptions = options ? JSON.stringify(options) : '';
  331. const key = from + path().delimiter + moduleName + stringifiedOptions;
  332. const cachedModuleID = this._moduleIDCache.get(key);
  333. if (cachedModuleID) {
  334. return cachedModuleID;
  335. }
  336. const moduleType = this._getModuleType(moduleName);
  337. const absolutePath = this._getAbsolutePath(
  338. virtualMocks,
  339. from,
  340. moduleName,
  341. options
  342. );
  343. const mockPath = this._getMockPath(from, moduleName);
  344. const sep = path().delimiter;
  345. const id =
  346. moduleType +
  347. sep +
  348. (absolutePath ? absolutePath + sep : '') +
  349. (mockPath ? mockPath + sep : '') +
  350. (stringifiedOptions ? stringifiedOptions + sep : '');
  351. this._moduleIDCache.set(key, id);
  352. return id;
  353. }
  354. _getModuleType(moduleName) {
  355. return this.isCoreModule(moduleName) ? 'node' : 'user';
  356. }
  357. _getAbsolutePath(virtualMocks, from, moduleName, options) {
  358. if (this.isCoreModule(moduleName)) {
  359. return moduleName;
  360. }
  361. return this._isModuleResolved(from, moduleName)
  362. ? this.getModule(moduleName)
  363. : this._getVirtualMockPath(virtualMocks, from, moduleName, options);
  364. }
  365. _getMockPath(from, moduleName) {
  366. return !this.isCoreModule(moduleName)
  367. ? this.getMockModule(from, moduleName)
  368. : null;
  369. }
  370. _getVirtualMockPath(virtualMocks, from, moduleName, options) {
  371. const virtualMockPath = this.getModulePath(from, moduleName);
  372. return virtualMocks.get(virtualMockPath)
  373. ? virtualMockPath
  374. : moduleName
  375. ? this.resolveModule(from, moduleName, options)
  376. : from;
  377. }
  378. _isModuleResolved(from, moduleName) {
  379. return !!(
  380. this.getModule(moduleName) || this.getMockModule(from, moduleName)
  381. );
  382. }
  383. resolveStubModuleName(from, moduleName) {
  384. const dirname = path().dirname(from);
  385. const paths = this._options.modulePaths;
  386. const extensions = this._options.extensions.slice();
  387. const moduleDirectory = this._options.moduleDirectories;
  388. const moduleNameMapper = this._options.moduleNameMapper;
  389. const resolver = this._options.resolver;
  390. const defaultPlatform = this._options.defaultPlatform;
  391. if (this._supportsNativePlatform) {
  392. extensions.unshift(
  393. ...this._options.extensions.map(ext => '.' + NATIVE_PLATFORM + ext)
  394. );
  395. }
  396. if (defaultPlatform) {
  397. extensions.unshift(
  398. ...this._options.extensions.map(ext => '.' + defaultPlatform + ext)
  399. );
  400. }
  401. if (moduleNameMapper) {
  402. for (const {moduleName: mappedModuleName, regex} of moduleNameMapper) {
  403. if (regex.test(moduleName)) {
  404. // Note: once a moduleNameMapper matches the name, it must result
  405. // in a module, or else an error is thrown.
  406. const matches = moduleName.match(regex);
  407. const mapModuleName = matches
  408. ? moduleName =>
  409. moduleName.replace(
  410. /\$([0-9]+)/g,
  411. (_, index) => matches[parseInt(index, 10)]
  412. )
  413. : moduleName => moduleName;
  414. const possibleModuleNames = Array.isArray(mappedModuleName)
  415. ? mappedModuleName
  416. : [mappedModuleName];
  417. let module = null;
  418. for (const possibleModuleName of possibleModuleNames) {
  419. const updatedName = mapModuleName(possibleModuleName);
  420. module =
  421. this.getModule(updatedName) ||
  422. Resolver.findNodeModule(updatedName, {
  423. basedir: dirname,
  424. extensions,
  425. moduleDirectory,
  426. paths,
  427. resolver,
  428. rootDir: this._options.rootDir
  429. });
  430. if (module) {
  431. break;
  432. }
  433. }
  434. if (!module) {
  435. throw createNoMappedModuleFoundError(
  436. moduleName,
  437. mapModuleName,
  438. mappedModuleName,
  439. regex,
  440. resolver
  441. );
  442. }
  443. return module;
  444. }
  445. }
  446. }
  447. return null;
  448. }
  449. }
  450. exports.default = Resolver;
  451. _defineProperty(Resolver, 'ModuleNotFoundError', _ModuleNotFoundError.default);
  452. _defineProperty(Resolver, 'unstable_shouldLoadAsEsm', _shouldLoadAsEsm.default);
  453. const createNoMappedModuleFoundError = (
  454. moduleName,
  455. mapModuleName,
  456. mappedModuleName,
  457. regex,
  458. resolver
  459. ) => {
  460. const mappedAs = Array.isArray(mappedModuleName)
  461. ? JSON.stringify(mappedModuleName.map(mapModuleName), null, 2)
  462. : mappedModuleName;
  463. const original = Array.isArray(mappedModuleName)
  464. ? JSON.stringify(mappedModuleName, null, 6) // using 6 because of misalignment when nested below
  465. .slice(0, -1) + ' ]' /// align last bracket correctly as well
  466. : mappedModuleName;
  467. const error = new Error(
  468. _chalk().default.red(`${_chalk().default.bold('Configuration error')}:
  469. Could not locate module ${_chalk().default.bold(moduleName)} mapped as:
  470. ${_chalk().default.bold(mappedAs)}.
  471. Please check your configuration for these entries:
  472. {
  473. "moduleNameMapper": {
  474. "${regex.toString()}": "${_chalk().default.bold(original)}"
  475. },
  476. "resolver": ${_chalk().default.bold(String(resolver))}
  477. }`)
  478. );
  479. error.name = '';
  480. return error;
  481. };