aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/PsModuleMap.js
blob: 2193f022de7bcbef8a10ee686874a67bd4610098 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use strict';

const path = require('path');

const Promise = require('bluebird');

const fs = Promise.promisifyAll(require('fs'));

const globby = require('globby');

const debug = require('debug')('purs-loader')

const srcModuleRegex = /(?:^|\n)module\s+([\w\.]+)/i

function match(str) {
  const matches = str.match(srcModuleRegex);
  return matches && matches[1];
}
module.exports.match = match;

function makeMapEntry(filePurs) {
  const dirname = path.dirname(filePurs);

  const basename = path.basename(filePurs, '.purs');

  const fileJs = path.join(dirname, `${basename}.js`);

  const result = Promise.props({
    filePurs: fs.readFileAsync(filePurs, 'utf8'),
    fileJs: fs.readFileAsync(fileJs, 'utf8').catch(() => undefined)
  }).then(fileMap => {
    const sourcePurs = fileMap.filePurs;

    const sourceJs = fileMap.fileJs;

    const moduleName = match(sourcePurs);

    const map = {};

    map[moduleName] = map[moduleName] || {};

    map[moduleName].src = path.resolve(filePurs);

    if (sourceJs) {
      map[moduleName].ffi = path.resolve(fileJs);
    }

    return map;
  });

  return result;
}
module.exports.makeMapEntry = makeMapEntry;

function makeMap(src) {
  debug('loading PureScript source and FFI files from %o', src);

  const globs = [].concat(src);

  return globby(globs).then(paths =>
    Promise.all(paths.map(makeMapEntry)).then(result =>
      result.reduce(Object.assign, {})
    )
  );
}
module.exports.makeMap = makeMap;