-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
115 lines (94 loc) · 2.61 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
'use strict';
var path = require('path');
var dirname = path.dirname;
var relative = path.relative;
var Promise = require('bluebird');
var concat = require('concat-stream');
var browserify = require('browserify');
var watchify = require('watchify');
function relativize(entry, requirement) {
var expose = relative(dirname(entry), requirement);
expose = expose.replace(/\.[a-z_\-]+$/, '');
return "./" + expose;
}
function isBrowserify(x) {
return x && (typeof x === 'object') &&
(typeof x.bundle === 'function') &&
(typeof x.plugin === 'function') &&
(typeof x.transform === 'function');
}
function isString(x) {
return Object.prototype.toString.call(x) === '[object String]';
}
function serve(options, maybeOptions) {
var b;
var rendered;
if (!maybeOptions) {
maybeOptions = {};
}
var contentType = options.contentType || 'application/javascript';
var pipes = options.pipes || function(x) { return x; };
var onError = options.onError || function() { };
if (isBrowserify(options)) {
b = options;
options = maybeOptions;
} else if (isString(options)) {
b = serve.bundle({entry: options, debug: maybeOptions.debug});
options = maybeOptions;
} else {
b = serve.bundle(options);
}
function make() {
rendered = new Promise(function(resolve, reject) {
var output = pipes(b.bundle());
output.on('error', reject);
output.pipe(concat({encoding: 'string'}, resolve));
});
rendered.catch(onError);
}
make();
var middleware = function(req, res, next) {
res.setHeader('Content-type', contentType);
return rendered.then(function(result) {
return res.end(result);
}).catch(next);
};
if (options.watch !== false) {
var w = watchify(b);
w.on('update', make);
middleware.watchify = w;
}
return middleware;
}
function bundle(options) {
var b = browserify({
entries: [options.entry],
extensions: options.extensions,
debug: options.debug
});
b.delay = options.bundleDelay || 300;
if (options.transforms) {
options.transforms.forEach(function(transform) {
if (Array.isArray(transform)) {
b.transform.apply(b, transform);
} else {
b.transform(transform);
}
});
}
if (options.requirements) {
options.requirements.forEach(function(requirement) {
var expose = relativize(options.entry, requirement);
b.require(requirement, {
expose: expose
});
});
}
if (options.bundle) {
b = options.bundle(b);
}
return b;
}
module.exports = serve;
module.exports.serve = serve;
module.exports.bundle = bundle;