ResolverFactory.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Resolver = require("./Resolver");
  7. const SyncAsyncFileSystemDecorator = require("./SyncAsyncFileSystemDecorator");
  8. const ParsePlugin = require("./ParsePlugin");
  9. const DescriptionFilePlugin = require("./DescriptionFilePlugin");
  10. const NextPlugin = require("./NextPlugin");
  11. const TryNextPlugin = require("./TryNextPlugin");
  12. const ModuleKindPlugin = require("./ModuleKindPlugin");
  13. const FileKindPlugin = require("./FileKindPlugin");
  14. const JoinRequestPlugin = require("./JoinRequestPlugin");
  15. const ModulesInHierachicDirectoriesPlugin = require("./ModulesInHierachicDirectoriesPlugin");
  16. const ModulesInRootPlugin = require("./ModulesInRootPlugin");
  17. const AliasPlugin = require("./AliasPlugin");
  18. const AliasFieldPlugin = require("./AliasFieldPlugin");
  19. const ConcordExtensionsPlugin = require("./ConcordExtensionsPlugin");
  20. const ConcordMainPlugin = require("./ConcordMainPlugin");
  21. const ConcordModulesPlugin = require("./ConcordModulesPlugin");
  22. const DirectoryExistsPlugin = require("./DirectoryExistsPlugin");
  23. const FileExistsPlugin = require("./FileExistsPlugin");
  24. const SymlinkPlugin = require("./SymlinkPlugin");
  25. const MainFieldPlugin = require("./MainFieldPlugin");
  26. const UseFilePlugin = require("./UseFilePlugin");
  27. const AppendPlugin = require("./AppendPlugin");
  28. const RootPlugin = require("./RootPlugin");
  29. const RestrictionsPlugin = require("./RestrictionsPlugin");
  30. const ResultPlugin = require("./ResultPlugin");
  31. const ModuleAppendPlugin = require("./ModuleAppendPlugin");
  32. const UnsafeCachePlugin = require("./UnsafeCachePlugin");
  33. exports.createResolver = function(options) {
  34. //// OPTIONS ////
  35. // A list of directories to resolve modules from, can be absolute path or folder name
  36. let modules = options.modules || ["node_modules"];
  37. // A list of description files to read from
  38. const descriptionFiles = options.descriptionFiles || ["package.json"];
  39. // A list of additional resolve plugins which should be applied
  40. // The slice is there to create a copy, because otherwise pushing into plugins
  41. // changes the original options.plugins array, causing duplicate plugins
  42. const plugins = (options.plugins && options.plugins.slice()) || [];
  43. // A list of main fields in description files
  44. let mainFields = options.mainFields || ["main"];
  45. // A list of alias fields in description files
  46. const aliasFields = options.aliasFields || [];
  47. // A list of main files in directories
  48. const mainFiles = options.mainFiles || ["index"];
  49. // A list of extensions which should be tried for files
  50. let extensions = options.extensions || [".js", ".json", ".node"];
  51. // Enforce that a extension from extensions must be used
  52. const enforceExtension = options.enforceExtension || false;
  53. // A list of module extensions which should be tried for modules
  54. let moduleExtensions = options.moduleExtensions || [];
  55. // Enforce that a extension from moduleExtensions must be used
  56. const enforceModuleExtension = options.enforceModuleExtension || false;
  57. // A list of module alias configurations or an object which maps key to value
  58. let alias = options.alias || [];
  59. // Resolve symlinks to their symlinked location
  60. const symlinks =
  61. typeof options.symlinks !== "undefined" ? options.symlinks : true;
  62. // Resolve to a context instead of a file
  63. const resolveToContext = options.resolveToContext || false;
  64. // A list of root paths
  65. const roots = options.roots || [];
  66. const restrictions = options.restrictions || [];
  67. // Use this cache object to unsafely cache the successful requests
  68. let unsafeCache = options.unsafeCache || false;
  69. // Whether or not the unsafeCache should include request context as part of the cache key.
  70. const cacheWithContext =
  71. typeof options.cacheWithContext !== "undefined"
  72. ? options.cacheWithContext
  73. : true;
  74. // Enable concord description file instructions
  75. const enableConcord = options.concord || false;
  76. // A function which decides whether a request should be cached or not.
  77. // an object is passed with `path` and `request` properties.
  78. const cachePredicate =
  79. options.cachePredicate ||
  80. function() {
  81. return true;
  82. };
  83. // The file system which should be used
  84. const fileSystem = options.fileSystem;
  85. // Use only the sync constiants of the file system calls
  86. const useSyncFileSystemCalls = options.useSyncFileSystemCalls;
  87. // A prepared Resolver to which the plugins are attached
  88. let resolver = options.resolver;
  89. //// options processing ////
  90. if (!resolver) {
  91. resolver = new Resolver(
  92. useSyncFileSystemCalls
  93. ? new SyncAsyncFileSystemDecorator(fileSystem)
  94. : fileSystem
  95. );
  96. }
  97. extensions = [].concat(extensions);
  98. moduleExtensions = [].concat(moduleExtensions);
  99. modules = mergeFilteredToArray([].concat(modules), item => {
  100. return !isAbsolutePath(item);
  101. });
  102. mainFields = mainFields.map(item => {
  103. if (typeof item === "string" || Array.isArray(item)) {
  104. item = {
  105. name: item,
  106. forceRelative: true
  107. };
  108. }
  109. return item;
  110. });
  111. if (typeof alias === "object" && !Array.isArray(alias)) {
  112. alias = Object.keys(alias).map(key => {
  113. let onlyModule = false;
  114. let obj = alias[key];
  115. if (/\$$/.test(key)) {
  116. onlyModule = true;
  117. key = key.substr(0, key.length - 1);
  118. }
  119. if (typeof obj === "string") {
  120. obj = {
  121. alias: obj
  122. };
  123. }
  124. obj = Object.assign(
  125. {
  126. name: key,
  127. onlyModule: onlyModule
  128. },
  129. obj
  130. );
  131. return obj;
  132. });
  133. }
  134. if (unsafeCache && typeof unsafeCache !== "object") {
  135. unsafeCache = {};
  136. }
  137. //// pipeline ////
  138. resolver.ensureHook("resolve");
  139. resolver.ensureHook("parsedResolve");
  140. resolver.ensureHook("describedResolve");
  141. resolver.ensureHook("rawModule");
  142. resolver.ensureHook("module");
  143. resolver.ensureHook("relative");
  144. resolver.ensureHook("describedRelative");
  145. resolver.ensureHook("directory");
  146. resolver.ensureHook("existingDirectory");
  147. resolver.ensureHook("undescribedRawFile");
  148. resolver.ensureHook("rawFile");
  149. resolver.ensureHook("file");
  150. resolver.ensureHook("existingFile");
  151. resolver.ensureHook("resolved");
  152. // resolve
  153. if (unsafeCache) {
  154. plugins.push(
  155. new UnsafeCachePlugin(
  156. "resolve",
  157. cachePredicate,
  158. unsafeCache,
  159. cacheWithContext,
  160. "new-resolve"
  161. )
  162. );
  163. plugins.push(new ParsePlugin("new-resolve", "parsed-resolve"));
  164. } else {
  165. plugins.push(new ParsePlugin("resolve", "parsed-resolve"));
  166. }
  167. // parsed-resolve
  168. plugins.push(
  169. new DescriptionFilePlugin(
  170. "parsed-resolve",
  171. descriptionFiles,
  172. "described-resolve"
  173. )
  174. );
  175. plugins.push(new NextPlugin("after-parsed-resolve", "described-resolve"));
  176. // described-resolve
  177. if (alias.length > 0)
  178. plugins.push(new AliasPlugin("described-resolve", alias, "resolve"));
  179. if (enableConcord) {
  180. plugins.push(new ConcordModulesPlugin("described-resolve", {}, "resolve"));
  181. }
  182. aliasFields.forEach(item => {
  183. plugins.push(new AliasFieldPlugin("described-resolve", item, "resolve"));
  184. });
  185. plugins.push(new ModuleKindPlugin("after-described-resolve", "raw-module"));
  186. roots.forEach(root => {
  187. plugins.push(new RootPlugin("after-described-resolve", root, "relative"));
  188. });
  189. plugins.push(new JoinRequestPlugin("after-described-resolve", "relative"));
  190. // raw-module
  191. moduleExtensions.forEach(item => {
  192. plugins.push(new ModuleAppendPlugin("raw-module", item, "module"));
  193. });
  194. if (!enforceModuleExtension)
  195. plugins.push(new TryNextPlugin("raw-module", null, "module"));
  196. // module
  197. modules.forEach(item => {
  198. if (Array.isArray(item))
  199. plugins.push(
  200. new ModulesInHierachicDirectoriesPlugin("module", item, "resolve")
  201. );
  202. else plugins.push(new ModulesInRootPlugin("module", item, "resolve"));
  203. });
  204. // relative
  205. plugins.push(
  206. new DescriptionFilePlugin(
  207. "relative",
  208. descriptionFiles,
  209. "described-relative"
  210. )
  211. );
  212. plugins.push(new NextPlugin("after-relative", "described-relative"));
  213. // described-relative
  214. plugins.push(new FileKindPlugin("described-relative", "raw-file"));
  215. plugins.push(
  216. new TryNextPlugin("described-relative", "as directory", "directory")
  217. );
  218. // directory
  219. plugins.push(new DirectoryExistsPlugin("directory", "existing-directory"));
  220. if (resolveToContext) {
  221. // existing-directory
  222. plugins.push(new NextPlugin("existing-directory", "resolved"));
  223. } else {
  224. // existing-directory
  225. if (enableConcord) {
  226. plugins.push(new ConcordMainPlugin("existing-directory", {}, "resolve"));
  227. }
  228. mainFields.forEach(item => {
  229. plugins.push(new MainFieldPlugin("existing-directory", item, "resolve"));
  230. });
  231. mainFiles.forEach(item => {
  232. plugins.push(
  233. new UseFilePlugin("existing-directory", item, "undescribed-raw-file")
  234. );
  235. });
  236. // undescribed-raw-file
  237. plugins.push(
  238. new DescriptionFilePlugin(
  239. "undescribed-raw-file",
  240. descriptionFiles,
  241. "raw-file"
  242. )
  243. );
  244. plugins.push(new NextPlugin("after-undescribed-raw-file", "raw-file"));
  245. // raw-file
  246. if (!enforceExtension) {
  247. plugins.push(new TryNextPlugin("raw-file", "no extension", "file"));
  248. }
  249. if (enableConcord) {
  250. plugins.push(new ConcordExtensionsPlugin("raw-file", {}, "file"));
  251. }
  252. extensions.forEach(item => {
  253. plugins.push(new AppendPlugin("raw-file", item, "file"));
  254. });
  255. // file
  256. if (alias.length > 0)
  257. plugins.push(new AliasPlugin("file", alias, "resolve"));
  258. if (enableConcord) {
  259. plugins.push(new ConcordModulesPlugin("file", {}, "resolve"));
  260. }
  261. aliasFields.forEach(item => {
  262. plugins.push(new AliasFieldPlugin("file", item, "resolve"));
  263. });
  264. if (symlinks) plugins.push(new SymlinkPlugin("file", "relative"));
  265. plugins.push(new FileExistsPlugin("file", "existing-file"));
  266. // existing-file
  267. plugins.push(new NextPlugin("existing-file", "resolved"));
  268. }
  269. // resolved
  270. if (restrictions.length > 0) {
  271. plugins.push(new RestrictionsPlugin(resolver.hooks.resolved, restrictions));
  272. }
  273. plugins.push(new ResultPlugin(resolver.hooks.resolved));
  274. //// RESOLVER ////
  275. plugins.forEach(plugin => {
  276. plugin.apply(resolver);
  277. });
  278. return resolver;
  279. };
  280. function mergeFilteredToArray(array, filter) {
  281. return array.reduce((array, item) => {
  282. if (filter(item)) {
  283. const lastElement = array[array.length - 1];
  284. if (Array.isArray(lastElement)) {
  285. lastElement.push(item);
  286. } else {
  287. array.push([item]);
  288. }
  289. return array;
  290. } else {
  291. array.push(item);
  292. return array;
  293. }
  294. }, []);
  295. }
  296. function isAbsolutePath(path) {
  297. return /^[A-Z]:|^\//.test(path);
  298. }