-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
276 lines (253 loc) · 9.09 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
'use strict';
const rollup = require('rollup');
const fsp = require('fs-extra');
let fecha = null;
try {
// eslint-disable-next-line global-require, import/no-unresolved, node/no-missing-require
fecha = require('fecha');
} catch (e) { /* empty */ }
const url = require('url');
const path = require('path');
const { dirname, join } = require('path');
function assert(condition, message) {
if (!condition) {
throw new Error(`\x07\x1B[31m${message}\x1B[91m`);
}
}
const defaults = {
mode: 'compile',
bundleExtension: '.bundle',
src: null,
dest: null,
root: process.cwd(),
prefix: null,
rebuild: 'deps-change', // or 'never' or 'always'
serve: false, /* or 'on-compile' or true. 'on-compile' has the benefit
that the bundle which is already in memory will be
written directly into the response */
type: 'javascript',
rollupOpts: {},
bundleOpts: { format: 'iife' },
debug: false,
maxAge: 0
};
class ExpressRollup {
constructor(opts) {
this.opts = opts;
// Cache for bundles' dependencies list
this.cache = {};
this.lastTimeStamp = Date.now();
}
log(key, val) {
if (this.opts.debug) {
let time = '';
let diff = '';
if (fecha !== null) {
const now = new Date();
time = `${fecha.format(now, 'hh:mm:ss')} `;
diff = `+${fecha.format(now.getTime() - this.lastTimeStamp, 'ss.SSS')} `;
this.lastTimeStamp = now;
}
if (!val) {
console.error('\x1B[33m%s\x1B[34m%s\x1B[36m%s\x1B[0m', diff, time, key);
} else {
console.error('\x1B[33m%s\x1B[34m%s\x1B[90m%s: \x1B[36m%s\x1B[0m', diff, time, key, val);
}
}
}
handle(req, res, next) {
if (req.method !== 'GET' && req.method !== 'HEAD') {
next();
return;
}
const { opts } = this;
const { src, dest, root } = opts;
const rollupOpts = Object.assign({}, opts.rollupOpts);
const bundleOpts = Object.assign({}, opts.bundleOpts);
const extRegex = /\.js$/;
let { pathname } = url.parse(req.url);
if (opts.prefix && pathname.indexOf(opts.prefix) === 0) {
pathname = pathname.substring(opts.prefix.length);
}
if (!extRegex.test(pathname)) {
next();
return;
}
const jsPath = join(root, dest, pathname.replace(new RegExp(`^${dest}`), ''));
const bundlePath = join(root, src, pathname
.replace(new RegExp(`^${dest}`), '')
.replace(extRegex, opts.bundleExtension));
this.log('source', bundlePath);
this.log('dest', jsPath);
rollupOpts.input = bundlePath;
fsp.access(bundlePath, fsp.constants.R_OK)
.then(() => this.checkNeedsRebuild(jsPath, rollupOpts))
.then((rebuild) => {
if (rebuild.needed) {
this.log('Needs rebuild', 'true');
this.log('Rolling up', 'started');
// checkNeedsRebuild may need to inspect the bundle, so re-use the
// one already available instead of creating a new one
if (rebuild.bundle) {
this.processBundle(rebuild.bundle, bundleOpts, jsPath, res, next, opts);
} else {
rollup.rollup(rollupOpts).then((bundle) => {
this.processBundle(bundle, bundleOpts, jsPath, res, next, opts);
}, (err) => {
console.error(err);
});
}
} else if (opts.serve === true) {
// serve js code from cache by ourselves
res.status(200)
.type(opts.type)
.set('Cache-Control', `max-age=${opts.maxAge}`)
.sendFile(jsPath, (err) => {
if (err) {
console.error(err);
res.status(err.status).end();
} else {
this.log('Serving', 'ourselves');
}
});
} else {
// have someone else take care of things
next();
}
}, (err) => {
if (err.syscall && err.syscall === 'access') {
this.log('Bundle file not found. Since you might intend to serve this file statically, this is a silent warning.');
} else {
console.error(err);
}
next();
});
}
processBundle(bundle, bundleOpts, dest, res, next, opts) {
// after loading the bundle, we first want to make sure the dependency
// cache is up-to-date
this.cache[dest] = ExpressRollup.getBundleDependencies(bundle);
bundle.generate(bundleOpts)
.then((bundled) => {
this.log('Rolling up', 'finished');
const writePromise = ExpressRollup.writeBundle(bundled, dest);
this.log('Writing out', 'started');
if (opts.serve === true || opts.serve === 'on-compile') {
/** serves js code by ourselves */
this.log('Serving', 'ourselves');
res.status(200)
.type(opts.type)
.set('Cache-Control', `max-age=${opts.maxAge}`)
.send(bundled.code);
} else {
writePromise.then(() => {
this.log('Serving', 'by next()');
next();
} /* Error case for this is handled below */);
}
writePromise.then(() => {
this.log('Writing out', 'finished');
}, (err) => {
console.error(err);
// Hope, that maybe another middleware can handle things
next();
});
});
}
static writeBundle(bundle, dest) {
const dirExists = fsp.stat(dirname(dest))
.catch(() => Promise.reject(new Error('Directory to write to does not exist')))
.then((stats) => (!stats.isDirectory()
? Promise.reject(new Error('Directory to write to does not exist (not a directory)'))
: Promise.resolve()));
return dirExists.then(() => {
let promise = fsp.writeFile(dest, bundle.code);
if (bundle.map) {
const mapPromise = fsp.writeFile(`${dest}.map`, bundle.map);
promise = Promise.all([promise, mapPromise]);
}
return promise;
});
}
allFilesOlder(file, files) {
const statsPromises = [file].concat(files)
.map((f) => fsp.stat(f).then((stat) => stat, () => false));
return Promise.all(statsPromises).then((stats) => {
const fileStat = stats[0];
assert(fileStat, 'File tested for allFilesOlder does not exist?');
this.log('Stats loaded', `${stats.length - 1} dependencies`);
for (let i = 1; i < stats.length; i += 1) {
// return false if a file does not exist (any more)
if (stats[i] === false) {
return false;
}
if (fileStat.mtime.valueOf() <= stats[i].mtime.valueOf()) {
this.log('File is newer', files[i - 1]);
return false;
}
}
return true;
});
}
checkNeedsRebuild(jsPath, rollupOpts) {
const testExists = fsp.access(jsPath, fsp.F_OK);
const { cache } = this;
if (!cache[jsPath]) {
this.log('Cache miss');
return testExists
.then(
() => ({ exists: true, bundle: rollup.rollup(rollupOpts) }),
() => ({ exists: false })
)
.then((res) => {
if (res.exists === false) {
// it does not exist, so we MUST rebuild (allFilesOlder = false)
return Promise.all([false, false]);
}
return res.bundle.then((bundle) => {
this.log('Bundle loaded');
const dependencies = ExpressRollup.getBundleDependencies(bundle);
cache[jsPath] = dependencies;
return Promise.all([this.allFilesOlder(jsPath, dependencies), bundle]);
}, (err) => { throw err; });
})
.then((results) => ({ needed: !results[0], bundle: results[1] }));
}
return testExists
.then(() => this.allFilesOlder(jsPath, cache[jsPath]))
.then((allOlder) => ({ needed: !allOlder }));
}
static getBundleDependencies(bundle) {
return (bundle.modules || bundle.cache.modules).map(
(module) => module.id
).filter(path.isAbsolute);
}
}
module.exports = function createExpressRollup(options) {
const opts = Object.assign({}, defaults);
if (options.mode === 'polyfill' || (!options.mode && defaults.mode === 'polyfill')) {
if (options.dest || options.serve || options.bundleExtension) {
console.warn('Explicitly setting options of compile mode in polyfill mode');
}
// some default values will be different if mode === 'polyfill'
Object.assign(opts, {
serve: true,
bundleExtension: '.js',
dest: options.cache || options.dest || 'cache'
});
}
Object.assign(opts, options);
// We're not fancy enough to use recursive option merging (yet), so...
opts.rollupOpts = Object.assign({}, defaults.rollupOpts);
Object.assign(opts.rollupOpts, options.rollupOpts);
opts.bundleOpts = Object.assign({}, defaults.bundleOpts);
Object.assign(opts.bundleOpts, options.bundleOpts);
// Source directory (required)
assert(opts.src, 'rollup middleware requires src directory.');
// Destination directory (source by default)
opts.dest = opts.dest || opts.src;
const expressRollup = new ExpressRollup(opts);
// eslint-disable-next-line prefer-rest-params, prefer-spread
function middleware() { expressRollup.handle.apply(expressRollup, arguments); }
return middleware;
};