]> git.immae.eu Git - github/fretlink/purs-loader.git/blame - src/index.js
Use emitError and emitWarning
[github/fretlink/purs-loader.git] / src / index.js
CommitLineData
7de41f10
AM
1'use strict'
2
7de41f10
AM
3const debug = require('debug')('purs-loader')
4const loaderUtils = require('loader-utils')
7de41f10
AM
5const Promise = require('bluebird')
6const fs = Promise.promisifyAll(require('fs'))
7de41f10 7const path = require('path')
f8d292fb 8const jsStringEscape = require('js-string-escape')
531c751f 9const PsModuleMap = require('./PsModuleMap');
10const Psc = require('./Psc');
11const PscIde = require('./PscIde');
12const dargs = require('./dargs');
7de41f10 13
7de41f10
AM
14const requireRegex = /require\(['"]\.\.\/([\w\.]+)['"]\)/g
15
16module.exports = function purescriptLoader(source, map) {
17 const callback = this.async()
18 const config = this.options
19 const query = loaderUtils.parseQuery(this.query)
20 const webpackOptions = this.options.purescriptLoader || {}
21
22 const options = Object.assign({
23 context: config.context,
24 psc: 'psc',
25 pscArgs: {},
26 pscBundle: 'psc-bundle',
27 pscBundleArgs: {},
5163b5a2 28 pscIde: false,
7de41f10
AM
29 pscIdeColors: webpackOptions.psc === 'psa' || query.psc === 'psa',
30 pscIdeArgs: {},
31 bundleOutput: 'output/bundle.js',
32 bundleNamespace: 'PS',
33 bundle: false,
34 warnings: true,
35 output: 'output',
36 src: [
37 path.join('src', '**', '*.purs'),
38 path.join('bower_components', 'purescript-*', 'src', '**', '*.purs')
2b2207bd 39 ]
7de41f10
AM
40 }, webpackOptions, query)
41
42 this.cacheable && this.cacheable()
43
44 let cache = config.purescriptLoaderCache = config.purescriptLoaderCache || {
45 rebuild: false,
46 deferred: [],
531c751f 47 bundleModules: []
7de41f10
AM
48 }
49
50 if (!config.purescriptLoaderInstalled) {
51 config.purescriptLoaderInstalled = true
52
53 // invalidate loader cache when bundle is marked as invalid (in watch mode)
54 this._compiler.plugin('invalid', () => {
531c751f 55 debug('invalidating loader cache');
56
7de41f10 57 cache = config.purescriptLoaderCache = {
5163b5a2 58 rebuild: options.pscIde,
7de41f10 59 deferred: [],
531c751f 60 bundleModules: [],
61 ideServer: cache.ideServer,
62 psModuleMap: cache.psModuleMap
7de41f10
AM
63 }
64 })
7de41f10
AM
65 }
66
531c751f 67 const psModuleName = PsModuleMap.match(source)
7de41f10
AM
68 const psModule = {
69 name: psModuleName,
70 load: js => callback(null, js),
71 reject: error => callback(error),
72 srcPath: this.resourcePath,
73 srcDir: path.dirname(this.resourcePath),
74 jsPath: path.resolve(path.join(options.output, psModuleName, 'index.js')),
75 options: options,
76 cache: cache,
45c62a2c 77 emitWarning: warning => this.emitWarning(warning),
78 emitError: error => this.emitError(error)
7de41f10
AM
79 }
80
67888496
AM
81 debug('loader called', psModule.name)
82
7de41f10
AM
83 if (options.bundle) {
84 cache.bundleModules.push(psModule.name)
85 }
86
87 if (cache.rebuild) {
531c751f 88 return PscIde.connect(psModule)
89 .then(PscIde.rebuild)
7de41f10
AM
90 .then(toJavaScript)
91 .then(psModule.load)
92 .catch(psModule.reject)
93 }
94
67888496 95 if (cache.compilationFinished) {
7de41f10
AM
96 return toJavaScript(psModule).then(psModule.load).catch(psModule.reject)
97 }
98
99 // We need to wait for compilation to finish before the loaders run so that
100 // references to compiled output are valid.
101 cache.deferred.push(psModule)
102
67888496 103 if (!cache.compilationStarted) {
531c751f 104 return Psc.compile(psModule)
105 .then(() => PsModuleMap.makeMap(options.src).then(map => {
106 debug('rebuilt module map');
107 cache.psModuleMap = map;
108 }))
7de41f10
AM
109 .then(() => Promise.map(cache.deferred, psModule => {
110 if (typeof cache.ideServer === 'object') cache.ideServer.kill()
111 return toJavaScript(psModule).then(psModule.load)
112 }))
113 .catch(error => {
114 cache.deferred[0].reject(error)
4b99e432 115 cache.deferred.slice(1).forEach(psModule => psModule.reject(new Error('purs-loader failed')))
7de41f10
AM
116 })
117 }
118}
119
531c751f 120function updatePsModuleMap(psModule) {
121 const options = psModule.options
122 const cache = psModule.cache
123 const filePurs = psModule.srcPath
124 if (!cache.psModuleMap) {
125 debug('module mapping does not exist');
126 return PsModuleMap.makeMap(options.src).then(map => {
127 cache.psModuleMap = map;
128 return cache.psModuleMap;
129 });
130 }
131 else {
132 return PsModuleMap.makeMapEntry(filePurs).then(result => {
133 const map = Object.assign(cache.psModuleMap, result)
134 cache.psModuleMap = map;
135 return cache.psModuleMap;
136 });
137 }
138}
139
7de41f10
AM
140// The actual loader is executed *after* purescript compilation.
141function toJavaScript(psModule) {
142 const options = psModule.options
143 const cache = psModule.cache
144 const bundlePath = path.resolve(options.bundleOutput)
145 const jsPath = cache.bundle ? bundlePath : psModule.jsPath
146
67888496 147 debug('loading JavaScript for', psModule.name)
7de41f10
AM
148
149 return Promise.props({
150 js: fs.readFileAsync(jsPath, 'utf8'),
531c751f 151 psModuleMap: updatePsModuleMap(psModule)
7de41f10
AM
152 }).then(result => {
153 let js = ''
154
155 if (options.bundle) {
156 // if bundling, return a reference to the bundle
157 js = 'module.exports = require("'
f8d292fb 158 + jsStringEscape(path.relative(psModule.srcDir, options.bundleOutput))
7de41f10
AM
159 + '")["' + psModule.name + '"]'
160 } else {
161 // replace require paths to output files generated by psc with paths
162 // to purescript sources, which are then also run through this loader.
7de41f10
AM
163 js = result.js
164 .replace(requireRegex, (m, p1) => {
f8d292fb 165 return 'require("' + jsStringEscape(result.psModuleMap[p1].src) + '")'
17acb575
AM
166 })
167 .replace(/require\(['"]\.\/foreign['"]\)/g, (m, p1) => {
f8d292fb 168 return 'require("' + jsStringEscape(result.psModuleMap[psModule.name].ffi) + '")'
7de41f10 169 })
7de41f10
AM
170 }
171
172 return js
173 })
174}