zero-http 0.2.0 → 0.2.1
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/README.md +314 -115
- package/documentation/full-server.js +82 -1
- package/documentation/public/data/api.json +154 -33
- package/documentation/public/data/examples.json +35 -11
- package/documentation/public/data/options.json +14 -8
- package/documentation/public/index.html +109 -17
- package/documentation/public/scripts/data-sections.js +4 -4
- package/documentation/public/scripts/helpers.js +4 -4
- package/documentation/public/scripts/playground.js +201 -0
- package/documentation/public/scripts/ui.js +6 -6
- package/documentation/public/scripts/uploads.js +9 -9
- package/documentation/public/styles.css +12 -12
- package/documentation/public/vendor/icons/compress.svg +27 -0
- package/documentation/public/vendor/icons/https.svg +23 -0
- package/documentation/public/vendor/icons/router.svg +29 -0
- package/documentation/public/vendor/icons/sse.svg +25 -0
- package/documentation/public/vendor/icons/websocket.svg +21 -0
- package/index.js +21 -4
- package/lib/app.js +145 -15
- package/lib/body/json.js +3 -0
- package/lib/body/multipart.js +2 -0
- package/lib/body/raw.js +3 -0
- package/lib/body/text.js +3 -0
- package/lib/body/urlencoded.js +3 -0
- package/lib/{fetch.js → fetch/index.js} +30 -1
- package/lib/http/index.js +9 -0
- package/lib/{request.js → http/request.js} +7 -1
- package/lib/{response.js → http/response.js} +70 -1
- package/lib/middleware/compress.js +194 -0
- package/lib/middleware/index.js +12 -0
- package/lib/router/index.js +278 -0
- package/lib/sse/index.js +8 -0
- package/lib/sse/stream.js +322 -0
- package/lib/ws/connection.js +440 -0
- package/lib/ws/handshake.js +122 -0
- package/lib/ws/index.js +12 -0
- package/package.json +1 -1
- package/lib/router.js +0 -87
- /package/lib/{cors.js → middleware/cors.js} +0 -0
- /package/lib/{logger.js → middleware/logger.js} +0 -0
- /package/lib/{rateLimit.js → middleware/rateLimit.js} +0 -0
- /package/lib/{static.js → middleware/static.js} +0 -0
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @module response
|
|
2
|
+
* @module http/response
|
|
3
3
|
* @description Lightweight wrapper around Node's `ServerResponse`.
|
|
4
4
|
* Provides chainable helpers for status, headers, and body output.
|
|
5
5
|
*/
|
|
6
|
+
const SSEStream = require('../sse/stream');
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* Wrapped HTTP response.
|
|
@@ -160,6 +161,74 @@ class Response
|
|
|
160
161
|
this.set('Location', target);
|
|
161
162
|
this.send('');
|
|
162
163
|
}
|
|
164
|
+
|
|
165
|
+
// -- Server-Sent Events (SSE) ---------------------
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Open a Server-Sent Events stream. Sets the correct headers and
|
|
169
|
+
* returns an SSE controller object with methods for pushing events.
|
|
170
|
+
*
|
|
171
|
+
* The connection stays open until the client disconnects or you call
|
|
172
|
+
* `sse.close()`.
|
|
173
|
+
*
|
|
174
|
+
* @param {object} [opts]
|
|
175
|
+
* @param {number} [opts.retry] - Reconnection interval hint (ms) sent to client.
|
|
176
|
+
* @param {object} [opts.headers] - Additional headers to set on the response.
|
|
177
|
+
* @param {number} [opts.keepAlive=0] - Auto keep-alive interval in ms. `0` to disable.
|
|
178
|
+
* @param {string} [opts.keepAliveComment='ping'] - Comment text for keep-alive messages.
|
|
179
|
+
* @param {boolean} [opts.autoId=false] - Auto-increment event IDs on every `.send()` / `.event()`.
|
|
180
|
+
* @param {number} [opts.startId=1] - Starting value for auto-IDs.
|
|
181
|
+
* @param {number} [opts.pad=0] - Bytes of initial padding (helps flush proxy buffers).
|
|
182
|
+
* @param {number} [opts.status=200] - HTTP status code for the SSE response.
|
|
183
|
+
* @returns {SSEStream} SSE controller.
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* app.get('/events', (req, res) => {
|
|
187
|
+
* const sse = res.sse({ retry: 5000, keepAlive: 30000, autoId: true });
|
|
188
|
+
* sse.send('hello'); // id: 1, data: hello
|
|
189
|
+
* sse.event('update', { x: 1 }); // id: 2, event: update
|
|
190
|
+
* sse.comment('debug note'); // : debug note
|
|
191
|
+
* sse.on('close', () => console.log('gone'));
|
|
192
|
+
* });
|
|
193
|
+
*/
|
|
194
|
+
sse(opts = {})
|
|
195
|
+
{
|
|
196
|
+
if (this._sent) return null;
|
|
197
|
+
this._sent = true;
|
|
198
|
+
|
|
199
|
+
const raw = this.raw;
|
|
200
|
+
const statusCode = opts.status || 200;
|
|
201
|
+
raw.writeHead(statusCode, {
|
|
202
|
+
'Content-Type': 'text/event-stream',
|
|
203
|
+
'Cache-Control': 'no-cache',
|
|
204
|
+
'Connection': 'keep-alive',
|
|
205
|
+
'X-Accel-Buffering': 'no',
|
|
206
|
+
...(opts.headers || {}),
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
// Initial padding to push past proxy buffers (e.g. 2 KB)
|
|
210
|
+
if (opts.pad && opts.pad > 0)
|
|
211
|
+
{
|
|
212
|
+
raw.write(': ' + ' '.repeat(opts.pad) + '\n\n');
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (opts.retry)
|
|
216
|
+
{
|
|
217
|
+
raw.write(`retry: ${opts.retry}\n\n`);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Capture the Last-Event-ID header from the request if available
|
|
221
|
+
const lastEventId = this._headers['_sse_last_event_id'] || null;
|
|
222
|
+
|
|
223
|
+
return new SSEStream(raw, {
|
|
224
|
+
keepAlive: opts.keepAlive || 0,
|
|
225
|
+
keepAliveComment: opts.keepAliveComment || 'ping',
|
|
226
|
+
autoId: !!opts.autoId,
|
|
227
|
+
startId: opts.startId || 1,
|
|
228
|
+
lastEventId,
|
|
229
|
+
secure: !!(raw.socket && raw.socket.encrypted),
|
|
230
|
+
});
|
|
231
|
+
}
|
|
163
232
|
}
|
|
164
233
|
|
|
165
234
|
module.exports = Response;
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module compress
|
|
3
|
+
* @description Response compression middleware using Node's built-in `zlib`.
|
|
4
|
+
* Supports gzip, deflate, and brotli (Node >= 11.7).
|
|
5
|
+
* Zero external dependencies.
|
|
6
|
+
*/
|
|
7
|
+
const zlib = require('zlib');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Default minimum response size (in bytes) to bother compressing.
|
|
11
|
+
* Responses smaller than this are sent uncompressed.
|
|
12
|
+
* @type {number}
|
|
13
|
+
*/
|
|
14
|
+
const DEFAULT_THRESHOLD = 1024;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* MIME types that are worth compressing.
|
|
18
|
+
* Binary formats (images, video, zip) are already compressed and gain little.
|
|
19
|
+
* @type {RegExp}
|
|
20
|
+
*/
|
|
21
|
+
const COMPRESSIBLE = /^text\/|^application\/(json|javascript|xml|x-www-form-urlencoded|ld\+json|graphql|wasm)|^image\/svg\+xml/;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Create a compression middleware.
|
|
25
|
+
*
|
|
26
|
+
* @param {object} [opts]
|
|
27
|
+
* @param {number} [opts.threshold=1024] - Minimum body size in bytes to compress.
|
|
28
|
+
* @param {number} [opts.level] - Compression level (zlib.constants.Z_DEFAULT_COMPRESSION).
|
|
29
|
+
* @param {string|string[]} [opts.encoding] - Force specific encoding(s). Default: auto-negotiate.
|
|
30
|
+
* @param {Function} [opts.filter] - `(req, res) => boolean` — return false to skip compression.
|
|
31
|
+
* @returns {Function} Middleware `(req, res, next) => void`.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* const { createApp, compress } = require('zero-http');
|
|
35
|
+
* const app = createApp();
|
|
36
|
+
* app.use(compress()); // gzip/deflate/br auto-negotiated
|
|
37
|
+
* app.use(compress({ threshold: 0 })) // compress everything
|
|
38
|
+
*/
|
|
39
|
+
function compress(opts = {})
|
|
40
|
+
{
|
|
41
|
+
const threshold = opts.threshold !== undefined ? opts.threshold : DEFAULT_THRESHOLD;
|
|
42
|
+
const level = opts.level !== undefined ? opts.level : undefined;
|
|
43
|
+
const filterFn = typeof opts.filter === 'function' ? opts.filter : null;
|
|
44
|
+
const hasBrotli = typeof zlib.createBrotliCompress === 'function';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Choose the best encoding from the Accept-Encoding header.
|
|
48
|
+
* Priority: br > gzip > deflate.
|
|
49
|
+
* @param {string} header
|
|
50
|
+
* @returns {string|null}
|
|
51
|
+
*/
|
|
52
|
+
function negotiate(header)
|
|
53
|
+
{
|
|
54
|
+
if (!header) return null;
|
|
55
|
+
const h = header.toLowerCase();
|
|
56
|
+
if (hasBrotli && h.includes('br')) return 'br';
|
|
57
|
+
if (h.includes('gzip')) return 'gzip';
|
|
58
|
+
if (h.includes('deflate')) return 'deflate';
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Create a compression stream for the chosen encoding.
|
|
64
|
+
* @param {string} encoding
|
|
65
|
+
* @returns {import('stream').Transform}
|
|
66
|
+
*/
|
|
67
|
+
function createStream(encoding)
|
|
68
|
+
{
|
|
69
|
+
const zlibOpts = {};
|
|
70
|
+
if (level !== undefined) zlibOpts.level = level;
|
|
71
|
+
switch (encoding)
|
|
72
|
+
{
|
|
73
|
+
case 'br':
|
|
74
|
+
return zlib.createBrotliCompress(level !== undefined
|
|
75
|
+
? { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: level } }
|
|
76
|
+
: undefined);
|
|
77
|
+
case 'gzip':
|
|
78
|
+
return zlib.createGzip(zlibOpts);
|
|
79
|
+
case 'deflate':
|
|
80
|
+
return zlib.createDeflate(zlibOpts);
|
|
81
|
+
default:
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return (req, res, next) =>
|
|
87
|
+
{
|
|
88
|
+
// Skip if client doesn't accept encoding
|
|
89
|
+
const acceptEncoding = req.headers['accept-encoding'] || '';
|
|
90
|
+
const encoding = negotiate(acceptEncoding);
|
|
91
|
+
if (!encoding) return next();
|
|
92
|
+
|
|
93
|
+
// Allow user to skip compression
|
|
94
|
+
if (filterFn && !filterFn(req, res)) return next();
|
|
95
|
+
|
|
96
|
+
// Monkey-patch the raw response's write/end to pipe through compression
|
|
97
|
+
const raw = res.raw;
|
|
98
|
+
const origWrite = raw.write.bind(raw);
|
|
99
|
+
const origEnd = raw.end.bind(raw);
|
|
100
|
+
let compressStream = null;
|
|
101
|
+
let headersWritten = false;
|
|
102
|
+
const chunks = [];
|
|
103
|
+
|
|
104
|
+
function initCompress()
|
|
105
|
+
{
|
|
106
|
+
if (compressStream) return true;
|
|
107
|
+
|
|
108
|
+
// If headers were already committed (e.g. res.sse() calls
|
|
109
|
+
// writeHead before write), we can no longer modify them.
|
|
110
|
+
if (raw.headersSent) return false;
|
|
111
|
+
|
|
112
|
+
// Check Content-Type — skip non-compressible types
|
|
113
|
+
const ct = raw.getHeader('content-type') || '';
|
|
114
|
+
if (ct && !COMPRESSIBLE.test(ct))
|
|
115
|
+
{
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Never compress SSE streams — compression buffers
|
|
120
|
+
// the small frames and prevents real-time delivery.
|
|
121
|
+
if (ct.includes('text/event-stream'))
|
|
122
|
+
{
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
compressStream = createStream(encoding);
|
|
127
|
+
if (!compressStream) return false;
|
|
128
|
+
|
|
129
|
+
// Remove Content-Length (we don't know compressed size ahead of time)
|
|
130
|
+
raw.removeHeader('content-length');
|
|
131
|
+
raw.removeHeader('Content-Length');
|
|
132
|
+
raw.setHeader('Content-Encoding', encoding);
|
|
133
|
+
raw.setHeader('Vary', 'Accept-Encoding');
|
|
134
|
+
|
|
135
|
+
compressStream.on('data', (chunk) => origWrite(chunk));
|
|
136
|
+
compressStream.on('end', () => origEnd());
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
raw.write = function (chunk, enc, callback)
|
|
141
|
+
{
|
|
142
|
+
if (!headersWritten)
|
|
143
|
+
{
|
|
144
|
+
headersWritten = true;
|
|
145
|
+
const ct = raw.getHeader('content-type') || '';
|
|
146
|
+
initCompress();
|
|
147
|
+
if (compressStream)
|
|
148
|
+
{
|
|
149
|
+
compressStream.write(chunk, enc, callback);
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (compressStream)
|
|
154
|
+
{
|
|
155
|
+
compressStream.write(chunk, enc, callback);
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
return origWrite(chunk, enc, callback);
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
raw.end = function (chunk, encoding, callback)
|
|
162
|
+
{
|
|
163
|
+
if (!headersWritten)
|
|
164
|
+
{
|
|
165
|
+
headersWritten = true;
|
|
166
|
+
|
|
167
|
+
// Check threshold — if the total body is small, skip compression
|
|
168
|
+
const totalChunk = chunk ? (Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))) : null;
|
|
169
|
+
if (totalChunk && totalChunk.length < threshold)
|
|
170
|
+
{
|
|
171
|
+
return origEnd(chunk, encoding, callback);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
if (initCompress())
|
|
175
|
+
{
|
|
176
|
+
if (chunk) compressStream.end(chunk, encoding, callback);
|
|
177
|
+
else compressStream.end(callback);
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (compressStream)
|
|
182
|
+
{
|
|
183
|
+
if (chunk) compressStream.end(chunk, encoding, callback);
|
|
184
|
+
else compressStream.end(callback);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
return origEnd(chunk, encoding, callback);
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
next();
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
module.exports = compress;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module middleware
|
|
3
|
+
* @description Built-in middleware for zero-http.
|
|
4
|
+
* Re-exports cors, logger, rateLimit, compress, and static file serving.
|
|
5
|
+
*/
|
|
6
|
+
const cors = require('./cors');
|
|
7
|
+
const logger = require('./logger');
|
|
8
|
+
const rateLimit = require('./rateLimit');
|
|
9
|
+
const compress = require('./compress');
|
|
10
|
+
const serveStatic = require('./static');
|
|
11
|
+
|
|
12
|
+
module.exports = { cors, logger, rateLimit, compress, static: serveStatic };
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module router
|
|
3
|
+
* @description Full-featured pattern-matching router with named parameters,
|
|
4
|
+
* wildcard catch-alls, sequential handler chains, sub-router
|
|
5
|
+
* mounting, and route introspection.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Convert a route path pattern into a RegExp and extract named parameter keys.
|
|
10
|
+
* Supports `:param` segments and trailing `*` wildcards.
|
|
11
|
+
*
|
|
12
|
+
* @param {string} path - Route pattern (e.g. '/users/:id', '/api/*').
|
|
13
|
+
* @returns {{ regex: RegExp, keys: string[] }} Compiled regex and ordered parameter names.
|
|
14
|
+
*/
|
|
15
|
+
function pathToRegex(path)
|
|
16
|
+
{
|
|
17
|
+
// Wildcard catch-all: /api/*
|
|
18
|
+
if (path.endsWith('*'))
|
|
19
|
+
{
|
|
20
|
+
const prefix = path.slice(0, -1); // e.g. "/api/"
|
|
21
|
+
const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
22
|
+
return { regex: new RegExp('^' + escaped + '(.*)$'), keys: ['0'] };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const parts = path.split('/').filter(Boolean);
|
|
26
|
+
const keys = [];
|
|
27
|
+
const pattern = parts.map(p =>
|
|
28
|
+
{
|
|
29
|
+
if (p.startsWith(':')) { keys.push(p.slice(1)); return '([^/]+)'; }
|
|
30
|
+
return p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
31
|
+
}).join('/');
|
|
32
|
+
return { regex: new RegExp('^/' + pattern + '/?$'), keys };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Join two path segments, avoiding double slashes.
|
|
37
|
+
* @param {string} base
|
|
38
|
+
* @param {string} child
|
|
39
|
+
* @returns {string}
|
|
40
|
+
*/
|
|
41
|
+
function joinPath(base, child)
|
|
42
|
+
{
|
|
43
|
+
if (base === '/') return child;
|
|
44
|
+
if (child === '/') return base;
|
|
45
|
+
return base.replace(/\/$/, '') + '/' + child.replace(/^\//, '');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
class Router
|
|
49
|
+
{
|
|
50
|
+
/**
|
|
51
|
+
* Create a new Router with an empty route table.
|
|
52
|
+
* Can be used standalone as a sub-router or internally by App.
|
|
53
|
+
*/
|
|
54
|
+
constructor()
|
|
55
|
+
{
|
|
56
|
+
this.routes = [];
|
|
57
|
+
/** @type {{ prefix: string, router: Router }[]} */
|
|
58
|
+
this._children = [];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Register a route.
|
|
63
|
+
*
|
|
64
|
+
* @param {string} method - HTTP method (e.g. 'GET') or 'ALL' to match any.
|
|
65
|
+
* @param {string} path - Route pattern.
|
|
66
|
+
* @param {Function[]} handlers - One or more handler functions `(req, res, next) => void`.
|
|
67
|
+
* @param {object} [options]
|
|
68
|
+
* @param {boolean} [options.secure] - When `true`, route matches only HTTPS requests;
|
|
69
|
+
* when `false`, only HTTP. Omit to match both.
|
|
70
|
+
*/
|
|
71
|
+
add(method, path, handlers, options = {})
|
|
72
|
+
{
|
|
73
|
+
const { regex, keys } = pathToRegex(path);
|
|
74
|
+
const entry = { method: method.toUpperCase(), path, regex, keys, handlers };
|
|
75
|
+
if (options.secure !== undefined) entry.secure = !!options.secure;
|
|
76
|
+
this.routes.push(entry);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Mount a child Router under a path prefix.
|
|
81
|
+
* Requests matching the prefix are delegated to the child router with
|
|
82
|
+
* the prefix stripped from `req.url`.
|
|
83
|
+
*
|
|
84
|
+
* @param {string} prefix - Path prefix (e.g. '/api').
|
|
85
|
+
* @param {Router} router - Child router instance.
|
|
86
|
+
*/
|
|
87
|
+
use(prefix, router)
|
|
88
|
+
{
|
|
89
|
+
if (typeof prefix === 'string' && router instanceof Router)
|
|
90
|
+
{
|
|
91
|
+
const cleanPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
|
|
92
|
+
this._children.push({ prefix: cleanPrefix, router });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Match an incoming request against the route table and execute the first
|
|
98
|
+
* matching handler chain. Delegates to child routers when mounted.
|
|
99
|
+
* Sends a 404 JSON response when no route matches.
|
|
100
|
+
*
|
|
101
|
+
* @param {import('./request')} req - Wrapped request.
|
|
102
|
+
* @param {import('./response')} res - Wrapped response.
|
|
103
|
+
*/
|
|
104
|
+
handle(req, res)
|
|
105
|
+
{
|
|
106
|
+
const method = req.method.toUpperCase();
|
|
107
|
+
const url = req.url.split('?')[0];
|
|
108
|
+
|
|
109
|
+
// Try own routes first
|
|
110
|
+
for (const r of this.routes)
|
|
111
|
+
{
|
|
112
|
+
if (r.method !== 'ALL' && r.method !== method) continue;
|
|
113
|
+
// Protocol-aware matching: skip if secure flag doesn't match
|
|
114
|
+
if (r.secure === true && !req.secure) continue;
|
|
115
|
+
if (r.secure === false && req.secure) continue;
|
|
116
|
+
const m = url.match(r.regex);
|
|
117
|
+
if (!m) continue;
|
|
118
|
+
req.params = {};
|
|
119
|
+
r.keys.forEach((k, i) => req.params[k] = decodeURIComponent(m[i + 1] || ''));
|
|
120
|
+
let idx = 0;
|
|
121
|
+
const next = () =>
|
|
122
|
+
{
|
|
123
|
+
if (idx < r.handlers.length)
|
|
124
|
+
{
|
|
125
|
+
const h = r.handlers[idx++];
|
|
126
|
+
return h(req, res, next);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
return next();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Try child routers
|
|
133
|
+
for (const child of this._children)
|
|
134
|
+
{
|
|
135
|
+
if (url === child.prefix || url.startsWith(child.prefix + '/'))
|
|
136
|
+
{
|
|
137
|
+
const origUrl = req.url;
|
|
138
|
+
req.url = req.url.slice(child.prefix.length) || '/';
|
|
139
|
+
const found = child.router._tryHandle(req, res);
|
|
140
|
+
if (found) return;
|
|
141
|
+
req.url = origUrl; // restore if child didn't match
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
res.status(404).json({ error: 'Not Found' });
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Try to handle a request without sending 404 on miss.
|
|
150
|
+
* Used internally by parent routers to probe child routers.
|
|
151
|
+
*
|
|
152
|
+
* @param {import('./request')} req
|
|
153
|
+
* @param {import('./response')} res
|
|
154
|
+
* @returns {boolean} `true` if a route matched.
|
|
155
|
+
* @private
|
|
156
|
+
*/
|
|
157
|
+
_tryHandle(req, res)
|
|
158
|
+
{
|
|
159
|
+
const method = req.method.toUpperCase();
|
|
160
|
+
const url = req.url.split('?')[0];
|
|
161
|
+
|
|
162
|
+
for (const r of this.routes)
|
|
163
|
+
{
|
|
164
|
+
if (r.method !== 'ALL' && r.method !== method) continue;
|
|
165
|
+
// Protocol-aware matching: skip if secure flag doesn't match
|
|
166
|
+
if (r.secure === true && !req.secure) continue;
|
|
167
|
+
if (r.secure === false && req.secure) continue;
|
|
168
|
+
const m = url.match(r.regex);
|
|
169
|
+
if (!m) continue;
|
|
170
|
+
req.params = {};
|
|
171
|
+
r.keys.forEach((k, i) => req.params[k] = decodeURIComponent(m[i + 1] || ''));
|
|
172
|
+
let idx = 0;
|
|
173
|
+
const next = () =>
|
|
174
|
+
{
|
|
175
|
+
if (idx < r.handlers.length)
|
|
176
|
+
{
|
|
177
|
+
const h = r.handlers[idx++];
|
|
178
|
+
return h(req, res, next);
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
next();
|
|
182
|
+
return true;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
for (const child of this._children)
|
|
186
|
+
{
|
|
187
|
+
if (url === child.prefix || url.startsWith(child.prefix + '/'))
|
|
188
|
+
{
|
|
189
|
+
const origUrl = req.url;
|
|
190
|
+
req.url = req.url.slice(child.prefix.length) || '/';
|
|
191
|
+
const found = child.router._tryHandle(req, res);
|
|
192
|
+
if (found) return true;
|
|
193
|
+
req.url = origUrl;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// -- Convenience route methods (mirror App API) ----------
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* @private
|
|
204
|
+
* Extract an options object from the head of the handlers array when
|
|
205
|
+
* the first argument is a plain object (not a function).
|
|
206
|
+
*
|
|
207
|
+
* Allows: `router.get('/path', { secure: true }, handler)`
|
|
208
|
+
*/
|
|
209
|
+
_extractOpts(fns)
|
|
210
|
+
{
|
|
211
|
+
let opts = {};
|
|
212
|
+
if (fns.length > 0 && typeof fns[0] === 'object' && typeof fns[0] !== 'function')
|
|
213
|
+
{
|
|
214
|
+
opts = fns.shift();
|
|
215
|
+
}
|
|
216
|
+
return opts;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** @see Router#add */ get(path, ...fns) { const o = this._extractOpts(fns); this.add('GET', path, fns, o); return this; }
|
|
220
|
+
/** @see Router#add */ post(path, ...fns) { const o = this._extractOpts(fns); this.add('POST', path, fns, o); return this; }
|
|
221
|
+
/** @see Router#add */ put(path, ...fns) { const o = this._extractOpts(fns); this.add('PUT', path, fns, o); return this; }
|
|
222
|
+
/** @see Router#add */ delete(path, ...fns) { const o = this._extractOpts(fns); this.add('DELETE', path, fns, o); return this; }
|
|
223
|
+
/** @see Router#add */ patch(path, ...fns) { const o = this._extractOpts(fns); this.add('PATCH', path, fns, o); return this; }
|
|
224
|
+
/** @see Router#add */ options(path, ...fns) { const o = this._extractOpts(fns); this.add('OPTIONS', path, fns, o); return this; }
|
|
225
|
+
/** @see Router#add */ head(path, ...fns) { const o = this._extractOpts(fns); this.add('HEAD', path, fns, o); return this; }
|
|
226
|
+
/** @see Router#add */ all(path, ...fns) { const o = this._extractOpts(fns); this.add('ALL', path, fns, o); return this; }
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Chainable route builder — register multiple methods on the same path.
|
|
230
|
+
*
|
|
231
|
+
* @example
|
|
232
|
+
* router.route('/users')
|
|
233
|
+
* .get((req, res) => { ... })
|
|
234
|
+
* .post((req, res) => { ... });
|
|
235
|
+
*
|
|
236
|
+
* @param {string} path - Route pattern.
|
|
237
|
+
* @returns {object} Chain object with HTTP verb methods.
|
|
238
|
+
*/
|
|
239
|
+
route(path)
|
|
240
|
+
{
|
|
241
|
+
const self = this;
|
|
242
|
+
const chain = {};
|
|
243
|
+
for (const m of ['get', 'post', 'put', 'delete', 'patch', 'options', 'head', 'all'])
|
|
244
|
+
{
|
|
245
|
+
chain[m] = (...fns) => { const o = self._extractOpts(fns); self.add(m.toUpperCase(), path, fns, o); return chain; };
|
|
246
|
+
}
|
|
247
|
+
return chain;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// -- Introspection -----------------------------------
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Return a flat list of all registered routes, including those in
|
|
254
|
+
* mounted child routers. Useful for debugging or auto-documentation.
|
|
255
|
+
*
|
|
256
|
+
* @param {string} [prefix=''] - Internal: accumulated prefix from parent routers.
|
|
257
|
+
* @returns {{ method: string, path: string }[]}
|
|
258
|
+
*/
|
|
259
|
+
inspect(prefix = '')
|
|
260
|
+
{
|
|
261
|
+
const list = [];
|
|
262
|
+
for (const r of this.routes)
|
|
263
|
+
{
|
|
264
|
+
const entry = { method: r.method, path: joinPath(prefix, r.path) };
|
|
265
|
+
if (r.secure === true) entry.secure = true;
|
|
266
|
+
else if (r.secure === false) entry.secure = false;
|
|
267
|
+
list.push(entry);
|
|
268
|
+
}
|
|
269
|
+
for (const child of this._children)
|
|
270
|
+
{
|
|
271
|
+
const childPrefix = prefix ? joinPath(prefix, child.prefix) : child.prefix;
|
|
272
|
+
list.push(...child.router.inspect(childPrefix));
|
|
273
|
+
}
|
|
274
|
+
return list;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
module.exports = Router;
|