]> git.immae.eu Git - github/fretlink/purs-loader.git/blob - src/index.js
Use emitError and emitWarning
[github/fretlink/purs-loader.git] / src / index.js
1 'use strict'
2
3 const debug = require('debug')('purs-loader')
4 const loaderUtils = require('loader-utils')
5 const Promise = require('bluebird')
6 const fs = Promise.promisifyAll(require('fs'))
7 const path = require('path')
8 const jsStringEscape = require('js-string-escape')
9 const PsModuleMap = require('./PsModuleMap');
10 const Psc = require('./Psc');
11 const PscIde = require('./PscIde');
12 const dargs = require('./dargs');
13
14 const requireRegex = /require\(['"]\.\.\/([\w\.]+)['"]\)/g
15
16 module.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: {},
28 pscIde: false,
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')
39 ]
40 }, webpackOptions, query)
41
42 this.cacheable && this.cacheable()
43
44 let cache = config.purescriptLoaderCache = config.purescriptLoaderCache || {
45 rebuild: false,
46 deferred: [],
47 bundleModules: []
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', () => {
55 debug('invalidating loader cache');
56
57 cache = config.purescriptLoaderCache = {
58 rebuild: options.pscIde,
59 deferred: [],
60 bundleModules: [],
61 ideServer: cache.ideServer,
62 psModuleMap: cache.psModuleMap
63 }
64 })
65 }
66
67 const psModuleName = PsModuleMap.match(source)
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,
77 emitWarning: warning => this.emitWarning(warning),
78 emitError: error => this.emitError(error)
79 }
80
81 debug('loader called', psModule.name)
82
83 if (options.bundle) {
84 cache.bundleModules.push(psModule.name)
85 }
86
87 if (cache.rebuild) {
88 return PscIde.connect(psModule)
89 .then(PscIde.rebuild)
90 .then(toJavaScript)
91 .then(psModule.load)
92 .catch(psModule.reject)
93 }
94
95 if (cache.compilationFinished) {
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
103 if (!cache.compilationStarted) {
104 return Psc.compile(psModule)
105 .then(() => PsModuleMap.makeMap(options.src).then(map => {
106 debug('rebuilt module map');
107 cache.psModuleMap = map;
108 }))
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)
115 cache.deferred.slice(1).forEach(psModule => psModule.reject(new Error('purs-loader failed')))
116 })
117 }
118 }
119
120 function 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
140 // The actual loader is executed *after* purescript compilation.
141 function 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
147 debug('loading JavaScript for', psModule.name)
148
149 return Promise.props({
150 js: fs.readFileAsync(jsPath, 'utf8'),
151 psModuleMap: updatePsModuleMap(psModule)
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("'
158 + jsStringEscape(path.relative(psModule.srcDir, options.bundleOutput))
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.
163 js = result.js
164 .replace(requireRegex, (m, p1) => {
165 return 'require("' + jsStringEscape(result.psModuleMap[p1].src) + '")'
166 })
167 .replace(/require\(['"]\.\/foreign['"]\)/g, (m, p1) => {
168 return 'require("' + jsStringEscape(result.psModuleMap[psModule.name].ffi) + '")'
169 })
170 }
171
172 return js
173 })
174 }