|
1 | 1 | module.exports = function PluginEnvironment() { |
2 | | - var events = []; |
| 2 | + const events = []; |
| 3 | + |
| 4 | + function addEvent(name, handler) { |
| 5 | + events.push({ |
| 6 | + name, |
| 7 | + handler |
| 8 | + }); |
| 9 | + } |
| 10 | + |
| 11 | + function getEventName(hookName) { |
| 12 | + // Convert a hook name to an event name. |
| 13 | + // e.g. `buildModule` -> `build-module` |
| 14 | + return hookName.replace(/[A-Z]/g, c => "-" + c.toLowerCase()); |
| 15 | + } |
3 | 16 |
|
4 | 17 | this.getEnvironmentStub = function() { |
| 18 | + const hooks = new Map(); |
5 | 19 | return { |
6 | | - plugin: function(name, handler) { |
7 | | - events.push({ |
8 | | - name, |
9 | | - handler |
10 | | - }); |
11 | | - } |
| 20 | + plugin: addEvent, |
| 21 | + // TODO: Figure out a better way of doing this |
| 22 | + // In the meanwhile, `hooks` is a `Proxy` which creates fake hooks |
| 23 | + // on demand. Instead of creating a dummy object with a few `Hook` |
| 24 | + // method, a custom `Hook` class could be used. |
| 25 | + hooks: new Proxy({}, { |
| 26 | + get(target, hookName) { |
| 27 | + let hook = hooks.get(hookName); |
| 28 | + if (hook === undefined) { |
| 29 | + const eventName = getEventName(hookName); |
| 30 | + hook = { |
| 31 | + tap(_, handler) { |
| 32 | + addEvent(eventName, handler); |
| 33 | + }, |
| 34 | + tapAsync(_, handler) { |
| 35 | + addEvent(eventName, handler); |
| 36 | + }, |
| 37 | + tapPromise(_, handler) { |
| 38 | + addEvent(eventName, handler); |
| 39 | + } |
| 40 | + }; |
| 41 | + hooks.set(hookName, hook); |
| 42 | + } |
| 43 | + return hook; |
| 44 | + } |
| 45 | + }) |
12 | 46 | }; |
13 | 47 | }; |
14 | 48 |
|
|
0 commit comments