-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmoduleTree.js
58 lines (52 loc) · 1.51 KB
/
moduleTree.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
import {BloomFilter} from 'bloomfilter';
import fs from 'fs';
import _ from 'lodash';
import path from 'path';
import analyze from './analyze';
export default async function(){
const depTree = await analyze();
return function tryPush(req, res){
try{
const moduleName = req.url;
console.log('⇒', moduleName);
if(!depTree.has(moduleName)){
return;
}
const hex = req.headers['bloom-filter'];
console.log('hex:', hex);
const bf = getBloomFilter(hex);
const module = depTree.get(moduleName);
const deps = module.dependencies.map(dep => ({
name: dep,
has: bf.test(dep)
}));
for(const {name, has} of deps){
console.log(' ', has ? '✔' : '✘', name);
}
console.log('⇐', moduleName);
deps.filter(d => !d.has).forEach(({name}) => {
try{
console.log('⇐', name);
const push = res.push(name);
push.stream.on('error', error => {
push.stream.removeAllListeners();
});
push.setHeader('content-type', 'application/javascript');
push.writeHead(200);
fs.createReadStream(path.join(process.cwd(), 'public', name)).pipe(push);
}catch(e){
console.error(e.stack || e);
}
});
}catch(e){
console.error(e.stack || e);
}
}
};
function getBloomFilter(hex){
const bloomArray = _.chain(hex)
.split('|')
.map(x => parseInt(x, 16))
.value();
return new BloomFilter(bloomArray, 6);
}