]>
Commit | Line | Data |
---|---|---|
531c751f | 1 | 'use strict'; |
2 | ||
3 | const path = require('path'); | |
4 | ||
5 | const Promise = require('bluebird'); | |
6 | ||
7 | const fs = Promise.promisifyAll(require('fs')); | |
8 | ||
9 | const globby = require('globby'); | |
10 | ||
8e21ab0a | 11 | const debug = require('debug')('purs-loader'); |
531c751f | 12 | |
8e21ab0a | 13 | const srcModuleRegex = /(?:^|\n)module\s+([\w\.]+)/i; |
531c751f | 14 | |
8e21ab0a | 15 | const importModuleRegex = /(?:^|\n)\s*import\s+([\w\.]+)/ig; |
16 | ||
1c12889c | 17 | module.exports.matchModule = function matchModule(str) { |
531c751f | 18 | const matches = str.match(srcModuleRegex); |
19 | return matches && matches[1]; | |
1c12889c | 20 | }; |
8e21ab0a | 21 | |
1c12889c | 22 | module.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 | 27 | module.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 | 64 | module.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 | }; |