forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdetach-plugin.js
73 lines (58 loc) · 1.6 KB
/
detach-plugin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
export default class DetachPlugin {
apply (compiler) {
compiler.pluginDetachFns = new Map()
compiler.plugin = plugin(compiler.plugin)
compiler.apply = apply
compiler.detach = detach
compiler.getDetachablePlugins = getDetachablePlugins
}
}
export function detachable (Plugin) {
const { apply } = Plugin.prototype
Plugin.prototype.apply = function (compiler) {
const fns = []
const { plugin } = compiler
compiler.plugin = function (name, fn) {
fns.push(plugin.call(this, name, fn))
}
// collect the result of `plugin` call in `apply`
apply.call(this, compiler)
compiler.plugin = plugin
return fns
}
}
function plugin (original) {
return function (name, fn) {
original.call(this, name, fn)
return () => {
const names = Array.isArray(name) ? name : [name]
for (const n of names) {
const plugins = this._plugins[n] || []
const i = plugins.indexOf(fn)
if (i >= 0) plugins.splice(i, 1)
}
}
}
}
function apply (...plugins) {
for (const p of plugins) {
const fn = p.apply(this)
if (!fn) continue
const fns = this.pluginDetachFns.get(p) || new Set()
const _fns = Array.isArray(fn) ? fn : [fn]
for (const f of _fns) fns.add(f)
this.pluginDetachFns.set(p, fns)
}
}
function detach (...plugins) {
for (const p of plugins) {
const fns = this.pluginDetachFns.get(p) || new Set()
for (const fn of fns) {
if (typeof fn === 'function') fn()
}
this.pluginDetachFns.delete(p)
}
}
function getDetachablePlugins () {
return new Set(this.pluginDetachFns.keys())
}