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