-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (59 loc) · 1.97 KB
/
index.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
var parse = require('url').parse;
var Build = require('component-build');
var Resolve = require('component-resolver');
module.exports = function (build, options) {
if (typeof build === 'object') {
options = build;
build = Build;
} else if (typeof build !== 'function') {
build = Build;
}
options = options || {};
// always install instead of erroring!
options.install = true;
// add require() by default
if (options.require == null) options.require = true;
var root = options.root || process.cwd();
var resolving = false;
var queue = [];
var path = options.path || '/build';
var re = new RegExp('^' + path + '.(js|css)$');
return function componentMiddleware(req, res, next) {
var m = re.exec(parse(req.url).pathname);
if (!m) return next();
resolve(function (err, tree) {
if (err) return next(err);
switch (m[1]) {
case 'js':
build(tree, options).scripts(function (err, js) {
if (err) return next(err);
res.setHeader('Cache-Control', 'private, no-cache');
res.setHeader('Content-Type', 'application/javascript');
res.setHeader('Content-Length', Buffer.byteLength(js));
res.end(js);
})
return;
case 'css':
build(tree, options).styles(function (err, css) {
if (err) return next(err);
res.setHeader('Cache-Control', 'private, no-cache');
res.setHeader('Content-Type', 'text/css; charset=utf-8');
res.setHeader('Content-Length', Buffer.byteLength(css));
res.end(css);
})
return;
}
})
}
// this is so you don't resolve two times at the same time.
// overoptimization, but hey.
function resolve(done) {
if (resolving) return queue.push(done);
resolving = true;
Resolve(root, options, function (err, tree) {
resolving = false;
while (queue.length) queue.shift()(err, tree);
done(err, tree);
});
}
}