/
index.js
109 lines (92 loc) · 2.58 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
'use strict';
//
// Required modules.
//
var Notify = require('fs.notify')
, colors = require('colors')
, path = require('path')
, fs = require('fs');
//
// Plugin name.
//
exports.name = 'watch';
/**
* Debounce function to defer the call of the supplied `fn` with `wait` ms. The
* timer will be reset as long as the function is called.
*
* @param {Function} fn function to call
* @param {Number} wait milliseconds
* @api private
*/
exports.debounce = function debounce(fn, wait) {
var timeout;
return function defer() {
var context = this
, args = arguments
, timestamp = Date.now()
, result;
function later() {
var last = Date.now() - timestamp;
if (last < wait) return timeout = setTimeout(later, wait - last);
timeout = null;
result = fn.apply(context, args);
}
if (!timeout) timeout = setTimeout(later, wait);
return result;
};
};
/**
* Server side plugin to watch pages, pagelets and views for easy reloading
* during development.
*
* @param {Pipe} bigpipe instance
* @api public
*/
exports.server = function server(bigpipe, options) {
var notifications = new Notify
, tempers = [ bigpipe.temper ];
//
// Keep track of all the temper instances for each individual pagelet.
//
bigpipe.on('transform::pagelet', function transform(pagelet) {
if (pagelet.temper) tempers.push(pagelet.temper);
});
//
// Wait till BigPipe emits listening. Compiler will have a collection of files
// to watch at that point.
//
bigpipe.once('listening', function addFiles() {
var assets = Object.keys(bigpipe.compiler.alias)
, views = Object.keys(bigpipe.temper.compiled);
/**
* Check cache and prefetch if the file is part of the compiler.
*
* @param {String} file name
* @api private
*/
function refresh(file, event, full) {
views.forEach(function loopViews(path) {
if (path !== full) return;
tempers.forEach(function eachTemper(temper) {
delete temper.file[path];
delete temper.compiled[path];
temper.prefetch(path);
});
});
assets.forEach(function loopAssets(path) {
if (path !== full) return;
bigpipe.compiler.put(path);
});
bigpipe.emit('change', file, event, full);
console.log([
'[watch] detected content changes --'.blue,
file.white,
'changed'.white
].join(' '));
}
//
// Notify the developer of changes and reload files.
//
notifications.add(assets).add(views).on('change', exports.debounce(refresh, 100));
});
};