This repository has been archived by the owner on Sep 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
300 lines (224 loc) · 6.73 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
* grunt-connect-ssi
* https://github.com/anguspiv/grunt-connect-ssi
*
* Copyright (c) 2014 Angus Perkerson
* Licensed under the MIT license.
*/
module.exports = function ssi(opt) {
var path = require('path');
var fs = require('fs');
var URL = require('url');
//options
var opt = opt || {};
var fileTypes = opt.fileTypes ||
opt.includeList ||
['.html', '.shtml', '.inc', '.incl'];
var baseDir = opt.baseDir || __dirname;
var proxies = opt.proxies || [];
if(!Array.isArray(baseDir)) {
baseDir = [baseDir];
}
//var ssiRegex = opt.ssiRegex || /<!--\#include\s+(file|virtual)=["']([^"'<>|\b]+)['"]\s+-->/gi;
var includeRegex = opt.includeRegex || /<!--\s*\#include\s+(file|virtual)=["']([^"'<>|\b]+)['"]\s*-->/;
var ssiRegex = new RegExp(includeRegex.source, 'gi');
var ssiCache = {};
var html = opt.html || _html;
var errorMessage = opt.errorMessage !== null ? opt.errorMessage : '[There was an error processing this include]';
var fileEncoding = opt.encoding || 'utf8';
/**
* Test the string for HTML
*/
function _html(str) {
if (!str) return false;
return /<[:_-\w\s\!\/\=\"\']+>/i.test(str);
}
function accept(req) {
var ha = req.headers["accept"];
if (!ha) {
return false;
}
return (~ha.indexOf("html") || ~ha.indexOf('text'));
}
function leave(req) {
var url = req.url;
var ignored = true;
if (!url) {
return true;
}
fileTypes.forEach(function(item) {
if (~url.indexOf(item)) {
ignored = false;
}
});
return false;
}
/**
* Generates an array of the SSI tags in the given html string
* @param {string} html A string of HTML tags
* @return {Array} A list of include tag objects, with their type, path, and original tag
*/
function getIncludes(html) {
var matches = html.match(ssiRegex);
var includes = [];
if (matches) {
matches.forEach(function(match) {
var includeParts = includeRegex.exec(match);
if(includeParts) {
includes.push({
type: includeParts[1],
path: includeParts[2],
original: includeParts[0],
});
}
});
}
return includes;
}
/**
* Creates the full filepath to the include objects path
* @param {object} include The include object to get the full path for
* @param {string} currDir The filepath to the current working directory
* @return {string} The fullpath to a include objects path,
* null if the file is not found
*/
function getFilePath(include, currDir) {
var fullPath = null;
baseDir.some(function(dir) {
var filepath = dir;
if(include.type.toLowerCase() === 'file' &&
currDir) {
filepath = path.join(dir, currDir, include.path);
} else {
filepath = path.join(dir, include.path);
}
filepath = path.normalize(filepath);
if(fs.existsSync(filepath)) {
fullPath = filepath;
return true;
}
});
return fullPath;
}
/**
* Creates a key string from the passed in filepath
* @param {string} filePath the filepath to create the key for
* @return {string} A Key string for the filepath
*/
function getKey(filepath) {
var key = filepath.substring(0, filepath.lastIndexOf(path.extname(filepath)));
return key.split(/[\\\/]+/).join('-');
}
/**
* Returns the data for a entry in the cache
* @param {string} key Key for the cache entry
* @return {string} The Data for the cache entry
*/
function getCache(key) {
var cache = ssiCache[key];
return cache.processed ? cache.data : cache.data.replace(ssiRegex, errorMessage);
}
/**
* Sets an entry into the cache objects
* @param {string} key key for the cache entry
* @param {string} data data for the cache entry
* @param {bool} processed if the data has been processed yet
*/
function setCache(key, data, processed) {
ssiCache[key] = {
data:data,
processed: (processed ? true : false)
};
}
function clearCache() {
ssiCache = {};
}
function getFile(filepath) {
try {
return fs.readFileSync(filepath, fileEncoding);
} catch(e) {
console.log('Could not read file: '+ filepath +'\nERROR::\n'+e.message);
return null;
}
}
function parseSSI(data, currDir) {
currDir = currDir || '';
var body = data instanceof Buffer ? data.toString(fileEncoding) : data;
var includes = getIncludes(body);
if(includes) {
includes.forEach(function(include) {
//Grab the new Current Directory
var newDir = path.join(currDir, path.dirname(include.path));
proxies.forEach(function(proxy) {
if(include.path.indexOf(proxy.context) > -1) {
for(var rule in proxy.rewrite){
if(proxy.rewrite.hasOwnProperty(rule)) {
var regexRule = new RegExp(rule);
include.path = include.path.replace(regexRule, proxy.rewrite[rule]);
}
}
}
});
//Get the includes absolute filePath
var filepath = getFilePath(include, currDir);
var includeBuffer = filepath ? getFile(filepath) : null;
var includeData = includeBuffer !== null ? parseSSI(includeBuffer, newDir) : errorMessage;
body = body.replace(include.original.trim() , includeData);
});
}
return body;
}
return function ssi(req, res, next) {
if(res._ssi) {
return next();
}
res._ssi = true;
clearCache();
var writeHead = res.writeHead;
var write = res.write;
var end = res.end;
if(!accept(req) || leave(req)) {
return next();
}
function restore() {
res.writeHead = writeHead;
res.write = write;
res.end = end;
}
res.inject = res.write = function(string, encoding) {
fileEncoding = encoding || 'utf8';
if(string !== undefined) {
var body = string instanceof Buffer ? string.toString(encoding) : string;
if(getIncludes(body)) {
var dir = path.dirname(URL.parse(req.url).pathname);
body = parseSSI(body, dir);
}
/* Breaks multi-part HTML responses */
//restore();
return write.call(res, body, encoding);
}
return true;
};
res.writeHead = function() {
var headers = arguments[arguments.length - 1];
if(headers && typeof headers === 'object') {
for (var name in headers) {
if(/content-length/i.test(name)) {
delete headers[name];
}
}
}
var header = res.getHeader( 'content-length' );
if ( header ) res.removeHeader( 'content-length' );
writeHead.apply(res, arguments);
};
res.end = function(string, encoding) {
var result = res.inject(string, encoding);
restore();
if (!result) return end.call(res, string, encoding);
if (res.data !== undefined && !res._header) res.setHeader('content-length', Buffer.byteLength(res.data, encoding));
res.end();
};
next();
};
};