-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
128 lines (100 loc) · 3.35 KB
/
index.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
'use strict';
const pSettle = require('p-settle');
const pDefer = require('p-defer');
const wrap = require('lodash.wrap');
const webpackSaneCompiler = require('webpack-sane-compiler');
const observeCompilers = require('./lib/observeCompilers');
function createSubFacade(saneCompiler) {
return {
webpackConfig: saneCompiler.webpackConfig,
webpackCompiler: saneCompiler.webpackCompiler,
};
}
function compiler(client, server) {
const clientCompiler = webpackSaneCompiler(client);
const serverCompiler = webpackSaneCompiler(server);
const { eventEmitter, state } = observeCompilers(clientCompiler, serverCompiler);
const compiler = Object.assign(eventEmitter, {
client: createSubFacade(clientCompiler),
server: createSubFacade(serverCompiler),
isCompiling() {
return state.isCompiling;
},
getCompilation() {
return state.compilation;
},
getError() {
return state.error;
},
run() {
clientCompiler.assertIdle('run');
serverCompiler.assertIdle('run');
return pSettle([
clientCompiler.run(),
serverCompiler.run(),
])
.then(() => {
if (state.error) {
throw state.error;
}
return state.compilation;
});
},
watch(options, handler) {
clientCompiler.assertIdle('watch');
serverCompiler.assertIdle('watch');
if (typeof options === 'function') {
handler = options;
options = null;
}
handler = handler && wrap(handler, (handler) => {
!state.isCompiling && handler(state.error, state.compilation);
});
const clientInvalidate = clientCompiler.watch(options, handler);
const serverInvalidate = serverCompiler.watch(options, handler);
return () => {
eventEmitter.emit('invalidate');
observeCompilers.resetState(state);
clientInvalidate();
serverInvalidate();
};
},
unwatch() {
return Promise.all([
clientCompiler.unwatch(),
serverCompiler.unwatch(),
])
.then(() => {});
},
resolve() {
const { error, compilation } = state;
// Already resolved?
if (error) {
return Promise.reject(error);
}
if (compilation) {
return Promise.resolve(compilation);
}
// Wait for it to be resolved
const deferred = pDefer();
const cleanup = () => {
eventEmitter.removeListener('error', onError);
eventEmitter.removeListener('end', onEnd);
};
const onError = (err) => {
cleanup();
deferred.reject(err);
};
const onEnd = (compilation) => {
cleanup();
deferred.resolve(compilation);
};
compiler
.on('error', onError)
.on('end', onEnd);
return deferred.promise;
},
});
return compiler;
}
module.exports = compiler;