@zero-server/core 0.9.1 → 0.9.2

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.
@@ -0,0 +1 @@
1
+ module.exports = require('@zero-server/lifecycle');
@@ -0,0 +1 @@
1
+ module.exports = require('@zero-server/observe');
@@ -0,0 +1 @@
1
+ module.exports = require('@zero-server/observe');
@@ -0,0 +1 @@
1
+ module.exports = require('@zero-server/observe');
@@ -0,0 +1,436 @@
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
+ * @example
8
+ * const { Router } = require('@zero-server/sdk');
9
+ *
10
+ * const api = new Router();
11
+ *
12
+ * api.get('/users/:id', (req, res) => {
13
+ * res.json({ id: req.params.id });
14
+ * });
15
+ *
16
+ * api.route('/posts')
17
+ * .get((req, res) => res.json([]))
18
+ * .post((req, res) => res.json({ created: true }));
19
+ *
20
+ * app.use('/api', api);
21
+ */
22
+
23
+ const log = require('../debug')('zero:router');
24
+
25
+ /**
26
+ * Convert a route path pattern into a RegExp and extract named parameter keys.
27
+ * Supports `:param` segments and trailing `*` wildcards.
28
+ *
29
+ * @private
30
+ * @param {string} path - Route pattern (e.g. '/users/:id', '/api/*').
31
+ * @returns {{ regex: RegExp, keys: string[] }} Compiled regex and ordered parameter names.
32
+ */
33
+ function pathToRegex(path)
34
+ {
35
+ // Wildcard catch-all: /api/*
36
+ if (path.endsWith('*'))
37
+ {
38
+ const prefix = path.slice(0, -1); // e.g. "/api/"
39
+ const escaped = prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
40
+ return { regex: new RegExp('^' + escaped + '(.*)$'), keys: ['0'] };
41
+ }
42
+
43
+ const parts = path.split('/').filter(Boolean);
44
+ const keys = [];
45
+ const pattern = parts.map(p =>
46
+ {
47
+ if (p.startsWith(':')) { keys.push(p.slice(1)); return '([^/]+)'; }
48
+ return p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
49
+ }).join('/');
50
+ return { regex: new RegExp('^/' + pattern + '/?$'), keys };
51
+ }
52
+
53
+ /**
54
+ * Join two path segments, avoiding double slashes.
55
+ * @private
56
+ * @param {string} base - Base path prefix.
57
+ * @param {string} child - Child path segment.
58
+ * @returns {string} Formatted string.
59
+ */
60
+ function joinPath(base, child)
61
+ {
62
+ if (base === '/') return child;
63
+ if (child === '/') return base;
64
+ return base.replace(/\/$/, '') + '/' + child.replace(/^\//, '');
65
+ }
66
+
67
+ class Router
68
+ {
69
+ /**
70
+ * Create a new Router with an empty route table.
71
+ * Can be used standalone as a sub-router or internally by App.
72
+ */
73
+ constructor()
74
+ {
75
+ this.routes = [];
76
+ /** @type {{ prefix: string, router: Router }[]} */
77
+ this._children = [];
78
+ /**
79
+ * Parameter pre-processing handlers (set by parent App).
80
+ * @type {Object<string, Function[]>}
81
+ */
82
+ this._paramHandlers = {};
83
+ }
84
+
85
+ // -- Core ------------------------------------------------
86
+
87
+ /**
88
+ * Register a route.
89
+ *
90
+ * @param {string} method - HTTP method (e.g. 'GET') or 'ALL' to match any.
91
+ * @param {string} path - Route pattern.
92
+ * @param {Function[]} handlers - One or more handler functions `(req, res, next) => void`.
93
+ * @param {object} [options] - Configuration options.
94
+ * @param {boolean} [options.secure] - When `true`, route matches only HTTPS requests;
95
+ * when `false`, only HTTP. Omit to match both.
96
+ */
97
+ add(method, path, handlers, options = {})
98
+ {
99
+ const { regex, keys } = pathToRegex(path);
100
+ const entry = { method: method.toUpperCase(), path, regex, keys, handlers };
101
+ if (options.secure !== undefined) entry.secure = !!options.secure;
102
+ this.routes.push(entry);
103
+ log.debug('route added %s %s', method.toUpperCase(), path);
104
+ }
105
+
106
+ /**
107
+ * Mount a child Router under a path prefix.
108
+ * Requests matching the prefix are delegated to the child router with
109
+ * the prefix stripped from `req.url`.
110
+ *
111
+ * @param {string} prefix - Path prefix (e.g. '/api').
112
+ * @param {Router} router - Child router instance.
113
+ * @returns {Router} `this` for chaining.
114
+ */
115
+ use(prefix, router)
116
+ {
117
+ if (typeof prefix === 'string' && router instanceof Router)
118
+ {
119
+ const cleanPrefix = prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
120
+ this._children.push({ prefix: cleanPrefix, router });
121
+ log.debug('mounted child router at %s', cleanPrefix);
122
+ }
123
+ return this;
124
+ }
125
+
126
+ /**
127
+ * Match an incoming request against the route table and execute the first
128
+ * matching handler chain. Delegates to child routers when mounted.
129
+ * Sends a 404 JSON response when no route matches.
130
+ *
131
+ * @param {import('./request')} req - Wrapped request.
132
+ * @param {import('./response')} res - Wrapped response.
133
+ */
134
+ handle(req, res)
135
+ {
136
+ if (!this._matchAndExecute(req, res))
137
+ {
138
+ res.status(404).json({ error: 'Not Found' });
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Try to handle a request without sending 404 on miss.
144
+ * Used internally by parent routers to probe child routers.
145
+ *
146
+ * @param {import('./request')} req - HTTP request object.
147
+ * @param {import('./response')} res - HTTP response object.
148
+ * @returns {boolean} `true` if a route matched.
149
+ * @private
150
+ */
151
+ _tryHandle(req, res)
152
+ {
153
+ return this._matchAndExecute(req, res);
154
+ }
155
+
156
+ /**
157
+ * Shared route matching and handler execution.
158
+ * Returns `true` if a route matched (handler invoked), `false` otherwise.
159
+ *
160
+ * @param {import('./request')} req - HTTP request object.
161
+ * @param {import('./response')} res - HTTP response object.
162
+ * @returns {boolean} Boolean result.
163
+ * @private
164
+ */
165
+ _matchAndExecute(req, res)
166
+ {
167
+ const method = req.method.toUpperCase();
168
+ const url = req.url.split('?')[0];
169
+ log.debug('%s %s', method, url);
170
+
171
+ // Try own routes first
172
+ for (let ri = 0; ri < this.routes.length; ri++)
173
+ {
174
+ const r = this.routes[ri];
175
+ if (r.method !== 'ALL' && r.method !== method) continue;
176
+ if (r.secure === true && !req.secure) continue;
177
+ if (r.secure === false && req.secure) continue;
178
+ const m = url.match(r.regex);
179
+ if (!m) continue;
180
+ req.params = {};
181
+ for (let i = 0; i < r.keys.length; i++)
182
+ {
183
+ req.params[r.keys[i]] = decodeURIComponent(m[i + 1] || '');
184
+ }
185
+
186
+ // Run param pre-processing handlers
187
+ const paramHandlers = this._paramHandlers || {};
188
+ let paramKeys;
189
+ let paramCount = 0;
190
+ for (let i = 0; i < r.keys.length; i++)
191
+ {
192
+ if (paramHandlers[r.keys[i]])
193
+ {
194
+ if (!paramKeys) paramKeys = [];
195
+ paramKeys.push(r.keys[i]);
196
+ paramCount++;
197
+ }
198
+ }
199
+
200
+ let pIdx = 0;
201
+ const runParams = () =>
202
+ {
203
+ if (pIdx < paramCount)
204
+ {
205
+ const pk = paramKeys[pIdx++];
206
+ const fns = paramHandlers[pk];
207
+ let fIdx = 0;
208
+ const nextParam = () =>
209
+ {
210
+ if (fIdx < fns.length)
211
+ {
212
+ const fn = fns[fIdx++];
213
+ try
214
+ {
215
+ const result = fn(req, res, nextParam, req.params[pk]);
216
+ if (result && typeof result.catch === 'function')
217
+ {
218
+ result.catch(e => this._handleRouteError(e, req, res));
219
+ }
220
+ }
221
+ catch (e) { this._handleRouteError(e, req, res); }
222
+ }
223
+ else { runParams(); }
224
+ };
225
+ nextParam();
226
+ }
227
+ else { runHandlers(); }
228
+ };
229
+
230
+ let idx = 0;
231
+ const runHandlers = () =>
232
+ {
233
+ if (idx < r.handlers.length)
234
+ {
235
+ const h = r.handlers[idx++];
236
+ try
237
+ {
238
+ const result = h(req, res, runHandlers);
239
+ if (result && typeof result.catch === 'function')
240
+ {
241
+ result.catch(e => this._handleRouteError(e, req, res));
242
+ }
243
+ }
244
+ catch (e)
245
+ {
246
+ this._handleRouteError(e, req, res);
247
+ }
248
+ }
249
+ };
250
+
251
+ if (paramCount > 0) runParams();
252
+ else runHandlers();
253
+ return true;
254
+ }
255
+
256
+ // Try child routers
257
+ for (let ci = 0; ci < this._children.length; ci++)
258
+ {
259
+ const child = this._children[ci];
260
+ if (url === child.prefix || url.startsWith(child.prefix + '/'))
261
+ {
262
+ const origUrl = req.url;
263
+ const origBaseUrl = req.baseUrl || '';
264
+ req.baseUrl = origBaseUrl + child.prefix;
265
+ req.url = req.url.slice(child.prefix.length) || '/';
266
+ child.router._paramHandlers = this._paramHandlers;
267
+ try
268
+ {
269
+ const found = child.router._matchAndExecute(req, res);
270
+ if (found) return true;
271
+ }
272
+ catch (e) { this._handleRouteError(e, req, res); return true; }
273
+ req.url = origUrl;
274
+ req.baseUrl = origBaseUrl;
275
+ }
276
+ }
277
+
278
+ return false;
279
+ }
280
+
281
+ // -- Route Shortcuts ----------------------------------------
282
+
283
+ /**
284
+ * @private
285
+ * Extract an options object from the head of the handlers array when
286
+ * the first argument is a plain object (not a function).
287
+ *
288
+ * Allows: `router.get('/path', { secure: true }, handler)`
289
+ */
290
+ _extractOpts(fns)
291
+ {
292
+ let opts = {};
293
+ if (fns.length > 0 && typeof fns[0] === 'object' && typeof fns[0] !== 'function')
294
+ {
295
+ opts = fns.shift();
296
+ }
297
+ return opts;
298
+ }
299
+
300
+ /**
301
+ * @see Router#add — shortcut for GET requests.
302
+ * @param {string} path - Route pattern.
303
+ * @param {...Function} fns - Handler functions.
304
+ * @returns {Router} `this` for chaining.
305
+ */
306
+ get(path, ...fns) { const o = this._extractOpts(fns); this.add('GET', path, fns, o); return this; }
307
+ /**
308
+ * @see Router#add — shortcut for POST requests.
309
+ * @param {string} path - Route pattern.
310
+ * @param {...Function} fns - Handler functions.
311
+ * @returns {Router} `this` for chaining.
312
+ */
313
+ post(path, ...fns) { const o = this._extractOpts(fns); this.add('POST', path, fns, o); return this; }
314
+ /**
315
+ * @see Router#add — shortcut for PUT requests.
316
+ * @param {string} path - Route pattern.
317
+ * @param {...Function} fns - Handler functions.
318
+ * @returns {Router} `this` for chaining.
319
+ */
320
+ put(path, ...fns) { const o = this._extractOpts(fns); this.add('PUT', path, fns, o); return this; }
321
+ /**
322
+ * @see Router#add — shortcut for DELETE requests.
323
+ * @param {string} path - Route pattern.
324
+ * @param {...Function} fns - Handler functions.
325
+ * @returns {Router} `this` for chaining.
326
+ */
327
+ delete(path, ...fns) { const o = this._extractOpts(fns); this.add('DELETE', path, fns, o); return this; }
328
+ /**
329
+ * @see Router#add — shortcut for PATCH requests.
330
+ * @param {string} path - Route pattern.
331
+ * @param {...Function} fns - Handler functions.
332
+ * @returns {Router} `this` for chaining.
333
+ */
334
+ patch(path, ...fns) { const o = this._extractOpts(fns); this.add('PATCH', path, fns, o); return this; }
335
+ /**
336
+ * @see Router#add — shortcut for OPTIONS requests.
337
+ * @param {string} path - Route pattern.
338
+ * @param {...Function} fns - Handler functions.
339
+ * @returns {Router} `this` for chaining.
340
+ */
341
+ options(path, ...fns) { const o = this._extractOpts(fns); this.add('OPTIONS', path, fns, o); return this; }
342
+ /**
343
+ * @see Router#add — shortcut for HEAD requests.
344
+ * @param {string} path - Route pattern.
345
+ * @param {...Function} fns - Handler functions.
346
+ * @returns {Router} `this` for chaining.
347
+ */
348
+ head(path, ...fns) { const o = this._extractOpts(fns); this.add('HEAD', path, fns, o); return this; }
349
+ /**
350
+ * @see Router#add — matches every HTTP method.
351
+ * @param {string} path - Route pattern.
352
+ * @param {...Function} fns - Handler functions.
353
+ * @returns {Router} `this` for chaining.
354
+ */
355
+ all(path, ...fns) { const o = this._extractOpts(fns); this.add('ALL', path, fns, o); return this; }
356
+
357
+ /**
358
+ * Chainable route builder — register multiple methods on the same path.
359
+ *
360
+ * @example
361
+ * router.route('/users')
362
+ * .get((req, res) => { ... })
363
+ * .post((req, res) => { ... });
364
+ *
365
+ * @param {string} path - Route pattern.
366
+ * @returns {{ get, post, put, delete, patch, options, head, all: Function }} Chain object with HTTP verb methods.
367
+ */
368
+ route(path)
369
+ {
370
+ const self = this;
371
+ const chain = {};
372
+ for (const m of ['get', 'post', 'put', 'delete', 'patch', 'options', 'head', 'all'])
373
+ {
374
+ chain[m] = (...fns) => { const o = self._extractOpts(fns); self.add(m.toUpperCase(), path, fns, o); return chain; };
375
+ }
376
+ return chain;
377
+ }
378
+
379
+ // -- Introspection -----------------------------------
380
+
381
+ /**
382
+ * Handle an error thrown by a route handler.
383
+ * Delegates to the app-level error handler if available, otherwise
384
+ * sends a generic 500 JSON response.
385
+ *
386
+ * @param {Error} err - Error object.
387
+ * @param {import('../http/request')} req - HTTP request object.
388
+ * @param {import('../http/response')} res - HTTP response object.
389
+ * @private
390
+ */
391
+ _handleRouteError(err, req, res)
392
+ {
393
+ log.error('route error: %s', err.message || err);
394
+ // Check if the app has an error handler (set via app.onError())
395
+ if (req.app && req.app._errorHandler)
396
+ {
397
+ return req.app._errorHandler(err, req, res, () => {});
398
+ }
399
+ const statusCode = err.statusCode || err.status || 500;
400
+ if (!res.headersSent && !(res.raw && res.raw.headersSent))
401
+ {
402
+ res.status(statusCode).json(
403
+ typeof err.toJSON === 'function'
404
+ ? err.toJSON()
405
+ : { error: err.message || 'Internal Server Error' }
406
+ );
407
+ }
408
+ }
409
+
410
+ /**
411
+ * Return a flat list of all registered routes, including those in
412
+ * mounted child routers. Useful for debugging or auto-documentation.
413
+ *
414
+ * @param {string} [prefix=''] - Internal: accumulated prefix from parent routers.
415
+ * @returns {{ method: string, path: string, secure?: boolean }[]} Registered routes.
416
+ */
417
+ inspect(prefix = '')
418
+ {
419
+ const list = [];
420
+ for (const r of this.routes)
421
+ {
422
+ const entry = { method: r.method, path: joinPath(prefix, r.path) };
423
+ if (r.secure === true) entry.secure = true;
424
+ else if (r.secure === false) entry.secure = false;
425
+ list.push(entry);
426
+ }
427
+ for (const child of this._children)
428
+ {
429
+ const childPrefix = prefix ? joinPath(prefix, child.prefix) : child.prefix;
430
+ list.push(...child.router.inspect(childPrefix));
431
+ }
432
+ return list;
433
+ }
434
+ }
435
+
436
+ module.exports = Router;
@@ -0,0 +1 @@
1
+ module.exports = require('@zero-server/realtime').SSEStream;
@@ -0,0 +1 @@
1
+ module.exports = require('@zero-server/realtime');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero-server/core",
3
- "version": "0.9.1",
3
+ "version": "0.9.2",
4
4
  "description": "App factory, Router, and the HTTP Request/Response wrappers.",
5
5
  "keywords": [
6
6
  "zero-server",
@@ -20,6 +20,7 @@
20
20
  "./package.json": "./package.json"
21
21
  },
22
22
  "files": [
23
+ "lib",
23
24
  "index.js",
24
25
  "index.d.ts",
25
26
  "README.md",
@@ -43,6 +44,18 @@
43
44
  },
44
45
  "sideEffects": false,
45
46
  "dependencies": {
46
- "@zero-server/sdk": "0.9.1"
47
+ "@zero-server/realtime": "0.9.2",
48
+ "@zero-server/grpc": "0.9.2",
49
+ "@zero-server/lifecycle": "0.9.2",
50
+ "@zero-server/observe": "0.9.2",
51
+ "@zero-server/auth": "0.9.2"
52
+ },
53
+ "peerDependencies": {
54
+ "@zero-server/sdk": ">=0.9.2"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "@zero-server/sdk": {
58
+ "optional": true
59
+ }
47
60
  }
48
61
  }