]>
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 | ||
17 | function matchModule(str) { | |
531c751f | 18 | const matches = str.match(srcModuleRegex); |
19 | return matches && matches[1]; | |
20 | } | |
8e21ab0a | 21 | module.exports.match = matchModule; |
22 | ||
23 | function matchImports(str) { | |
24 | const matches = str.match(importModuleRegex); | |
25 | return (matches || []).map(a => a.replace(/\n?\s*import\s+/i, '')); | |
26 | } | |
27 | module.exports.matchImports = matchImports; | |
531c751f | 28 | |
29 | function makeMapEntry(filePurs) { | |
30 | const dirname = path.dirname(filePurs); | |
31 | ||
32 | const basename = path.basename(filePurs, '.purs'); | |
33 | ||
34 | const fileJs = path.join(dirname, `${basename}.js`); | |
35 | ||
36 | const result = Promise.props({ | |
37 | filePurs: fs.readFileAsync(filePurs, 'utf8'), | |
38 | fileJs: fs.readFileAsync(fileJs, 'utf8').catch(() => undefined) | |
39 | }).then(fileMap => { | |
40 | const sourcePurs = fileMap.filePurs; | |
41 | ||
42 | const sourceJs = fileMap.fileJs; | |
43 | ||
8e21ab0a | 44 | const moduleName = matchModule(sourcePurs); |
45 | ||
46 | const imports = matchImports(sourcePurs); | |
531c751f | 47 | |
48 | const map = {}; | |
49 | ||
50 | map[moduleName] = map[moduleName] || {}; | |
51 | ||
52 | map[moduleName].src = path.resolve(filePurs); | |
53 | ||
8e21ab0a | 54 | map[moduleName].imports = imports; |
55 | ||
531c751f | 56 | if (sourceJs) { |
57 | map[moduleName].ffi = path.resolve(fileJs); | |
58 | } | |
59 | ||
60 | return map; | |
61 | }); | |
62 | ||
63 | return result; | |
64 | } | |
65 | module.exports.makeMapEntry = makeMapEntry; | |
66 | ||
67 | function makeMap(src) { | |
68 | debug('loading PureScript source and FFI files from %o', src); | |
69 | ||
70 | const globs = [].concat(src); | |
71 | ||
72 | return globby(globs).then(paths => | |
73 | Promise.all(paths.map(makeMapEntry)).then(result => | |
74 | result.reduce(Object.assign, {}) | |
75 | ) | |
76 | ); | |
77 | } | |
78 | module.exports.makeMap = makeMap; |