UNPKG

2.69 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5
6"use strict";
7
8const ModuleNotFoundError = require("../ModuleNotFoundError");
9const LazySet = require("../util/LazySet");
10
11/** @typedef {import("../Compilation")} Compilation */
12/** @typedef {import("../ResolverFactory").ResolveOptionsWithDependencyType} ResolveOptionsWithDependencyType */
13
14/**
15 * @template T
16 * @typedef {Object} MatchedConfigs
17 * @property {Map<string, T>} resolved
18 * @property {Map<string, T>} unresolved
19 * @property {Map<string, T>} prefixed
20 */
21
22/** @type {ResolveOptionsWithDependencyType} */
23const RESOLVE_OPTIONS = { dependencyType: "esm" };
24
25/**
26 * @template T
27 * @param {Compilation} compilation the compilation
28 * @param {[string, T][]} configs to be processed configs
29 * @returns {Promise<MatchedConfigs<T>>} resolved matchers
30 */
31exports.resolveMatchedConfigs = (compilation, configs) => {
32 /** @type {Map<string, T>} */
33 const resolved = new Map();
34 /** @type {Map<string, T>} */
35 const unresolved = new Map();
36 /** @type {Map<string, T>} */
37 const prefixed = new Map();
38 const resolveContext = {
39 /** @type {LazySet<string>} */
40 fileDependencies: new LazySet(),
41 /** @type {LazySet<string>} */
42 contextDependencies: new LazySet(),
43 /** @type {LazySet<string>} */
44 missingDependencies: new LazySet()
45 };
46 const resolver = compilation.resolverFactory.get("normal", RESOLVE_OPTIONS);
47 const context = compilation.compiler.context;
48
49 return Promise.all(
50 configs.map(([request, config]) => {
51 if (/^\.\.?(\/|$)/.test(request)) {
52 // relative request
53 return new Promise(resolve => {
54 resolver.resolve(
55 {},
56 context,
57 request,
58 resolveContext,
59 (err, result) => {
60 if (err || result === false) {
61 err = err || new Error(`Can't resolve ${request}`);
62 compilation.errors.push(
63 new ModuleNotFoundError(null, err, {
64 name: `shared module ${request}`
65 })
66 );
67 return resolve();
68 }
69 resolved.set(result, config);
70 resolve();
71 }
72 );
73 });
74 } else if (/^(\/|[A-Za-z]:\\|\\\\)/.test(request)) {
75 // absolute path
76 resolved.set(request, config);
77 } else if (request.endsWith("/")) {
78 // module request prefix
79 prefixed.set(request, config);
80 } else {
81 // module request
82 unresolved.set(request, config);
83 }
84 })
85 ).then(() => {
86 compilation.contextDependencies.addAll(resolveContext.contextDependencies);
87 compilation.fileDependencies.addAll(resolveContext.fileDependencies);
88 compilation.missingDependencies.addAll(resolveContext.missingDependencies);
89 return { resolved, unresolved, prefixed };
90 });
91};