expediate 0.0.1 → 0.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.gitignore +14 -0
- package/.npmignore +14 -0
- package/README.md +29 -1
- package/index.js +83 -82
- package/package.json +5 -2
- package/sample.js +9 -0
- package/static.js +416 -0
package/.gitignore
ADDED
package/.npmignore
ADDED
package/README.md
CHANGED
|
@@ -6,10 +6,11 @@ however it doesn't intent to provide all the features.
|
|
|
6
6
|
|
|
7
7
|
[![NPM Version][npm-image]][npm-url]
|
|
8
8
|
[![NPM Downloads][downloads-image]][downloads-url]
|
|
9
|
+
<!--
|
|
9
10
|
[![Linux Build][travis-image]][travis-url]
|
|
10
11
|
[![Windows Build][appveyor-image]][appveyor-url]
|
|
11
12
|
[![Test Coverage][coveralls-image]][coveralls-url]
|
|
12
|
-
|
|
13
|
+
-->
|
|
13
14
|
```js
|
|
14
15
|
const expediate = require('expediate')
|
|
15
16
|
const app = expediate()
|
|
@@ -21,6 +22,10 @@ app.get('/', function (req, res) {
|
|
|
21
22
|
app.listen(3000)
|
|
22
23
|
```
|
|
23
24
|
|
|
25
|
+
The main reason for this package is that expressjs grow to become extra
|
|
26
|
+
complicated with tons of dependencies. Expediate aims to keep thing simple
|
|
27
|
+
while retaining the most widely used features.
|
|
28
|
+
|
|
24
29
|
## Installation
|
|
25
30
|
|
|
26
31
|
This is a [Node.js](https://nodejs.org/en/) module available through the
|
|
@@ -38,6 +43,29 @@ Installation is done using the
|
|
|
38
43
|
$ npm install expediate
|
|
39
44
|
```
|
|
40
45
|
|
|
46
|
+
## Usage
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
### Middleware
|
|
50
|
+
|
|
51
|
+
json => Parse Json body
|
|
52
|
+
static => Serve static files
|
|
53
|
+
urlencdeded => Parse url encoded
|
|
54
|
+
|
|
55
|
+
```js
|
|
56
|
+
var apiApp = expediate()
|
|
57
|
+
apiApp.use('/myEndpoint', ...)
|
|
58
|
+
|
|
59
|
+
var app = expediate();
|
|
60
|
+
var app.use('/api', apiApp);
|
|
61
|
+
|
|
62
|
+
app.listen(80)
|
|
63
|
+
app.listen(443, { key: 'xx', cert: 'xx' })
|
|
64
|
+
apiApp.listen(8900) // Only api
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
41
69
|
## License
|
|
42
70
|
|
|
43
71
|
[MIT](LICENSE)
|
package/index.js
CHANGED
|
@@ -20,9 +20,9 @@
|
|
|
20
20
|
*/
|
|
21
21
|
'use strict';
|
|
22
22
|
|
|
23
|
-
const http = require('http'),
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
const http = require('http'),
|
|
24
|
+
https = require('https'),
|
|
25
|
+
serv = require('./static.js');
|
|
26
26
|
|
|
27
27
|
/**
|
|
28
28
|
* Prepare an layer object to define a new route
|
|
@@ -32,14 +32,18 @@ const Router = {};
|
|
|
32
32
|
* @param {Listener} listener
|
|
33
33
|
* @return {Layer}
|
|
34
34
|
*/
|
|
35
|
-
|
|
35
|
+
function buildRouteLayer(method, path, listener) {
|
|
36
36
|
if (method)
|
|
37
37
|
method = method.toUpperCase();
|
|
38
|
-
if (typeof path
|
|
38
|
+
if (typeof path !== 'string' && !(path instanceof RegExp)) {
|
|
39
39
|
listener = path;
|
|
40
40
|
path = '/';
|
|
41
41
|
}
|
|
42
|
-
let parts = path.split('/').filter(x => x.length > 0);
|
|
42
|
+
let parts = path instanceof RegExp ? null : path.split('/').filter(x => x.length > 0);
|
|
43
|
+
if (listener && typeof listener !== 'function')
|
|
44
|
+
listener = listener.listener // Route object
|
|
45
|
+
if (typeof listener !== 'function')
|
|
46
|
+
throw new TypeError('Incorrect listener type');
|
|
43
47
|
return { method, path, parts, listener };
|
|
44
48
|
};
|
|
45
49
|
|
|
@@ -54,14 +58,28 @@ Router.buildLayer = function (method, path, listener) {
|
|
|
54
58
|
* @param {String[]} parts
|
|
55
59
|
* @return {Bool}
|
|
56
60
|
*/
|
|
57
|
-
|
|
61
|
+
function matchRouteLayer(layer, req, parts, path) {
|
|
58
62
|
if (layer.method && layer.method != req.method)
|
|
59
63
|
return false;
|
|
60
64
|
let params = {}
|
|
61
65
|
for (let i = 0; ; ++i) {
|
|
66
|
+
if (layer.parts == null) {
|
|
67
|
+
var m = layer.path.exec(path);
|
|
68
|
+
if (m == null)
|
|
69
|
+
return false;
|
|
70
|
+
for (let i = 1; i < m.length; ++i)
|
|
71
|
+
params[i] = m[i];
|
|
72
|
+
req.path = m.index == 0 ? path.replace(m[0], '') : path;
|
|
73
|
+
req.queries.route = params;
|
|
74
|
+
for (var k in params)
|
|
75
|
+
req.params[k] = params[k];
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
62
78
|
if (layer.parts.length <= i) {
|
|
63
79
|
req.path = '/' + parts.slice(i).join('/');
|
|
64
80
|
req.queries.route = params;
|
|
81
|
+
for (var k in params)
|
|
82
|
+
req.params[k] = params[k];
|
|
65
83
|
return true;
|
|
66
84
|
} else if (parts.length <= i)
|
|
67
85
|
return false;
|
|
@@ -79,12 +97,13 @@ Router.matchLayer = function (layer, req, parts) {
|
|
|
79
97
|
* @param {http.ClientRequest} req
|
|
80
98
|
* @param {http.ServerResponse} res
|
|
81
99
|
*/
|
|
82
|
-
|
|
100
|
+
function updateHttpObject(req, res) {
|
|
83
101
|
if (req.queries)
|
|
84
102
|
return
|
|
85
103
|
req.queries = {};
|
|
86
104
|
|
|
87
105
|
let qry = new URL(`http://${req.headers.host}${req.url}`)
|
|
106
|
+
req.originalUrl = req.url;
|
|
88
107
|
req.path = qry.pathname
|
|
89
108
|
|
|
90
109
|
// Parse URL-encoded data
|
|
@@ -92,21 +111,19 @@ Router.updateReq = function (req, res) {
|
|
|
92
111
|
for(var pair of qry.searchParams.entries())
|
|
93
112
|
params[pair[0]] = pair[1];
|
|
94
113
|
req.queries.url = params;
|
|
114
|
+
req.params = params;
|
|
95
115
|
|
|
96
116
|
// Parse cookies
|
|
97
117
|
if (req.cookies == null) {
|
|
98
118
|
req.cookies = {};
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
cookies = cookies.split(';')
|
|
119
|
+
if (req.headers.cookie) {
|
|
120
|
+
const dico = req.headers.cookie.split(';')
|
|
102
121
|
.map(x => x.replace(/^\s+|\s+$/g, '').split('='));
|
|
103
|
-
for (var k in
|
|
104
|
-
let key =
|
|
105
|
-
let val =
|
|
122
|
+
for (var k in dico) {
|
|
123
|
+
let key = dico[k][0]
|
|
124
|
+
let val = dico[k][1]
|
|
106
125
|
req.cookies[key] = val;
|
|
107
|
-
|
|
108
|
-
// TODO s: Cookie is signed, j: Cookie is a JSON
|
|
109
|
-
}
|
|
126
|
+
// TODO s: Cookie is signed, j: Cookie is a JSON
|
|
110
127
|
}
|
|
111
128
|
}
|
|
112
129
|
}
|
|
@@ -115,15 +132,16 @@ Router.updateReq = function (req, res) {
|
|
|
115
132
|
res.setHeader('X-Powered-By', 'Expediate');
|
|
116
133
|
|
|
117
134
|
res.send = (data) => {
|
|
118
|
-
|
|
135
|
+
if (data)
|
|
136
|
+
res.write(data);
|
|
119
137
|
res.end();
|
|
120
138
|
}
|
|
121
139
|
|
|
122
140
|
res.status = (code, headers) => {
|
|
141
|
+
res.statusCode = code;
|
|
123
142
|
if (headers)
|
|
124
143
|
for (var k in headers)
|
|
125
144
|
res.setHeader(k, headers[k])
|
|
126
|
-
res.writeHead(code)
|
|
127
145
|
return res;
|
|
128
146
|
};
|
|
129
147
|
|
|
@@ -157,62 +175,22 @@ Router.updateReq = function (req, res) {
|
|
|
157
175
|
|
|
158
176
|
if (opts.path == null)
|
|
159
177
|
opts.path = '/';
|
|
178
|
+
txt += `; Path=${opts.path}`
|
|
160
179
|
|
|
161
180
|
res.setHeader('Set-Cookie', txt);
|
|
162
181
|
return res;
|
|
163
182
|
};
|
|
164
183
|
|
|
165
|
-
res.sendFile = function sendFile(path, options, callback) {
|
|
166
|
-
var done = callback;
|
|
167
|
-
var req = this.req;
|
|
168
|
-
var res = this;
|
|
169
|
-
var next = req.next;
|
|
170
|
-
var opts = options || {};
|
|
171
|
-
|
|
172
|
-
if (!path) {
|
|
173
|
-
throw new TypeError('path argument is required to res.sendFile');
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
if (typeof path !== 'string') {
|
|
177
|
-
throw new TypeError('path must be a string to res.sendFile')
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
// support function as second arg
|
|
181
|
-
if (typeof options === 'function') {
|
|
182
|
-
done = options;
|
|
183
|
-
opts = {};
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
if (!opts.root && !isAbsolute(path)) {
|
|
187
|
-
throw new TypeError('path must be absolute or specify root to res.sendFile');
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
// create file stream
|
|
191
|
-
var pathname = encodeURI(path);
|
|
192
|
-
var file = send(req, pathname, opts);
|
|
193
|
-
|
|
194
|
-
// transfer
|
|
195
|
-
sendfile(res, file, opts, function (err) {
|
|
196
|
-
if (done) return done(err);
|
|
197
|
-
if (err && err.code === 'EISDIR') return next();
|
|
198
|
-
|
|
199
|
-
// next() all but write errors
|
|
200
|
-
if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
|
|
201
|
-
next(err);
|
|
202
|
-
}
|
|
203
|
-
});
|
|
204
|
-
};
|
|
205
|
-
|
|
206
184
|
};
|
|
207
185
|
|
|
208
186
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
|
209
187
|
|
|
210
|
-
module.exports =
|
|
188
|
+
module.exports = Router;
|
|
211
189
|
|
|
212
190
|
/**
|
|
213
191
|
* This function create a new router function as a web listener.
|
|
214
192
|
*/
|
|
215
|
-
function
|
|
193
|
+
function Router() {
|
|
216
194
|
|
|
217
195
|
const routes = [];
|
|
218
196
|
|
|
@@ -220,13 +198,13 @@ function NewRouter() {
|
|
|
220
198
|
const method = req.method;
|
|
221
199
|
const url = req.url;
|
|
222
200
|
let idx = 0;
|
|
223
|
-
|
|
201
|
+
updateHttpObject(req, res);
|
|
224
202
|
const parts = req.path.split('/').filter(x => x.length > 0);
|
|
225
203
|
|
|
226
204
|
const next = () => {
|
|
227
205
|
while (idx < routes.length) {
|
|
228
206
|
let layer = routes[idx++];
|
|
229
|
-
if (
|
|
207
|
+
if (matchRouteLayer(layer, req, parts, req.path))
|
|
230
208
|
return layer.listener(req, res, next);
|
|
231
209
|
}
|
|
232
210
|
|
|
@@ -243,19 +221,23 @@ function NewRouter() {
|
|
|
243
221
|
}
|
|
244
222
|
};
|
|
245
223
|
|
|
246
|
-
listener.use = (p, l) => routes.push(
|
|
247
|
-
listener.all = (p, l) => routes.push(
|
|
248
|
-
listener.get = (p, l) => routes.push(
|
|
249
|
-
listener.put = (p, l) => routes.push(
|
|
250
|
-
listener.post = (p, l) => routes.push(
|
|
251
|
-
listener.delete = (p, l) => routes.push(
|
|
252
|
-
listener.patch = (p, l) => routes.push(
|
|
253
|
-
|
|
254
|
-
listener.listen = (port, opts) => {
|
|
224
|
+
listener.use = (p, l) => routes.push(buildRouteLayer(null, p, l));
|
|
225
|
+
listener.all = (p, l) => routes.push(buildRouteLayer(null, p, l));
|
|
226
|
+
listener.get = (p, l) => routes.push(buildRouteLayer('GET', p, l));
|
|
227
|
+
listener.put = (p, l) => routes.push(buildRouteLayer('PUT', p, l));
|
|
228
|
+
listener.post = (p, l) => routes.push(buildRouteLayer('POST', p, l));
|
|
229
|
+
listener.delete = (p, l) => routes.push(buildRouteLayer('DELETE', p, l));
|
|
230
|
+
listener.patch = (p, l) => routes.push(buildRouteLayer('PATCH', p, l));
|
|
231
|
+
|
|
232
|
+
listener.listen = (port, opts, cb) => {
|
|
233
|
+
if (typeof opts === 'function') {
|
|
234
|
+
cb = opts;
|
|
235
|
+
opts = null;
|
|
236
|
+
}
|
|
255
237
|
if (opts && opts.key && opts.cert)
|
|
256
|
-
https.createServer(opts, listener).listen(port);
|
|
238
|
+
https.createServer(opts, listener).listen(port, cb);
|
|
257
239
|
else
|
|
258
|
-
http.createServer(listener).listen(port);
|
|
240
|
+
http.createServer(listener).listen(port, cb);
|
|
259
241
|
};
|
|
260
242
|
|
|
261
243
|
return listener;
|
|
@@ -263,7 +245,7 @@ function NewRouter() {
|
|
|
263
245
|
|
|
264
246
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
|
265
247
|
|
|
266
|
-
|
|
248
|
+
Router.logger = () => {
|
|
267
249
|
return (req, res, next) => {
|
|
268
250
|
const nclr = '\x1b[0m';
|
|
269
251
|
const colors = [
|
|
@@ -282,18 +264,37 @@ NewRouter.logger = () => {
|
|
|
282
264
|
const user = req.session ? `${req.session.username}/${req.session.ssid}` : '-'
|
|
283
265
|
const status = `${clr}${res.statusCode}${nclr}`
|
|
284
266
|
const elp = `${req.elapsed} ms`
|
|
285
|
-
|
|
267
|
+
const len = res.getHeader('content-length') ? res.getHeader('content-length') : '-';
|
|
268
|
+
console.log(`${rec} ${status} ${req.method} ${path} ${ip} <${user}> ${elp} (${len})`);
|
|
286
269
|
})
|
|
287
270
|
next();
|
|
288
271
|
};
|
|
289
272
|
};
|
|
290
273
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
274
|
+
Router.parseBody = () => {
|
|
275
|
+
return (req, res, next) => {
|
|
276
|
+
let data = '';
|
|
277
|
+
req.on('data', chunk => {
|
|
278
|
+
data += chunk;
|
|
279
|
+
});
|
|
280
|
+
req.on('end', () => {
|
|
281
|
+
try {
|
|
282
|
+
req.body = JSON.parse(data);
|
|
283
|
+
} catch {
|
|
284
|
+
req.body = data;
|
|
285
|
+
}
|
|
286
|
+
next();
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
Router.static = serv.serveStatic;
|
|
292
|
+
Router.file = serv.serveFile;
|
|
293
|
+
Router.sendFile = serv.sendFile;
|
|
294
|
+
Router.sendIndex = serv.sendIndex;
|
|
295
|
+
|
|
295
296
|
|
|
296
|
-
|
|
297
|
+
Router.session = (opts) => {
|
|
297
298
|
return (req, res, next) => {
|
|
298
299
|
let ssid = req.cookies.ssid;
|
|
299
300
|
req.session = opts.openSession(ssid);
|
package/package.json
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "expediate",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.3",
|
|
4
4
|
"description": "Fast and simple, minimalist web framework",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"test": "echo \"Error: no test specified\" && exit 1"
|
|
8
8
|
},
|
|
9
9
|
"author": "Fabien Bavent <fabien.bavet@gmail.com>",
|
|
10
|
-
"license": "MIT"
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"mime": "^1.6.0"
|
|
13
|
+
}
|
|
11
14
|
}
|
package/sample.js
ADDED
package/static.js
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
/* Copyright 2021 Fabien Bavent
|
|
2
|
+
*
|
|
3
|
+
* Permission is hereby granted, free of charge, to any person obtaining a
|
|
4
|
+
* copy of this software and associated documentation files (the "Software"),
|
|
5
|
+
* to deal in the Software without restriction, including without limitation
|
|
6
|
+
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
7
|
+
* and/or sell copies of the Software, and to permit persons to whom the
|
|
8
|
+
* Software is furnished to do so, subject to the following conditions:
|
|
9
|
+
*
|
|
10
|
+
* The above copyright notice and this permission notice shall be included
|
|
11
|
+
* in all copies or substantial portions of the Software.
|
|
12
|
+
*
|
|
13
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
14
|
+
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
|
16
|
+
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
18
|
+
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
19
|
+
* DEALINGS IN THE SOFTWARE.
|
|
20
|
+
*/
|
|
21
|
+
'use strict';
|
|
22
|
+
|
|
23
|
+
const fs = require('fs'),
|
|
24
|
+
path = require('path');
|
|
25
|
+
const mime = require('mime');
|
|
26
|
+
|
|
27
|
+
// Regular expression to match a path with a directory up component.
|
|
28
|
+
const UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/
|
|
29
|
+
|
|
30
|
+
const HTTP = {
|
|
31
|
+
NOT_MODIFIED: res => httpSend(res, 304),
|
|
32
|
+
FORBIDDEN: res => httpSend(res, 403, {
|
|
33
|
+
'Content-Security-Policy': "default-src 'none'",
|
|
34
|
+
'X-Content-Type-Options': 'nosniff'
|
|
35
|
+
}, 'Forbidden'),
|
|
36
|
+
NOT_FOUND: res => httpSend(res, 404, {
|
|
37
|
+
// 'Content-Type': 'text/html; charset=UTF-8',
|
|
38
|
+
'Content-Security-Policy': "default-src 'none'",
|
|
39
|
+
'X-Content-Type-Options': 'nosniff'
|
|
40
|
+
}, 'Not Found'),
|
|
41
|
+
NOT_ALLOWED: res => httpSend(res, 405, { 'Allow': 'GET, HEAD' }),
|
|
42
|
+
PRECONDITION_FAILS: res => httpSend(res, 412, {
|
|
43
|
+
'Content-Security-Policy': "default-src 'none'",
|
|
44
|
+
'X-Content-Type-Options': 'nosniff'
|
|
45
|
+
}, 'Precondition Failed'),
|
|
46
|
+
INTERNAL_ERROR: (res, err) => httpSend(res, 500, {
|
|
47
|
+
'Content-Security-Policy': "default-src 'none'",
|
|
48
|
+
'X-Content-Type-Options': 'nosniff'
|
|
49
|
+
}, `Internal error: ${err}`),
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// Destroy a read stream properly
|
|
53
|
+
function destroyReadStream(stream) {
|
|
54
|
+
stream.destroy()
|
|
55
|
+
if (typeof stream.close === 'function') {
|
|
56
|
+
// node.js core bug work-around
|
|
57
|
+
stream.on('open', _ => {
|
|
58
|
+
if (typeof stream.fd === 'number')
|
|
59
|
+
stream.close()
|
|
60
|
+
})
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function removeContentHeaders(res) {
|
|
65
|
+
var keys = Object.keys(res.getHeaders() || {});
|
|
66
|
+
for (let key of keys) {
|
|
67
|
+
if (key.substr(0, 8) === 'content-' && key != 'content-location')
|
|
68
|
+
res.removeHeader(key)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Create a simple ETag based on file metadata
|
|
73
|
+
function createETag(stat) {
|
|
74
|
+
var mtime = stat.mtime.getTime().toString(16)
|
|
75
|
+
var size = stat.size.toString(16)
|
|
76
|
+
return 'W/"' + size + '-' + mtime + '"'
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Basic utility for default answers
|
|
80
|
+
function httpSend (res, code, headers, body) {
|
|
81
|
+
headers = headers || {}
|
|
82
|
+
body = body || ''
|
|
83
|
+
res.statusCode = code;
|
|
84
|
+
for (let k in headers)
|
|
85
|
+
res.setHeader(k.toString(), headers[k].toString())
|
|
86
|
+
res.setHeader('Content-Length', Buffer.byteLength(body))
|
|
87
|
+
if (body)
|
|
88
|
+
res.write(body);
|
|
89
|
+
res.end();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Parse a HTTP token list.
|
|
93
|
+
function parseTokenList (str) {
|
|
94
|
+
var end = 0
|
|
95
|
+
var list = []
|
|
96
|
+
var start = 0
|
|
97
|
+
|
|
98
|
+
// gather tokens
|
|
99
|
+
for (var i = 0, len = str.length; i < len; i++) {
|
|
100
|
+
switch (str.charCodeAt(i)) {
|
|
101
|
+
case 0x20: /* */
|
|
102
|
+
if (start === end) {
|
|
103
|
+
start = end = i + 1
|
|
104
|
+
}
|
|
105
|
+
break
|
|
106
|
+
case 0x2c: /* , */
|
|
107
|
+
list.push(str.substring(start, end))
|
|
108
|
+
start = end = i + 1
|
|
109
|
+
break
|
|
110
|
+
default:
|
|
111
|
+
end = i + 1
|
|
112
|
+
break
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// final token
|
|
117
|
+
list.push(str.substring(start, end))
|
|
118
|
+
|
|
119
|
+
return list
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Parse an HTTP Date into a number.
|
|
123
|
+
function parseHttpDate (date) {
|
|
124
|
+
var timestamp = date && Date.parse(date)
|
|
125
|
+
|
|
126
|
+
return typeof timestamp === 'number'
|
|
127
|
+
? timestamp
|
|
128
|
+
: NaN
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function hasCondition(req) {
|
|
132
|
+
return req['if-match'] ||
|
|
133
|
+
req['if-unmodified-since'] ||
|
|
134
|
+
req['if-none-match'] ||
|
|
135
|
+
req['if-modified-since']
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function conditionMatch(req, res) {
|
|
139
|
+
|
|
140
|
+
// if-match
|
|
141
|
+
const match = req['if-match']
|
|
142
|
+
if (match) {
|
|
143
|
+
const etag = res['etag']
|
|
144
|
+
if (match === etag || match === '*')
|
|
145
|
+
return true;
|
|
146
|
+
for (let tag of parseTokenList(match))
|
|
147
|
+
if (match === tag || match === 'W/' + tag || 'W/' + match === tag)
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// if-unmodified-since
|
|
152
|
+
const lastModified = parseHttpDate(res['last-modified'])
|
|
153
|
+
const unmodifiedSince = parseHttpDate(req['if-modified-since'])
|
|
154
|
+
if (!isNaN(unmodifiedSince) && !isNaN(lastModified))
|
|
155
|
+
return lastModified <= unmodifiedSince
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
return false
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Check freshness of the response using request and response headers.
|
|
162
|
+
function isCacheFresh (req, res) {
|
|
163
|
+
const CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/
|
|
164
|
+
// fields
|
|
165
|
+
var modifiedSince = req['if-modified-since']
|
|
166
|
+
var noneMatch = req['if-none-match']
|
|
167
|
+
|
|
168
|
+
// unconditional request
|
|
169
|
+
if (!modifiedSince && !noneMatch) {
|
|
170
|
+
return false
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Always return stale when Cache-Control: no-cache
|
|
174
|
+
// to support end-to-end reload requests
|
|
175
|
+
// https://tools.ietf.org/html/rfc2616#section-14.9.4
|
|
176
|
+
var cacheControl = req['cache-control']
|
|
177
|
+
if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) {
|
|
178
|
+
return false
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// if-none-match
|
|
182
|
+
if (noneMatch && noneMatch !== '*') {
|
|
183
|
+
var etag = res['etag']
|
|
184
|
+
|
|
185
|
+
if (!etag) {
|
|
186
|
+
return false
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
var etagStale = true
|
|
190
|
+
var matches = parseTokenList(noneMatch)
|
|
191
|
+
for (var i = 0; i < matches.length; i++) {
|
|
192
|
+
var match = matches[i]
|
|
193
|
+
if (match === etag || match === 'W/' + etag || 'W/' + match === etag) {
|
|
194
|
+
etagStale = false
|
|
195
|
+
break
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (etagStale) {
|
|
200
|
+
return false
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// if-modified-since
|
|
205
|
+
if (modifiedSince) {
|
|
206
|
+
var lastModified = res['last-modified']
|
|
207
|
+
var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince))
|
|
208
|
+
|
|
209
|
+
if (modifiedStale) {
|
|
210
|
+
return false
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
return true
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function sendFile(req, res, pathname, stat, opts) {
|
|
218
|
+
const len = stat.size
|
|
219
|
+
const etag = createETag(stat)
|
|
220
|
+
|
|
221
|
+
if (opts.setHeaders)
|
|
222
|
+
opts.setHeaders(res);
|
|
223
|
+
|
|
224
|
+
// set cache-control
|
|
225
|
+
if (!res.getHeader('Cache-Control') && opts.maxage) {
|
|
226
|
+
var cacheControl = 'public, max-age=' + Math.floor(opts.maxage / 1000)
|
|
227
|
+
if (opts.immutable === true)
|
|
228
|
+
cacheControl += ', immutable'
|
|
229
|
+
res.setHeader('Cache-Control', cacheControl)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (!res.getHeader('Last-Modified') && opts.lastModified !== false)
|
|
233
|
+
res.setHeader('Last-Modified', stat.mtime.toUTCString())
|
|
234
|
+
|
|
235
|
+
if (!res.getHeader('ETag') && opts.etag !== false)
|
|
236
|
+
res.setHeader('ETag', etag)
|
|
237
|
+
|
|
238
|
+
// set content-type
|
|
239
|
+
if (!res.getHeader('Content-Type')) {
|
|
240
|
+
if (opts.contentType) {
|
|
241
|
+
res.setHeader('Content-Type', opts.contentType)
|
|
242
|
+
} else {
|
|
243
|
+
var type = mime.lookup(pathname)
|
|
244
|
+
if (type) {
|
|
245
|
+
var charset = mime.charsets.lookup(type)
|
|
246
|
+
if (charset)
|
|
247
|
+
res.setHeader('Content-Type', type + '; charset=' + charset)
|
|
248
|
+
else
|
|
249
|
+
res.setHeader('Content-Type', type)
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Conditionnal GET
|
|
255
|
+
if (hasCondition(req.headers)) {
|
|
256
|
+
if (conditionMatch(req.headers, res.getHeaders())) {
|
|
257
|
+
|
|
258
|
+
if (isCacheFresh(req.headers, res.getHeaders())) {
|
|
259
|
+
removeContentHeaders(res);
|
|
260
|
+
return HTTP.NOT_MODIFIED(res);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
// return HTTP.PRECONDITION_FAILS(res)
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
// Send data
|
|
268
|
+
res.setHeader('Content-Length', len)
|
|
269
|
+
if (req.method === 'HEAD')
|
|
270
|
+
return res.end()
|
|
271
|
+
|
|
272
|
+
let finished = false
|
|
273
|
+
const stream = fs.createReadStream(pathname);
|
|
274
|
+
res.on('finish', _ => {
|
|
275
|
+
finished = true;
|
|
276
|
+
destroyReadStream(stream);
|
|
277
|
+
});
|
|
278
|
+
stream.on('error', err => {
|
|
279
|
+
if (finished) return;
|
|
280
|
+
console.warn('static error', pathname, err)
|
|
281
|
+
HTTP.INTERNAL_ERROR(res, err.code);
|
|
282
|
+
finished = true;
|
|
283
|
+
destroyReadStream(stream);
|
|
284
|
+
});
|
|
285
|
+
stream.on('end', _ => {
|
|
286
|
+
res.end();
|
|
287
|
+
});
|
|
288
|
+
stream.pipe(res);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function sendIndex(req, res, pathname, stat, opts) {
|
|
292
|
+
|
|
293
|
+
var p = path.join(pathname, 'index.html')
|
|
294
|
+
fs.stat(p, function (err, stat) {
|
|
295
|
+
if (err) {
|
|
296
|
+
if (err.code == 'ENOENT' || err.code == 'ENAMETOOLONG' || err.code == 'ENOTDIR') {
|
|
297
|
+
if (opts.fallthrough)
|
|
298
|
+
return next();
|
|
299
|
+
return HTTP.NOT_FOUND(res)
|
|
300
|
+
}
|
|
301
|
+
return HTTP.INTERNAL_ERROR(res, err.code);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// index file support
|
|
305
|
+
if (stat.isDirectory()) {
|
|
306
|
+
return HTTP.NOT_FOUND(res);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
sendFile(req, res, p, stat, opts)
|
|
310
|
+
})
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function serveOptions(root, options) {
|
|
314
|
+
|
|
315
|
+
if (!root)
|
|
316
|
+
throw new TypeError('root path required')
|
|
317
|
+
else if (typeof root !== 'string')
|
|
318
|
+
throw new TypeError('root path must be a string')
|
|
319
|
+
|
|
320
|
+
// copy options
|
|
321
|
+
var opts = options || {
|
|
322
|
+
fallthrough: true,
|
|
323
|
+
redirect: false,
|
|
324
|
+
};
|
|
325
|
+
opts.fallthrough = opts.fallthrough !== false
|
|
326
|
+
opts.redirect = opts.redirect !== false
|
|
327
|
+
opts.maxage = opts.maxage || opts.maxAge || 0
|
|
328
|
+
opts.root = path.resolve(root)
|
|
329
|
+
if (opts.setHeaders && typeof opts.setHeaders !== 'function')
|
|
330
|
+
throw new TypeError('option setHeaders must be function')
|
|
331
|
+
|
|
332
|
+
return opts;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function serveStatic (root, options) {
|
|
336
|
+
|
|
337
|
+
var opts = serveOptions(root, options);
|
|
338
|
+
return function (req, res, next) {
|
|
339
|
+
|
|
340
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
341
|
+
if (opts.fallthrough)
|
|
342
|
+
return next()
|
|
343
|
+
return HTTP.NOT_ALLOWED(res);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
var originalUrl = decodeURIComponent(/*req.originalUrl || */req.path || req.url)
|
|
347
|
+
var pathname = originalUrl
|
|
348
|
+
|
|
349
|
+
// make sure redirect occurs at mount
|
|
350
|
+
if (pathname === '/' && originalUrl.substr(-1) !== '/') {
|
|
351
|
+
pathname = ''
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
if (UP_PATH_REGEXP.test(pathname))
|
|
355
|
+
return HTTP.FORBIDDEN(res);
|
|
356
|
+
|
|
357
|
+
// resolve the path
|
|
358
|
+
pathname = path.resolve(path.normalize(opts.root + '/' + pathname));
|
|
359
|
+
|
|
360
|
+
// dotfile handling
|
|
361
|
+
if (opts.dotfiles != 'allow' && pathname.indexOf('/.') >= 0) {
|
|
362
|
+
if (opts.dotfiles == 'deny')
|
|
363
|
+
return HTTP.FORBIDDEN(res);
|
|
364
|
+
return HTTP.NOT_FOUND(res);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
fs.stat(pathname, function onstat (err, stat) {
|
|
368
|
+
if (err) {
|
|
369
|
+
// console.log('DBG', pathname, err.code, req.originalUrl, req.url, req.path)
|
|
370
|
+
if (err.code == 'ENOENT' || err.code == 'ENAMETOOLONG' || err.code == 'ENOTDIR') {
|
|
371
|
+
if (opts.fallthrough)
|
|
372
|
+
return next();
|
|
373
|
+
console.warn('static error:', err)
|
|
374
|
+
return HTTP.NOT_FOUND(res)
|
|
375
|
+
}
|
|
376
|
+
return HTTP.INTERNAL_ERROR(res, err.code);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// index file support
|
|
380
|
+
if (stat.isDirectory()) {
|
|
381
|
+
// if (!opts.redirect)
|
|
382
|
+
// return HTTP.NOT_FOUND(res);
|
|
383
|
+
return sendIndex(req, res, pathname, stat, opts)
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
sendFile(req, res, pathname, stat, opts)
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function serveFile (root, options) {
|
|
393
|
+
|
|
394
|
+
var opts = serveOptions(root, options);
|
|
395
|
+
return function (req, res, next) {
|
|
396
|
+
|
|
397
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
398
|
+
if (opts.fallthrough)
|
|
399
|
+
return next()
|
|
400
|
+
return HTTP.NOT_ALLOWED(res);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const pathname = opts.root;
|
|
404
|
+
fs.stat(pathname, function onstat (err, stat) {
|
|
405
|
+
if (err)
|
|
406
|
+
return HTTP.INTERNAL_ERROR(res, err.code);
|
|
407
|
+
if (stat.isDirectory())
|
|
408
|
+
return HTTP.INTERNAL_ERROR(res, err.code);
|
|
409
|
+
|
|
410
|
+
sendFile(req, res, pathname, stat, opts)
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
module.exports = { serveStatic, serveFile, sendFile, sendIndex };
|