2017-11-17 21:26:23 +08:00
|
|
|
/*
|
2018-07-30 23:08:51 +08:00
|
|
|
MIT License http://www.opensource.org/licenses/mit-license.php
|
|
|
|
Author Tobias Koppers @sokra
|
|
|
|
*/
|
|
|
|
|
2017-11-17 21:26:23 +08:00
|
|
|
"use strict";
|
|
|
|
|
|
|
|
const Factory = require("enhanced-resolve").ResolverFactory;
|
2018-07-30 23:08:51 +08:00
|
|
|
const { HookMap, SyncHook, SyncWaterfallHook } = require("tapable");
|
2017-11-17 21:26:23 +08:00
|
|
|
|
2018-06-26 14:27:44 +08:00
|
|
|
module.exports = class ResolverFactory {
|
2017-11-17 21:26:23 +08:00
|
|
|
constructor() {
|
2018-07-30 20:25:40 +08:00
|
|
|
this.hooks = Object.freeze({
|
2018-02-25 09:00:20 +08:00
|
|
|
resolveOptions: new HookMap(
|
|
|
|
() => new SyncWaterfallHook(["resolveOptions"])
|
|
|
|
),
|
|
|
|
resolver: new HookMap(() => new SyncHook(["resolver", "resolveOptions"]))
|
2018-07-30 20:25:40 +08:00
|
|
|
});
|
2017-11-17 21:26:23 +08:00
|
|
|
this.cache1 = new WeakMap();
|
|
|
|
this.cache2 = new Map();
|
|
|
|
}
|
|
|
|
|
|
|
|
get(type, resolveOptions) {
|
|
|
|
const cachedResolver = this.cache1.get(resolveOptions);
|
2018-02-25 09:00:20 +08:00
|
|
|
if (cachedResolver) return cachedResolver();
|
2017-11-17 21:26:23 +08:00
|
|
|
const ident = `${type}|${JSON.stringify(resolveOptions)}`;
|
|
|
|
const resolver = this.cache2.get(ident);
|
2018-02-25 09:00:20 +08:00
|
|
|
if (resolver) return resolver;
|
2017-11-17 21:26:23 +08:00
|
|
|
const newResolver = this._create(type, resolveOptions);
|
|
|
|
this.cache2.set(ident, newResolver);
|
|
|
|
return newResolver;
|
|
|
|
}
|
|
|
|
|
|
|
|
_create(type, resolveOptions) {
|
2017-11-28 23:45:27 +08:00
|
|
|
resolveOptions = this.hooks.resolveOptions.for(type).call(resolveOptions);
|
2017-11-17 21:26:23 +08:00
|
|
|
const resolver = Factory.createResolver(resolveOptions);
|
2018-02-25 09:00:20 +08:00
|
|
|
if (!resolver) {
|
2017-11-17 21:26:23 +08:00
|
|
|
throw new Error("No resolver created");
|
|
|
|
}
|
2017-11-28 23:45:27 +08:00
|
|
|
this.hooks.resolver.for(type).call(resolver, resolveOptions);
|
2017-11-17 21:26:23 +08:00
|
|
|
return resolver;
|
|
|
|
}
|
|
|
|
};
|