]> git.immae.eu Git - github/fretlink/purs-loader.git/blame - src/index.js
Use cross-spawn for windows support
[github/fretlink/purs-loader.git] / src / index.js
CommitLineData
7de41f10
AM
1'use strict'
2
3const colors = require('chalk')
4const debug = require('debug')('purs-loader')
5const loaderUtils = require('loader-utils')
6const globby = require('globby')
7const Promise = require('bluebird')
8const fs = Promise.promisifyAll(require('fs'))
cfa924ef 9const spawn = require('cross-spawn')
7de41f10
AM
10const path = require('path')
11const retryPromise = require('promise-retry')
12
17acb575
AM
13const ffiModuleRegex = /\/\/\s+module\s+([\w\.]+)/i
14const srcModuleRegex = /(?:^|\n)module\s+([\w\.]+)/i
7de41f10
AM
15const requireRegex = /require\(['"]\.\.\/([\w\.]+)['"]\)/g
16
17module.exports = function purescriptLoader(source, map) {
18 const callback = this.async()
19 const config = this.options
20 const query = loaderUtils.parseQuery(this.query)
21 const webpackOptions = this.options.purescriptLoader || {}
22
23 const options = Object.assign({
24 context: config.context,
25 psc: 'psc',
26 pscArgs: {},
27 pscBundle: 'psc-bundle',
28 pscBundleArgs: {},
5163b5a2 29 pscIde: false,
7de41f10
AM
30 pscIdeColors: webpackOptions.psc === 'psa' || query.psc === 'psa',
31 pscIdeArgs: {},
32 bundleOutput: 'output/bundle.js',
33 bundleNamespace: 'PS',
34 bundle: false,
35 warnings: true,
36 output: 'output',
37 src: [
38 path.join('src', '**', '*.purs'),
39 path.join('bower_components', 'purescript-*', 'src', '**', '*.purs')
40 ],
41 ffi: [
42 path.join('src', '**', '*.js'),
43 path.join('bower_components', 'purescript-*', 'src', '**', '*.js')
44 ],
45 }, webpackOptions, query)
46
47 this.cacheable && this.cacheable()
48
49 let cache = config.purescriptLoaderCache = config.purescriptLoaderCache || {
50 rebuild: false,
51 deferred: [],
52 bundleModules: [],
53 }
54
55 if (!config.purescriptLoaderInstalled) {
56 config.purescriptLoaderInstalled = true
57
58 // invalidate loader cache when bundle is marked as invalid (in watch mode)
59 this._compiler.plugin('invalid', () => {
60 cache = config.purescriptLoaderCache = {
5163b5a2 61 rebuild: options.pscIde,
7de41f10
AM
62 deferred: [],
63 ideServer: cache.ideServer
64 }
65 })
66
67 // add psc warnings to webpack compilation warnings
68 this._compiler.plugin('after-compile', (compilation, callback) => {
9dc10210
AM
69 if (options.warnings && cache.warnings) {
70 compilation.warnings.unshift(`PureScript compilation:\n${cache.warnings}`)
7de41f10
AM
71 }
72
9dc10210
AM
73 if (cache.errors) {
74 compilation.errors.unshift(`PureScript compilation:\n${cache.errors}`)
7de41f10
AM
75 }
76
77 callback()
78 })
79 }
80
17acb575 81 const psModuleName = match(srcModuleRegex, source)
7de41f10
AM
82 const psModule = {
83 name: psModuleName,
84 load: js => callback(null, js),
85 reject: error => callback(error),
86 srcPath: this.resourcePath,
87 srcDir: path.dirname(this.resourcePath),
88 jsPath: path.resolve(path.join(options.output, psModuleName, 'index.js')),
89 options: options,
90 cache: cache,
91 }
92
67888496
AM
93 debug('loader called', psModule.name)
94
7de41f10
AM
95 if (options.bundle) {
96 cache.bundleModules.push(psModule.name)
97 }
98
99 if (cache.rebuild) {
100 return connectIdeServer(psModule)
101 .then(rebuild)
102 .then(toJavaScript)
103 .then(psModule.load)
104 .catch(psModule.reject)
105 }
106
67888496 107 if (cache.compilationFinished) {
7de41f10
AM
108 return toJavaScript(psModule).then(psModule.load).catch(psModule.reject)
109 }
110
111 // We need to wait for compilation to finish before the loaders run so that
112 // references to compiled output are valid.
113 cache.deferred.push(psModule)
114
67888496 115 if (!cache.compilationStarted) {
7de41f10
AM
116 return compile(psModule)
117 .then(() => Promise.map(cache.deferred, psModule => {
118 if (typeof cache.ideServer === 'object') cache.ideServer.kill()
119 return toJavaScript(psModule).then(psModule.load)
120 }))
121 .catch(error => {
122 cache.deferred[0].reject(error)
123 cache.deferred.slice(1).forEach(psModule => psModule.reject(true))
124 })
125 }
126}
127
128// The actual loader is executed *after* purescript compilation.
129function toJavaScript(psModule) {
130 const options = psModule.options
131 const cache = psModule.cache
132 const bundlePath = path.resolve(options.bundleOutput)
133 const jsPath = cache.bundle ? bundlePath : psModule.jsPath
134
67888496 135 debug('loading JavaScript for', psModule.name)
7de41f10
AM
136
137 return Promise.props({
138 js: fs.readFileAsync(jsPath, 'utf8'),
17acb575 139 psModuleMap: psModuleMap(options, cache)
7de41f10
AM
140 }).then(result => {
141 let js = ''
142
143 if (options.bundle) {
144 // if bundling, return a reference to the bundle
145 js = 'module.exports = require("'
146 + path.relative(psModule.srcDir, options.bundleOutput)
147 + '")["' + psModule.name + '"]'
148 } else {
149 // replace require paths to output files generated by psc with paths
150 // to purescript sources, which are then also run through this loader.
7de41f10
AM
151 js = result.js
152 .replace(requireRegex, (m, p1) => {
17acb575
AM
153 return 'require("' + result.psModuleMap[p1].src + '")'
154 })
155 .replace(/require\(['"]\.\/foreign['"]\)/g, (m, p1) => {
156 return 'require("' + result.psModuleMap[psModule.name].ffi + '")'
7de41f10 157 })
7de41f10
AM
158 }
159
160 return js
161 })
162}
163
164function compile(psModule) {
165 const options = psModule.options
166 const cache = psModule.cache
167 const stderr = []
168
67888496 169 if (cache.compilationStarted) return Promise.resolve(psModule)
7de41f10 170
67888496 171 cache.compilationStarted = true
7de41f10
AM
172
173 const args = dargs(Object.assign({
174 _: options.src,
175 ffi: options.ffi,
176 output: options.output,
177 }, options.pscArgs))
178
179 debug('spawning compiler %s %o', options.psc, args)
180
181 return (new Promise((resolve, reject) => {
182 console.log('\nCompiling PureScript...')
183
184 const compilation = spawn(options.psc, args)
185
9dc10210 186 compilation.stdout.on('data', data => stderr.push(data.toString()))
7de41f10
AM
187 compilation.stderr.on('data', data => stderr.push(data.toString()))
188
189 compilation.on('close', code => {
190 console.log('Finished compiling PureScript.')
67888496 191 cache.compilationFinished = true
7de41f10 192 if (code !== 0) {
9dc10210 193 cache.errors = stderr.join('')
7de41f10
AM
194 reject(true)
195 } else {
9dc10210 196 cache.warnings = stderr.join('')
7de41f10
AM
197 resolve(psModule)
198 }
199 })
200 }))
201 .then(compilerOutput => {
202 if (options.bundle) {
203 return bundle(options, cache).then(() => psModule)
204 }
205 return psModule
206 })
207}
208
209function rebuild(psModule) {
210 const options = psModule.options
211 const cache = psModule.cache
212
213 debug('attempting rebuild with psc-ide-client %s', psModule.srcPath)
214
215 const request = (body) => new Promise((resolve, reject) => {
216 const args = dargs(options.pscIdeArgs)
217 const ideClient = spawn('psc-ide-client', args)
218
58f78e37 219 var stdout = ''
220 var stderr = ''
221
222 ideClient.stdout.on('data', data => {
223 stdout = stdout + data.toString()
224 })
225
226 ideClient.stderr.on('data', data => {
227 stderr = stderr + data.toString()
228 })
229
230 ideClient.on('close', code => {
231 if (code !== 0) {
232 const error = stderr === '' ? 'Failed to spawn psc-ide-client' : stderr
233 return reject(new Error(error))
234 }
235
5163b5a2 236 let res = null
7de41f10 237
5163b5a2 238 try {
58f78e37 239 res = JSON.parse(stdout.toString())
5163b5a2
AM
240 debug(res)
241 } catch (err) {
242 return reject(err)
243 }
244
245 if (res && !Array.isArray(res.result)) {
7de41f10
AM
246 return res.resultType === 'success'
247 ? resolve(psModule)
5163b5a2 248 : reject('psc-ide rebuild failed')
7de41f10
AM
249 }
250
251 Promise.map(res.result, (item, i) => {
252 debug(item)
253 return formatIdeResult(item, options, i, res.result.length)
254 })
255 .then(compileMessages => {
256 if (res.resultType === 'error') {
5163b5a2
AM
257 if (res.result.some(item => item.errorCode === 'UnknownModule')) {
258 console.log('Unknown module, attempting full recompile')
259 return compile(psModule)
260 .then(() => request({ command: 'load' }))
261 .then(resolve)
262 .catch(() => reject('psc-ide rebuild failed'))
263 }
9dc10210 264 cache.errors = compileMessages.join('\n')
5163b5a2 265 reject('psc-ide rebuild failed')
7de41f10 266 } else {
9dc10210 267 cache.warnings = compileMessages.join('\n')
7de41f10
AM
268 resolve(psModule)
269 }
270 })
271 })
272
7de41f10
AM
273 ideClient.stdin.write(JSON.stringify(body))
274 ideClient.stdin.write('\n')
275 })
276
277 return request({
278 command: 'rebuild',
279 params: {
280 file: psModule.srcPath,
281 }
7de41f10
AM
282 })
283}
284
285function formatIdeResult(result, options, index, length) {
286 const srcPath = path.relative(options.context, result.filename)
287 const pos = result.position
288 const fileAndPos = `${srcPath}:${pos.startLine}:${pos.startColumn}`
289 let numAndErr = `[${index+1}/${length} ${result.errorCode}]`
290 numAndErr = options.pscIdeColors ? colors.yellow(numAndErr) : numAndErr
291
292 return fs.readFileAsync(result.filename, 'utf8').then(source => {
293 const lines = source.split('\n').slice(pos.startLine - 1, pos.endLine)
294 const endsOnNewline = pos.endColumn === 1 && pos.startLine !== pos.endLine
295 const up = options.pscIdeColors ? colors.red('^') : '^'
296 const down = options.pscIdeColors ? colors.red('v') : 'v'
297 let trimmed = lines.slice(0)
298
299 if (endsOnNewline) {
300 lines.splice(lines.length - 1, 1)
301 pos.endLine = pos.endLine - 1
302 pos.endColumn = lines[lines.length - 1].length || 1
303 }
304
305 // strip newlines at the end
306 if (endsOnNewline) {
307 trimmed = lines.reverse().reduce((trimmed, line, i) => {
308 if (i === 0 && line === '') trimmed.trimming = true
309 if (!trimmed.trimming) trimmed.push(line)
310 if (trimmed.trimming && line !== '') {
311 trimmed.trimming = false
312 trimmed.push(line)
313 }
314 return trimmed
315 }, []).reverse()
316 pos.endLine = pos.endLine - (lines.length - trimmed.length)
317 pos.endColumn = trimmed[trimmed.length - 1].length || 1
318 }
319
320 const spaces = ' '.repeat(String(pos.endLine).length)
321 let snippet = trimmed.map((line, i) => {
322 return ` ${pos.startLine + i} ${line}`
323 }).join('\n')
324
325 if (trimmed.length === 1) {
326 snippet += `\n ${spaces} ${' '.repeat(pos.startColumn - 1)}${up.repeat(pos.endColumn - pos.startColumn + 1)}`
327 } else {
328 snippet = ` ${spaces} ${' '.repeat(pos.startColumn - 1)}${down}\n${snippet}`
329 snippet += `\n ${spaces} ${' '.repeat(pos.endColumn - 1)}${up}`
330 }
331
332 return Promise.resolve(
333 `\n${numAndErr} ${fileAndPos}\n\n${snippet}\n\n${result.message}`
334 )
335 })
336}
337
338function bundle(options, cache) {
339 if (cache.bundle) return Promise.resolve(cache.bundle)
340
341 const stdout = []
342 const stderr = cache.bundle = []
343
344 const args = dargs(Object.assign({
345 _: [path.join(options.output, '*', '*.js')],
346 output: options.bundleOutput,
347 namespace: options.bundleNamespace,
348 }, options.pscBundleArgs))
349
350 cache.bundleModules.forEach(name => args.push('--module', name))
351
352 debug('spawning bundler %s %o', options.pscBundle, args.join(' '))
353
354 return (new Promise((resolve, reject) => {
355 console.log('Bundling PureScript...')
356
357 const compilation = spawn(options.pscBundle, args)
358
359 compilation.stdout.on('data', data => stdout.push(data.toString()))
360 compilation.stderr.on('data', data => stderr.push(data.toString()))
361 compilation.on('close', code => {
362 if (code !== 0) {
9dc10210 363 cache.errors = (cache.errors || '') + stderr.join('')
7de41f10
AM
364 return reject(true)
365 }
366 cache.bundle = stderr
367 resolve(fs.appendFileAsync('output/bundle.js', `module.exports = ${options.bundleNamespace}`))
368 })
369 }))
370}
371
372// map of PS module names to their source path
17acb575 373function psModuleMap(options, cache) {
7de41f10
AM
374 if (cache.psModuleMap) return Promise.resolve(cache.psModuleMap)
375
17acb575
AM
376 const globs = [].concat(options.src).concat(options.ffi)
377
7de41f10
AM
378 return globby(globs).then(paths => {
379 return Promise
380 .props(paths.reduce((map, file) => {
381 map[file] = fs.readFileAsync(file, 'utf8')
382 return map
383 }, {}))
17acb575
AM
384 .then(fileMap => {
385 cache.psModuleMap = Object.keys(fileMap).reduce((map, file) => {
386 const source = fileMap[file]
387 const ext = path.extname(file)
388 const isPurs = ext.match(/purs$/i)
389 const moduleRegex = isPurs ? srcModuleRegex : ffiModuleRegex
390 const moduleName = match(moduleRegex, source)
391 map[moduleName] = map[moduleName] || {}
392 if (isPurs) {
393 map[moduleName].src = path.resolve(file)
394 } else {
395 map[moduleName].ffi = path.resolve(file)
396 }
7de41f10
AM
397 return map
398 }, {})
399 return cache.psModuleMap
400 })
401 })
402}
403
404function connectIdeServer(psModule) {
405 const options = psModule.options
406 const cache = psModule.cache
407
408 if (cache.ideServer) return Promise.resolve(psModule)
409
410 cache.ideServer = true
411
412 const connect = () => new Promise((resolve, reject) => {
413 const args = dargs(options.pscIdeArgs)
414
415 debug('attempting to connect to psc-ide-server', args)
416
417 const ideClient = spawn('psc-ide-client', args)
418
419 ideClient.stderr.on('data', data => {
420 debug(data.toString())
421 cache.ideServer = false
422 reject(true)
423 })
424 ideClient.stdout.once('data', data => {
425 debug(data.toString())
426 if (data.toString()[0] === '{') {
427 const res = JSON.parse(data.toString())
428 if (res.resultType === 'success') {
429 cache.ideServer = ideServer
430 resolve(psModule)
431 } else {
432 cache.ideServer = ideServer
433 reject(true)
434 }
435 } else {
436 cache.ideServer = false
437 reject(true)
438 }
439 })
440 ideClient.stdin.resume()
441 ideClient.stdin.write(JSON.stringify({ command: 'load' }))
442 ideClient.stdin.write('\n')
443 })
444
445 const args = dargs(Object.assign({
446 outputDirectory: options.output,
447 }, options.pscIdeArgs))
448
449 debug('attempting to start psc-ide-server', args)
450
451 const ideServer = cache.ideServer = spawn('psc-ide-server', [])
452 ideServer.stderr.on('data', data => {
453 debug(data.toString())
454 })
455
456 return retryPromise((retry, number) => {
457 return connect().catch(error => {
458 if (!cache.ideServer && number === 9) {
459 debug(error)
460
461 console.log(
462 'failed to connect to or start psc-ide-server, ' +
463 'full compilation will occur on rebuild'
464 )
465
466 return Promise.resolve(psModule)
467 }
468
469 return retry(error)
470 })
471 }, {
472 retries: 9,
473 factor: 1,
474 minTimeout: 333,
475 maxTimeout: 333,
476 })
477}
478
479function match(regex, str) {
480 const matches = str.match(regex)
481 return matches && matches[1]
482}
483
484function dargs(obj) {
485 return Object.keys(obj).reduce((args, key) => {
486 const arg = '--' + key.replace(/[A-Z]/g, '-$&').toLowerCase();
487 const val = obj[key]
488
489 if (key === '_') val.forEach(v => args.push(v))
490 else if (Array.isArray(val)) val.forEach(v => args.push(arg, v))
491 else args.push(arg, obj[key])
492
2d052df7 493 return args.filter(arg => (typeof arg !== 'boolean'))
7de41f10
AM
494 }, [])
495}