-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
233 lines (200 loc) · 6.94 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
/*
* Module dependencies.
*/
var debug = require('debug')('koa-stylreworka');
var fs = require('fs');
var cofs = require('co-fs');
var path = require('path');
var crc = require('buffer-crc32').signed;
var rework = require('rework');
var whitespace = require('css-whitespace');
var autoprefixer = require('autoprefixer')
/**
* Return koajs middleware with styl-like css-whitespace - reworkcss - autoprefixer pipeline.
* `src` {String} required - root dir for .styl files
* `dest` {String} optional, default: src - root dir for .css files
* `transformPath`{function(reqPath):string} optional - function to allow url path transforms
* `force` {Boolean} optional, default: false - when true, always compile
* `reworkcss` {function(reworkcss, String):String} optional - function to rework css using reworkcss/rework
* `autoprefixer` {function(autoprefixer, String):String} optional - function to prefix css using ai/autoprefixer
*
* Note: Src files can be either .styl (whitespace significant files) or .css files. If both exists in src then
* .styl will be used. .css files will skip the css-whitespace preprocessing and if src & dest are the same and
* no .styl file exists in that location the .css will be served as a static css file with no preprocessing.
*/
module.exports = function stylreworka(options) {
options = options || {};
if ('string' == typeof options)
options = {
src: options
};
// must have a src
if (!options.src)
throw new Error('Options: options.src is required.')
// default dst to src
options.dest = options.dest || options.src;
// these must be functions
if (options.transformPath && 'function' !== typeof options.transformPath)
throw new Error('Options: options.transformPath must be a function.');
if (options.reworkcss && 'function' !== typeof options.reworkcss)
throw new Error('Options: options.reworkcss must be a function.');
if (options.autoprefixer && 'function' !== typeof options.autoprefixer)
throw new Error('Options: options.autoprefixer must be a function.');
// defaults if not provided
options.transformPath = options.transformPath || function(path) {
return path;
};
/**
* Cache is of the form:
*
* {
* <target> : {
* etag: <number>,
* mtime: <mtime ms>,
* files: [
* <dependant filepath>,
* <dependant filepath>
* ]
* }
* }
*
*/
var cache = {};
// check mtimes
function* checkMTimes(target) {
var tcache = cache[target];
// no mtime so outdated
if (!tcache.mtime)
return false;
// get mtime of target and check dependant mtimes
var tmtime;
try {
// get mtime of target and
var stat = (yield cofs.stat(target));
tmtime = stat.mtime.getTime()
// check against cached target mtime
if (tmtime < tcache.mtime)
return false;
} catch(e) {
return false; // doesn't exist
}
if (tcache.files) {
// dependents
for (var i = 0; i < tcache.files.length; i++) {
try {
var stat = yield cofs.stat(tcache.files[i]);
if (tmtime < stat.mtime.getTime())
return false;
} catch(e) {
return false;
}
}
}
return true;
}
// css @import resolver (updates dependants)
function importResolver(root, target) {
var files = cache[target].files = cache[target].files || [];
return function(p) {
// only match .styl extension or no extension at all
var match = p.match(/^['"]?(.+?)(?:\.styl)?['"]?$/);
if (match) {
var file = path.join(root, match[1]) + '.styl'
if (fs.existsSync(file)) {
debug('resolved ' + match[1] + '.styl');
files.push(file);
return fs.readFileSync(file, 'utf8');
}
}
debug('unresolved ' + p);
return null;
}
}
// handle *.css requests
return function* stylreworka(next) {
// filter on HTTP GET/HEAD & *.css resource
if (('GET' !== this.method && 'HEAD' !== this.method) || !/\.css$/.test(this.path))
return yield* next;
var dst = path.join(options.dest, this.path);
var dstExists = yield cofs.exists(dst);
// init mtimes cache
cache[dst] = cache[dst] || {};
// check freshness if dst exists
if (dstExists && !options.force && (yield checkMTimes(dst))) {
// prep for freshness check
this.status = 200;
this.set('ETag', '"' + cache[dst].etag + '"');
// fresh?
if (this.fresh) {
debug('css is fresh (' + this.path + ')');
this.status = 304;
} else {
debug('css is stale (' + this.path + ')');
this.body = yield cofs.readFile(dst, 'utf8');
this.set('Content-Type', 'text/css');
}
return yield* next;
}
// probe for src & src type (.css/.styl)
var src = path.join(options.src, options.transformPath(this.path));
var dstEQsrc = (dst === src);
var cssExists = yield cofs.exists(src);
var stylExists = yield cofs.exists(src.replace('.css', '.styl'));
var srcExists = (dstEQsrc && stylExists) || (!dstEQsrc && (cssExists || stylExists));
// if dst & src don't exist hand off downstream
if (!dstExists && !srcExists)
return yield* next;
// can only serve dst css
if ((dstEQsrc && !stylExists) || (dstExists && !srcExists)) {
// just serve static css if it exists
debug('serving dst css (' + this.path + ')');
this.status = 200;
this.body = yield cofs.readFile(dst, 'utf8');
cache[dst].etag = crc(this.body);
cache[dst].mtime = (yield cofs.stat(dst)).mtime.getTime();
this.set('Content-Type', 'text/css');
this.set('ETag', '"' + cache[dst].etag + '"');
return yield* next;
}
// preprocess
var css;
// if src is .styl
if (stylExists) {
debug('css-whitespace (' + this.path + ')');
// css-whitespace
src = src.replace('.css', '.styl');
css = whitespace('@import ' + path.basename(src), {
resolver: importResolver(path.dirname(src), dst)
});
}
// if src is .css
if (!css && cssExists) {
debug('src is css (' + this.path + ')');
cache[dst].files = [src];
css = yield cofs.readFile(src, 'utf8');
}
// reworkcss
if (css && options.reworkcss) {
debug('reworkcss (' + this.path + ')');
css = options.reworkcss(rework, css);
}
// autoprefixer
if (css && options.autoprefixer) {
debug('autoprefixer (' + this.path + ')');
css = options.autoprefixer(autoprefixer, css);
}
// calc etag
cache[dst].etag = crc(css);
// response
debug('serving processed css (' + this.path + ')');
this.body = css;
this.status = 200;
this.set('Content-Type', 'text/css');
this.set('ETag', '"' + cache[dst].etag + '"');
// save
yield cofs.writeFile(dst, css, 'utf8');
cache[dst].mtime = (yield cofs.stat(dst)).mtime.getTime();
// allow downstream middlewares to do work
yield* next;
}
};