/
build-response.js
99 lines (94 loc) · 2.84 KB
/
build-response.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
'use strict';
var Promise = require('promise');
var prepare = require('prepare-response');
var uglify = require('uglify-es');
var watchify = require('watchify');
var buildBundle = require('./build-bundle');
module.exports = function send(path, options) {
var bundle = buildBundle(path, options);
if (!options.cache) {
return {
send: function (req, res, next) {
getResponse(bundle, options).send(req, res, next);
},
dispose: noop
};
} else if (options.cache === 'dynamic') {
var response, resolve;
var updatingTimeout;
bundle = watchify(bundle, {poll: true, delay: 0});
bundle.on('update', function () {
if (resolve) {
clearTimeout(updatingTimeout);
} else {
response = new Promise(function (_resolve) {
resolve = _resolve;
});
}
updatingTimeout = setTimeout(function rebuild() {
resolve(getResponse(bundle, options));
resolve = undefined;
}, 600);
});
response = Promise.resolve(getResponse(bundle, options));
return {
send: function (req, res, next) {
response.done(function (response) { response.send(req, res, next); }, next);
},
dispose: function () {
bundle.close();
}
};
} else {
return getResponse(bundle, options);
}
}
function getResponse(bundle, options) {
var headers = {'content-type': 'application/javascript'};
if (options.cache && options.cache !== 'dynamic') {
headers['cache-control'] = options.cache;
}
var response = getSource(bundle, options).then(function (src) {
return prepare(src, headers, {gzip: options.gzip})
}).then(function (response) {
return syncResponse = response;
});
var syncResponse;
return {
send: function (req, res, next) {
if (syncResponse) return syncResponse.send(req, res);
else return response.done(function (response) { response.send(req, res); }, next);
},
dispose: noop
};
}
function getSource(bundle, options) {
return new Promise(function (resolve, reject) {
bundle.bundle(function (err, src) {
if (err) return reject(err);
resolve(src);
});
}).then(function (src) {
src = src.toString();
return options.postcompile ? options.postcompile(src) : src;
}).then(function (src) {
return (options.minify && options.preminify) ? options.preminify(src) : src;
}).then(function (src) {
if (options.minify) {
try {
src = minify(src, options.minify).code;
} catch (ex) { } //better to just let the client fail to parse
}
return (options.minify && options.postminify) ? options.postminify(src) : src;
});
}
function minify(str, options) {
if (!options || typeof options !== 'object') options = {};
const result = uglify.minify(str, options);
if (result.error) {
throw result.error;
}
return result;
}
function noop() {
}