]> git.immae.eu Git - github/fretlink/purs-loader.git/blob - src/index.js
Add options for ide commands
[github/fretlink/purs-loader.git] / src / index.js
1 'use strict'
2
3 const debug_ = require('debug');
4
5 const debug = debug_('purs-loader');
6
7 const debugVerbose = debug_('purs-loader:verbose');
8
9 const loaderUtils = require('loader-utils')
10
11 const Promise = require('bluebird')
12
13 const path = require('path')
14
15 const PsModuleMap = require('./purs-module-map');
16
17 const compile = require('./compile');
18
19 const bundle = require('./bundle');
20
21 const ide = require('./ide');
22
23 const toJavaScript = require('./to-javascript');
24
25 const dargs = require('./dargs');
26
27 const spawn = require('cross-spawn').sync
28
29 const eol = require('os').EOL
30
31 module.exports = function purescriptLoader(source, map) {
32 this.cacheable && this.cacheable();
33
34 const webpackConfig = this.options;
35
36 var cache = webpackConfig.purescriptLoaderCache = webpackConfig.purescriptLoaderCache || {
37 rebuild: false,
38 deferred: [],
39 bundleModules: [],
40 ideServer: null,
41 psModuleMap: null,
42 warnings: [],
43 errors: [],
44 compilationStarted: false,
45 compilationFinished: false,
46 installed: false,
47 srcOption: []
48 };
49
50 const callback = this.async();
51
52 const loaderOptions = loaderUtils.getOptions(this) || {};
53
54 const srcOption = (pscPackage => {
55 const srcPath = path.join('src', '**', '*.purs');
56
57 const bowerPath = path.join('bower_components', 'purescript-*', 'src', '**', '*.purs');
58
59 if (cache.srcOption.length > 0) {
60 return cache.srcOption;
61 }
62 else if (pscPackage) {
63 const pscPackageCommand = 'psc-package';
64
65 const pscPackageArgs = ['sources'];
66
67 const loaderSrc = loaderOptions.src || [
68 srcPath
69 ];
70
71 debug('psc-package %s %o', pscPackageCommand, pscPackageArgs);
72
73 const cmd = spawn(pscPackageCommand, pscPackageArgs);
74
75 if (cmd.error) {
76 throw new Error(cmd.error);
77 }
78 else if (cmd.status !== 0) {
79 const error = cmd.stdout.toString();
80
81 throw new Error(error);
82 }
83 else {
84 const result = cmd.stdout.toString().split(eol).filter(v => v != '').concat(loaderSrc);
85
86 debug('psc-package result: %o', result);
87
88 cache.srcOption = result;
89
90 return result;
91 }
92 }
93 else {
94 const result = loaderOptions.src || [
95 bowerPath,
96 srcPath
97 ];
98
99 cache.srcOption = result;
100
101 return result;
102 }
103 })(loaderOptions.pscPackage);
104
105 const options = Object.assign({
106 context: webpackConfig.context,
107 psc: null,
108 pscArgs: {},
109 pscBundle: null,
110 pscBundleArgs: {},
111 pscIdeClient: null,
112 pscIdeClientArgs: {},
113 pscIdeServer: null,
114 pscIdeServerArgs: {},
115 pscIde: false,
116 pscIdeColors: loaderOptions.psc === 'psa',
117 pscPackage: false,
118 bundleOutput: 'output/bundle.js',
119 bundleNamespace: 'PS',
120 bundle: false,
121 warnings: true,
122 watch: false,
123 output: 'output',
124 src: []
125 }, loaderOptions, {
126 src: srcOption
127 });
128
129 if (!cache.installed) {
130 debugVerbose('installing purs-loader with options: %O', options);
131
132 cache.installed = true;
133
134 // invalidate loader cache when bundle is marked as invalid (in watch mode)
135 this._compiler.plugin('invalid', () => {
136 debugVerbose('invalidating loader cache');
137
138 cache = webpackConfig.purescriptLoaderCache = {
139 rebuild: options.pscIde,
140 deferred: [],
141 bundleModules: [],
142 ideServer: cache.ideServer,
143 psModuleMap: cache.psModuleMap,
144 warnings: [],
145 errors: [],
146 compilationStarted: false,
147 compilationFinished: false,
148 installed: cache.installed,
149 srcOption: []
150 };
151 });
152
153 // add psc warnings to webpack compilation warnings
154 this._compiler.plugin('after-compile', (compilation, callback) => {
155 cache.warnings.forEach(warning => {
156 compilation.warnings.push(warning);
157 });
158
159 cache.errors.forEach(error => {
160 compilation.errors.push(error);
161 });
162
163 callback()
164 });
165 }
166
167 const psModuleName = PsModuleMap.matchModule(source);
168
169 const psModule = {
170 name: psModuleName,
171 load: js => callback(null, js),
172 reject: error => callback(error),
173 srcPath: this.resourcePath,
174 srcDir: path.dirname(this.resourcePath),
175 jsPath: path.resolve(path.join(options.output, psModuleName, 'index.js')),
176 options: options,
177 cache: cache,
178 emitWarning: warning => {
179 if (options.warnings && warning.length) {
180 cache.warnings.push(warning);
181 }
182 },
183 emitError: error => {
184 if (error.length) {
185 cache.errors.push(error);
186 }
187 }
188 }
189
190 debug('loading %s', psModule.name);
191
192 if (options.bundle) {
193 cache.bundleModules.push(psModule.name);
194 }
195
196 if (cache.rebuild) {
197 const connect = () => {
198 if (!cache.ideServer) {
199 cache.ideServer = true;
200
201 return ide.connect(psModule)
202 .then(ideServer => {
203 cache.ideServer = ideServer;
204 return psModule;
205 })
206 .then(ide.loadWithRetry)
207 .catch(error => {
208 if (cache.ideServer.kill) {
209 debug('ide failed to initially load modules, stopping the ide server process');
210
211 cache.ideServer.kill();
212 }
213
214 cache.ideServer = null;
215
216 return Promise.reject(error);
217 })
218 ;
219 }
220 else {
221 return Promise.resolve(psModule);
222 }
223 };
224
225 const rebuild = () =>
226 ide.rebuild(psModule)
227 .then(() =>
228 toJavaScript(psModule)
229 .then(psModule.load)
230 .catch(psModule.reject)
231 )
232 .catch(error => {
233 if (error instanceof ide.UnknownModuleError) {
234 // Store the modules that trigger a recompile due to an
235 // unknown module error. We need to wait until compilation is
236 // done before loading these files.
237
238 cache.deferred.push(psModule);
239
240 if (!cache.compilationStarted) {
241 cache.compilationStarted = true;
242
243 return compile(psModule)
244 .then(() => {
245 cache.compilationFinished = true;
246 })
247 .then(() =>
248 PsModuleMap.makeMap(options.src).then(map => {
249 debug('rebuilt module map after unknown module forced a recompilation');
250
251 cache.psModuleMap = map;
252 })
253 )
254 .then(() =>
255 Promise.map(cache.deferred, psModule =>
256 ide.load(psModule)
257 .then(() => toJavaScript(psModule))
258 .then(psModule.load)
259 )
260 )
261 .catch(error => {
262 cache.deferred[0].reject(error);
263
264 cache.deferred.slice(1).forEach(psModule => {
265 psModule.reject(new Error('purs-loader failed'));
266 })
267 })
268 ;
269 }
270 else {
271 // The compilation has started. We must wait until it is
272 // done in order to ensure the module map contains all of
273 // the unknown modules.
274 }
275 }
276 else {
277 debug('ide rebuild failed due to an unhandled error: %o', error);
278
279 psModule.reject(error);
280 }
281 })
282 ;
283
284 connect().then(rebuild);
285 }
286 else if (cache.compilationFinished) {
287 debugVerbose('compilation is already finished, loading module %s', psModule.name);
288
289 toJavaScript(psModule)
290 .then(psModule.load)
291 .catch(psModule.reject);
292 }
293 else {
294 // The compilation has not finished yet. We need to wait for
295 // compilation to finish before the loaders run so that references
296 // to compiled output are valid. Push the modules into the cache to
297 // be loaded once the complation is complete.
298
299 cache.deferred.push(psModule);
300
301 if (!cache.compilationStarted) {
302 cache.compilationStarted = true;
303
304 compile(psModule)
305 .then(() => {
306 cache.compilationFinished = true;
307 })
308 .then(() => {
309 if (options.bundle) {
310 return bundle(options, cache.bundleModules);
311 }
312 })
313 .then(() =>
314 PsModuleMap.makeMap(options.src).then(map => {
315 debug('rebuilt module map after compilation');
316
317 cache.psModuleMap = map;
318 })
319 )
320 .then(() =>
321 Promise.map(cache.deferred, psModule =>
322 toJavaScript(psModule)
323 .then(psModule.load)
324 )
325 )
326 .catch(error => {
327 cache.deferred[0].reject(error);
328
329 cache.deferred.slice(1).forEach(psModule => {
330 psModule.reject(new Error('purs-loader failed'));
331 })
332 })
333 ;
334 }
335 else {
336 // The complation has started. Nothing to do but wait until it is
337 // done before loading all of the modules.
338 }
339 }
340 }