]> git.immae.eu Git - github/fretlink/purs-loader.git/blame - src/purs-module-map.js
Merge remote-tracking branch 'fretlink/master' into latest
[github/fretlink/purs-loader.git] / src / purs-module-map.js
CommitLineData
531c751f 1'use strict';
2
3const path = require('path');
4
5const Promise = require('bluebird');
6
7const fs = Promise.promisifyAll(require('fs'));
8
9const globby = require('globby');
10
8e21ab0a 11const debug = require('debug')('purs-loader');
531c751f 12
8e21ab0a 13const srcModuleRegex = /(?:^|\n)module\s+([\w\.]+)/i;
531c751f 14
8e21ab0a 15const importModuleRegex = /(?:^|\n)\s*import\s+([\w\.]+)/ig;
16
1c12889c 17module.exports.matchModule = function matchModule(str) {
531c751f 18 const matches = str.match(srcModuleRegex);
19 return matches && matches[1];
1c12889c 20};
8e21ab0a 21
1c12889c 22module.exports.matchImports = function matchImports(str) {
8e21ab0a 23 const matches = str.match(importModuleRegex);
24 return (matches || []).map(a => a.replace(/\n?\s*import\s+/i, ''));
1c12889c 25};
531c751f 26
1c12889c 27module.exports.makeMapEntry = function makeMapEntry(filePurs) {
531c751f 28 const dirname = path.dirname(filePurs);
29
30 const basename = path.basename(filePurs, '.purs');
31
32 const fileJs = path.join(dirname, `${basename}.js`);
33
34 const result = Promise.props({
35 filePurs: fs.readFileAsync(filePurs, 'utf8'),
36 fileJs: fs.readFileAsync(fileJs, 'utf8').catch(() => undefined)
37 }).then(fileMap => {
38 const sourcePurs = fileMap.filePurs;
39
40 const sourceJs = fileMap.fileJs;
41
1c12889c 42 const moduleName = module.exports.matchModule(sourcePurs);
8e21ab0a 43
1c12889c 44 const imports = module.exports.matchImports(sourcePurs);
531c751f 45
46 const map = {};
47
48 map[moduleName] = map[moduleName] || {};
49
50 map[moduleName].src = path.resolve(filePurs);
51
8e21ab0a 52 map[moduleName].imports = imports;
53
531c751f 54 if (sourceJs) {
55 map[moduleName].ffi = path.resolve(fileJs);
56 }
57
58 return map;
59 });
60
61 return result;
1c12889c 62};
531c751f 63
1c12889c 64module.exports.makeMap = function makeMap(src) {
531c751f 65 debug('loading PureScript source and FFI files from %o', src);
66
67 const globs = [].concat(src);
68
69 return globby(globs).then(paths =>
1c12889c 70 Promise.all(paths.map(module.exports.makeMapEntry)).then(result =>
531c751f 71 result.reduce(Object.assign, {})
72 )
73 );
1c12889c 74};