1 | var createWatchify = require('watchify')
|
2 | var EventEmitter = require('events').EventEmitter
|
3 | var debounce = require('debounce')
|
4 | var concat = require('concat-stream')
|
5 | var assign = require('object-assign')
|
6 | var parseError = require('./parse-error')
|
7 |
|
8 | module.exports = bundler
|
9 | function bundler (browserify, opt) {
|
10 | opt = opt || {}
|
11 | var emitter = new EventEmitter()
|
12 | var delay = opt.delay || 0
|
13 | var closed = false
|
14 | var pending = true
|
15 | var time = Date.now()
|
16 | var updates = []
|
17 | var errorHandler = opt.errorHandler
|
18 | if (errorHandler === true) {
|
19 | errorHandler = defaultErrorHandler
|
20 | }
|
21 |
|
22 | var watchify = createWatchify(browserify, assign({}, opt, {
|
23 |
|
24 |
|
25 | delay: 0
|
26 | }))
|
27 | var contents = null
|
28 |
|
29 | emitter.close = function () {
|
30 | if (closed) {
|
31 | return
|
32 | }
|
33 | closed = true
|
34 | if (watchify) {
|
35 |
|
36 |
|
37 | setTimeout(function () {
|
38 | watchify.close()
|
39 | }, 50)
|
40 | }
|
41 | }
|
42 |
|
43 | var bundleDebounced = debounce(bundle, delay)
|
44 | watchify.on('update', function (rows) {
|
45 | updates = rows
|
46 | emitter.emit('pending')
|
47 | pending = true
|
48 | time = Date.now()
|
49 | bundleDebounced()
|
50 | })
|
51 |
|
52 |
|
53 | time = Date.now()
|
54 | emitter.emit('pending')
|
55 | pending = true
|
56 | bundle()
|
57 |
|
58 | function bundle () {
|
59 | if (closed) {
|
60 | update()
|
61 | return
|
62 | }
|
63 |
|
64 | var didError = false
|
65 |
|
66 | var outStream = concat(function (body) {
|
67 | if (!didError) {
|
68 | contents = body
|
69 |
|
70 | var delay = Date.now() - time
|
71 | emitter.emit('log', {
|
72 | elapsed: Math.round(delay),
|
73 | level: 'info',
|
74 | type: 'bundle'
|
75 | })
|
76 |
|
77 | bundleEnd()
|
78 | }
|
79 | })
|
80 |
|
81 | var wb = watchify.bundle()
|
82 |
|
83 | if (typeof errorHandler === 'function') {
|
84 | wb.once('error', function (err) {
|
85 | err.message = parseError(err)
|
86 | contents = errorHandler(err) || ''
|
87 |
|
88 | didError = true
|
89 | bundleEnd()
|
90 | })
|
91 | }
|
92 | wb.pipe(outStream)
|
93 |
|
94 | function bundleEnd () {
|
95 | update()
|
96 | }
|
97 | }
|
98 | return emitter
|
99 |
|
100 | function update () {
|
101 | if (pending) {
|
102 | pending = false
|
103 | emitter.emit('update', contents, updates)
|
104 | updates = []
|
105 | }
|
106 | }
|
107 | }
|
108 |
|
109 | function defaultErrorHandler (err) {
|
110 | console.error('%s', err)
|
111 | return ';console.error(' + JSON.stringify(err.message) + ');'
|
112 | }
|