aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/bundle.js
blob: 374212487931f84c4d7ee75b3f03b945834f12bb (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
'use strict';

const path = require('path');

const Promise = require('bluebird')

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

const spawn = require('cross-spawn')

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

const dargs = require('./dargs');

module.exports = function bundle(options, bundleModules) {
  const stdout = []

  const stderr = []

  const bundleCommand = options.pscBundle || 'purs';

  const bundleArgs = (options.pscBundle ? [] : [ 'bundle' ]).concat(dargs(Object.assign({
    _: [path.join(options.output, '*', '*.js')],
    output: options.bundleOutput,
    namespace: options.bundleNamespace,
  }, options.pscBundleArgs)));

  bundleModules.forEach(name => bundleArgs.push('--module', name))

  debug('bundle: %s %O', bundleCommand, bundleArgs);

  return (new Promise((resolve, reject) => {
    debug('bundling PureScript...')

    const compilation = spawn(bundleCommand, bundleArgs)

    compilation.stdout.on('data', data => stdout.push(data.toString()))

    compilation.stderr.on('data', data => stderr.push(data.toString()))

    compilation.on('close', code => {
      debug('finished bundling PureScript.')

      if (code !== 0) {
        const errorMessage = stderr.join('');

        if (errorMessage.length) {
          reject(new Error(`bundling failed: ${errorMessage}`))
        }
        else {
          reject(new Error('bundling failed'))
        }
      }
      else {
        resolve(fs.appendFileAsync(options.bundleOutput, `module.exports = ${options.bundleNamespace}`))
      }
    })
  }))
};