@oxog/spark 1.1.0 → 1.2.0

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.
Files changed (64) hide show
  1. package/CHANGELOG.md +632 -293
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1070 -956
  6. package/src/core/context.js +1100 -830
  7. package/src/core/middleware.js +305 -217
  8. package/src/index.js +183 -278
  9. package/src/middleware/body-parser.js +484 -526
  10. package/src/middleware/cache.js +179 -170
  11. package/src/middleware/compression.js +179 -182
  12. package/src/middleware/cors.js +178 -95
  13. package/src/middleware/health.js +221 -218
  14. package/src/middleware/logger.js +197 -194
  15. package/src/middleware/metrics.js +341 -327
  16. package/src/middleware/rate-limit.js +369 -319
  17. package/src/middleware/security.js +444 -332
  18. package/src/middleware/session.js +649 -529
  19. package/src/middleware/static.js +406 -299
  20. package/src/router/layer.js +199 -117
  21. package/src/router/route.js +151 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +147 -144
  24. package/src/utils/context-pool.js +85 -82
  25. package/src/utils/regex-validator.js +189 -176
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +536 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -957
  31. package/dist/core/context.js +0 -831
  32. package/dist/core/middleware.js +0 -218
  33. package/dist/core/request.js +0 -333
  34. package/dist/core/response.js +0 -375
  35. package/dist/index.js +0 -278
  36. package/dist/middleware/body-parser.js +0 -526
  37. package/dist/middleware/cache.js +0 -171
  38. package/dist/middleware/compression.js +0 -183
  39. package/dist/middleware/cors.js +0 -95
  40. package/dist/middleware/health.js +0 -219
  41. package/dist/middleware/index.js +0 -21
  42. package/dist/middleware/logger.js +0 -195
  43. package/dist/middleware/metrics.js +0 -328
  44. package/dist/middleware/rate-limit.js +0 -320
  45. package/dist/middleware/security.js +0 -333
  46. package/dist/middleware/session.js +0 -530
  47. package/dist/middleware/static.js +0 -299
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -117
  50. package/dist/router/route.js +0 -123
  51. package/dist/router/router.js +0 -756
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -145
  54. package/dist/utils/cache.js +0 -441
  55. package/dist/utils/context-pool.js +0 -83
  56. package/dist/utils/error-types.js +0 -132
  57. package/dist/utils/http.js +0 -413
  58. package/dist/utils/regex-validator.js +0 -177
  59. package/src/core/request.js +0 -333
  60. package/src/core/response.js +0 -375
  61. package/src/middleware/index.js +0 -21
  62. package/src/utils/cache.js +0 -441
  63. package/src/utils/error-types.js +0 -132
  64. package/src/utils/http.js +0 -413
@@ -1,756 +0,0 @@
1
- /**
2
- * @fileoverview Router class for handling HTTP routes in Spark Framework
3
- * @author Spark Framework Team
4
- * @since 1.0.0
5
- * @version 1.0.0
6
- */
7
-
8
- const Layer = require('./layer');
9
- const Route = require('./route');
10
- const { SafeRegexCache } = require('../utils/regex-validator');
11
-
12
- /**
13
- * Router class for managing HTTP routes and middleware
14
- *
15
- * The Router class provides route registration, path matching, and middleware execution.
16
- * It supports dynamic route parameters, nested routers, route grouping, and various
17
- * HTTP methods. Routes are matched using optimized regular expressions with caching.
18
- *
19
- * @class Router
20
- * @since 1.0.0
21
- *
22
- * @example
23
- * // Basic usage
24
- * const router = new Router();
25
- *
26
- * router.get('/users', (ctx) => {
27
- * ctx.json({ users: [] });
28
- * });
29
- *
30
- * router.post('/users', (ctx) => {
31
- * const user = ctx.body;
32
- * ctx.status(201).json({ id: 123, ...user });
33
- * });
34
- *
35
- * @example
36
- * // With parameters and middleware
37
- * router.get('/users/:id', authenticate, (ctx) => {
38
- * const userId = ctx.params.id;
39
- * ctx.json({ id: userId, name: 'User' });
40
- * });
41
- *
42
- * @example
43
- * // Route grouping
44
- * router.group('/api/v1', (api) => {
45
- * api.get('/users', getUsersHandler);
46
- * api.post('/users', createUserHandler);
47
- * });
48
- */
49
- class Router {
50
- /**
51
- * Create a new Router instance
52
- *
53
- * @param {Object} [options={}] - Router configuration options
54
- * @param {boolean} [options.caseSensitive=false] - Enable case-sensitive routing
55
- * @param {boolean} [options.strict=false] - Enable strict routing (trailing slash matters)
56
- *
57
- * @since 1.0.0
58
- *
59
- * @example
60
- * // Default router
61
- * const router = new Router();
62
- *
63
- * @example
64
- * // Case-sensitive router
65
- * const router = new Router({ caseSensitive: true });
66
- *
67
- * @example
68
- * // Strict routing (trailing slash matters)
69
- * const router = new Router({ strict: true });
70
- */
71
- constructor(options = {}) {
72
- /**
73
- * Router configuration options
74
- * @type {Object}
75
- * @private
76
- */
77
- this.options = {
78
- caseSensitive: false,
79
- strict: false,
80
- ...options
81
- };
82
-
83
- /**
84
- * Array of route layers (middleware and routes)
85
- * @type {Array}
86
- * @private
87
- */
88
- this.stack = [];
89
-
90
- /**
91
- * Parameter handlers for route parameters
92
- * @type {Object}
93
- * @private
94
- */
95
- this.params = {};
96
-
97
- /**
98
- * Cache for compiled regular expressions
99
- * @type {SafeRegexCache}
100
- * @private
101
- */
102
- this.regexCache = new SafeRegexCache();
103
- }
104
-
105
- /**
106
- * Add middleware to the router
107
- *
108
- * Middleware functions are executed for routes that match the specified path.
109
- * If no path is provided, middleware applies to all routes.
110
- *
111
- * @param {string|Function} pathOrMiddleware - Path pattern or middleware function
112
- * @param {...Function} middlewares - Additional middleware functions
113
- * @returns {Router} The router instance for method chaining
114
- *
115
- * @since 1.0.0
116
- *
117
- * @example
118
- * // Global middleware
119
- * router.use((ctx, next) => {
120
- * console.log(`${ctx.method} ${ctx.path}`);
121
- * return next();
122
- * });
123
- *
124
- * @example
125
- * // Path-specific middleware
126
- * router.use('/api', authenticateMiddleware);
127
- *
128
- * @example
129
- * // Multiple middleware
130
- * router.use('/admin', authenticate, authorize, logAccess);
131
- */
132
- use(pathOrMiddleware, ...middlewares) {
133
- let path = '/';
134
- let handlers = [];
135
-
136
- if (typeof pathOrMiddleware === 'string') {
137
- path = pathOrMiddleware;
138
- handlers = middlewares;
139
- } else {
140
- handlers = [pathOrMiddleware, ...middlewares];
141
- }
142
-
143
- for (const handler of handlers) {
144
- const layer = new Layer(path, {
145
- sensitive: this.options.caseSensitive,
146
- strict: this.options.strict,
147
- end: false
148
- }, handler, this);
149
-
150
- this.stack.push(layer);
151
- }
152
-
153
- return this;
154
- }
155
-
156
- /**
157
- * Register a GET route
158
- *
159
- * @param {string} path - Route path pattern
160
- * @param {...Function} handlers - Route handler functions
161
- * @returns {Route} The created route object
162
- *
163
- * @since 1.0.0
164
- *
165
- * @example
166
- * router.get('/', (ctx) => {
167
- * ctx.json({ message: 'Hello World!' });
168
- * });
169
- *
170
- * @example
171
- * // With parameters
172
- * router.get('/users/:id', (ctx) => {
173
- * const id = ctx.params.id;
174
- * ctx.json({ id, name: 'User' });
175
- * });
176
- */
177
- get(path, ...handlers) {
178
- return this.route(path, 'GET', ...handlers);
179
- }
180
-
181
- /**
182
- * Register a POST route
183
- *
184
- * @param {string} path - Route path pattern
185
- * @param {...Function} handlers - Route handler functions
186
- * @returns {Route} The created route object
187
- *
188
- * @since 1.0.0
189
- *
190
- * @example
191
- * router.post('/users', (ctx) => {
192
- * const user = ctx.body;
193
- * ctx.status(201).json({ id: 123, ...user });
194
- * });
195
- */
196
- post(path, ...handlers) {
197
- return this.route(path, 'POST', ...handlers);
198
- }
199
-
200
- /**
201
- * Register a PUT route
202
- *
203
- * @param {string} path - Route path pattern
204
- * @param {...Function} handlers - Route handler functions
205
- * @returns {Route} The created route object
206
- *
207
- * @since 1.0.0
208
- *
209
- * @example
210
- * router.put('/users/:id', (ctx) => {
211
- * const id = ctx.params.id;
212
- * const updates = ctx.body;
213
- * ctx.json({ id, ...updates });
214
- * });
215
- */
216
- put(path, ...handlers) {
217
- return this.route(path, 'PUT', ...handlers);
218
- }
219
-
220
- /**
221
- * Register a DELETE route
222
- *
223
- * @param {string} path - Route path pattern
224
- * @param {...Function} handlers - Route handler functions
225
- * @returns {Route} The created route object
226
- *
227
- * @since 1.0.0
228
- *
229
- * @example
230
- * router.delete('/users/:id', (ctx) => {
231
- * const id = ctx.params.id;
232
- * // Delete user logic
233
- * ctx.status(204).end();
234
- * });
235
- */
236
- delete(path, ...handlers) {
237
- return this.route(path, 'DELETE', ...handlers);
238
- }
239
-
240
- /**
241
- * Register a PATCH route
242
- *
243
- * @param {string} path - Route path pattern
244
- * @param {...Function} handlers - Route handler functions
245
- * @returns {Route} The created route object
246
- *
247
- * @since 1.0.0
248
- *
249
- * @example
250
- * router.patch('/users/:id', (ctx) => {
251
- * const id = ctx.params.id;
252
- * const updates = ctx.body;
253
- * ctx.json({ id, ...updates });
254
- * });
255
- */
256
- patch(path, ...handlers) {
257
- return this.route(path, 'PATCH', ...handlers);
258
- }
259
-
260
- /**
261
- * Register a HEAD route
262
- *
263
- * @param {string} path - Route path pattern
264
- * @param {...Function} handlers - Route handler functions
265
- * @returns {Route} The created route object
266
- *
267
- * @since 1.0.0
268
- *
269
- * @example
270
- * router.head('/users/:id', (ctx) => {
271
- * // Check if user exists
272
- * ctx.status(200).end();
273
- * });
274
- */
275
- head(path, ...handlers) {
276
- return this.route(path, 'HEAD', ...handlers);
277
- }
278
-
279
- /**
280
- * Register an OPTIONS route
281
- *
282
- * @param {string} path - Route path pattern
283
- * @param {...Function} handlers - Route handler functions
284
- * @returns {Route} The created route object
285
- *
286
- * @since 1.0.0
287
- *
288
- * @example
289
- * router.options('/api/*', (ctx) => {
290
- * ctx.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
291
- * ctx.status(200).end();
292
- * });
293
- */
294
- options(path, ...handlers) {
295
- return this.route(path, 'OPTIONS', ...handlers);
296
- }
297
-
298
- /**
299
- * Register a route for all HTTP methods
300
- *
301
- * @param {string} path - Route path pattern
302
- * @param {...Function} handlers - Route handler functions
303
- * @returns {Route} The created route object
304
- *
305
- * @since 1.0.0
306
- *
307
- * @example
308
- * router.all('/api/*', (ctx, next) => {
309
- * ctx.set('X-API-Version', '1.0');
310
- * return next();
311
- * });
312
- */
313
- all(path, ...handlers) {
314
- return this.route(path, null, ...handlers);
315
- }
316
-
317
- /**
318
- * Create a new route for the specified path and method
319
- *
320
- * This is an internal method used by the HTTP method functions (get, post, etc.).
321
- * It creates a new Route instance and wraps it in a Layer for the router stack.
322
- *
323
- * @param {string} path - Route path pattern
324
- * @param {string|null} method - HTTP method or null for all methods
325
- * @param {...Function} handlers - Route handler functions
326
- * @returns {Route} The created route object
327
- *
328
- * @private
329
- * @since 1.0.0
330
- */
331
- route(path, method, ...handlers) {
332
- const route = new Route(path);
333
-
334
- if (method) {
335
- route[method.toLowerCase()](...handlers);
336
- } else {
337
- route.all(...handlers);
338
- }
339
-
340
- const layer = new Layer(path, {
341
- sensitive: this.options.caseSensitive,
342
- strict: this.options.strict,
343
- end: true
344
- }, (ctx, next) => {
345
- return route.dispatch(ctx, next);
346
- }, this);
347
-
348
- layer.route = route;
349
- this.stack.push(layer);
350
-
351
- return route;
352
- }
353
-
354
- /**
355
- * Register a parameter handler
356
- *
357
- * Parameter handlers are called when a route parameter is matched.
358
- * They can be used for validation, transformation, or loading related data.
359
- *
360
- * @param {string} name - Parameter name
361
- * @param {Function} handler - Handler function (ctx, next, value, name) => {}
362
- * @returns {Router} The router instance for method chaining
363
- *
364
- * @since 1.0.0
365
- *
366
- * @example
367
- * // Load user for :userId parameter
368
- * router.param('userId', async (ctx, next, id) => {
369
- * ctx.user = await User.findById(id);
370
- * if (!ctx.user) {
371
- * ctx.status(404).json({ error: 'User not found' });
372
- * return;
373
- * }
374
- * return next();
375
- * });
376
- *
377
- * router.get('/users/:userId', (ctx) => {
378
- * ctx.json(ctx.user); // User already loaded by param handler
379
- * });
380
- */
381
- param(name, handler) {
382
- this.params[name] = handler;
383
- return this;
384
- }
385
-
386
- /**
387
- * Handle an incoming request through the router
388
- *
389
- * Processes the request through all layers (middleware and routes) in the router stack.
390
- * Matches paths, extracts parameters, and executes appropriate handlers.
391
- *
392
- * @param {Context} ctx - The request context
393
- * @param {Function} next - The next function to call if no routes match
394
- * @returns {Promise<void>}
395
- *
396
- * @since 1.0.0
397
- */
398
- async handle(ctx, next) {
399
- let layerError = null;
400
- let layerIndex = 0;
401
-
402
- const nextLayer = async (error) => {
403
- if (error) {
404
- layerError = error;
405
- }
406
-
407
- if (layerIndex >= this.stack.length) {
408
- return next(layerError);
409
- }
410
-
411
- const layer = this.stack[layerIndex++];
412
- const match = layer.match(ctx.path);
413
-
414
- if (!match) {
415
- return nextLayer(layerError);
416
- }
417
-
418
- ctx.params = { ...ctx.params, ...match.params };
419
-
420
- if (match.path !== undefined) {
421
- ctx.path = match.path;
422
- }
423
-
424
- try {
425
- await this.processParams(ctx, layer, match.params);
426
-
427
- if (layer.route) {
428
- if (layer.route.handles_method(ctx.method)) {
429
- await layer.handle(ctx, nextLayer);
430
- } else {
431
- nextLayer();
432
- }
433
- } else {
434
- await layer.handle(ctx, nextLayer);
435
- }
436
- } catch (err) {
437
- nextLayer(err);
438
- }
439
- };
440
-
441
- await nextLayer();
442
- }
443
-
444
- /**
445
- * Process route parameters through registered parameter handlers
446
- *
447
- * Calls any registered parameter handlers for the matched route parameters.
448
- * Parameter handlers can validate, transform, or load data based on parameter values.
449
- *
450
- * @param {Context} ctx - The request context
451
- * @param {Layer} layer - The matched layer
452
- * @param {Object} params - The extracted route parameters
453
- * @returns {Promise<void>}
454
- *
455
- * @private
456
- * @since 1.0.0
457
- */
458
- async processParams(ctx, layer, params) {
459
- if (!params || Object.keys(params).length === 0) {
460
- return;
461
- }
462
-
463
- for (const [key, value] of Object.entries(params)) {
464
- if (this.params[key]) {
465
- try {
466
- await this.params[key](ctx, () => {}, value, key);
467
- } catch (error) {
468
- throw error;
469
- }
470
- }
471
- }
472
- }
473
-
474
- /**
475
- * Convert a path string to a regular expression
476
- *
477
- * Converts route path patterns to regular expressions for matching URLs.
478
- * Supports parameter patterns (:param) and wildcard patterns (*wild).
479
- *
480
- * @param {string|RegExp|Array} path - Path pattern(s) to convert
481
- * @param {Object} [options={}] - Conversion options
482
- * @param {boolean} [options.sensitive=false] - Case-sensitive matching
483
- * @param {boolean} [options.strict=false] - Strict mode (trailing slash matters)
484
- * @param {boolean} [options.end=true] - Match to end of string
485
- * @returns {Object} Object with regexp and keys properties
486
- *
487
- * @static
488
- * @since 1.0.0
489
- *
490
- * @example
491
- * // Simple path
492
- * Router.pathToRegExp('/users'); // { regexp: /^\/users\/?$/, keys: [] }
493
- *
494
- * @example
495
- * // With parameters
496
- * Router.pathToRegExp('/users/:id'); // { regexp: /^\/users\/([^/]+)\/?$/, keys: [{ name: 'id', optional: false }] }
497
- */
498
- static pathToRegExp(path, options = {}) {
499
- const { sensitive = false, strict = false, end = true } = options;
500
-
501
- if (path instanceof RegExp) {
502
- return { regexp: path, keys: [] };
503
- }
504
-
505
- if (Array.isArray(path)) {
506
- const regexps = path.map(p => Router.pathToRegExp(p, options));
507
- return {
508
- regexp: new RegExp(`(?:${regexps.map(r => r.regexp.source).join('|')})`, getFlags(options)),
509
- keys: regexps.reduce((keys, r) => keys.concat(r.keys), [])
510
- };
511
- }
512
-
513
- const keys = [];
514
- let regexp = path;
515
-
516
- regexp = regexp.replace(/\\\//g, '/');
517
-
518
- regexp = regexp.replace(/:([^(/\\]+)/g, (match, key) => {
519
- keys.push({ name: key, optional: false });
520
- return '([^/]+)';
521
- });
522
-
523
- regexp = regexp.replace(/\*([^(/\\]*)/g, (match, key) => {
524
- keys.push({ name: key || 'wild', optional: false });
525
- return '(.*)';
526
- });
527
-
528
- if (end) {
529
- regexp += strict ? '' : '/?';
530
- }
531
-
532
- regexp += end ? '$' : '';
533
-
534
- const flags = getFlags(options);
535
- return {
536
- regexp: new RegExp(`^${regexp}`, flags),
537
- keys
538
- };
539
- }
540
-
541
- /**
542
- * Match a path against a regular expression and extract parameters
543
- *
544
- * Tests if a path matches the given regular expression and extracts
545
- * parameter values based on the provided keys.
546
- *
547
- * @param {string} path - The path to match
548
- * @param {RegExp} regexp - The regular expression to test against
549
- * @param {Array} keys - Array of parameter key objects
550
- * @returns {Object|false} Match object with path and params, or false if no match
551
- *
552
- * @throws {Error} When URL parameters cannot be decoded
553
- *
554
- * @static
555
- * @since 1.0.0
556
- *
557
- * @example
558
- * const { regexp, keys } = Router.pathToRegExp('/users/:id');
559
- * const match = Router.match('/users/123', regexp, keys);
560
- * // { path: '/users/123', params: { id: '123' } }
561
- */
562
- static match(path, regexp, keys) {
563
- const match = regexp.exec(path);
564
- if (!match) return false;
565
-
566
- const params = {};
567
- for (let i = 1; i < match.length; i++) {
568
- const key = keys[i - 1];
569
- const value = match[i];
570
-
571
- if (value !== undefined) {
572
- try {
573
- params[key.name] = decodeURIComponent(value);
574
- } catch (error) {
575
- // Handle malformed URL parameters
576
- throw new Error('Invalid URL parameter');
577
- }
578
- }
579
- }
580
-
581
- return {
582
- path: match[0],
583
- params
584
- };
585
- }
586
-
587
- /**
588
- * Create a route group with a common prefix
589
- *
590
- * Groups routes under a common path prefix. The callback function receives
591
- * a new router instance to define routes within the group.
592
- *
593
- * @param {string} prefix - Common path prefix for the group
594
- * @param {Function} callback - Function that receives the group router
595
- * @returns {Router} The router instance for method chaining
596
- *
597
- * @since 1.0.0
598
- *
599
- * @example
600
- * router.group('/api', (api) => {
601
- * api.get('/users', getUsersHandler);
602
- * api.post('/users', createUserHandler);
603
- * api.get('/users/:id', getUserHandler);
604
- * });
605
- * // Creates routes: GET /api/users, POST /api/users, GET /api/users/:id
606
- */
607
- group(prefix, callback) {
608
- const router = new Router(this.options);
609
- callback(router);
610
-
611
- this.use(prefix, (ctx, next) => {
612
- const originalPath = ctx.path;
613
- if (ctx.path.startsWith(prefix)) {
614
- ctx.path = ctx.path.slice(prefix.length) || '/';
615
- }
616
-
617
- return router.handle(ctx, () => {
618
- ctx.path = originalPath;
619
- return next();
620
- });
621
- });
622
-
623
- return this;
624
- }
625
-
626
- /**
627
- * Create a versioned API group
628
- *
629
- * Convenience method for creating API version groups with /v{version} prefix.
630
- *
631
- * @param {string|number} version - API version number
632
- * @param {Function} callback - Function that receives the version router
633
- * @returns {Router} The router instance for method chaining
634
- *
635
- * @since 1.0.0
636
- *
637
- * @example
638
- * router.version('1', (v1) => {
639
- * v1.get('/users', getUsersV1);
640
- * v1.post('/users', createUserV1);
641
- * });
642
- *
643
- * router.version('2', (v2) => {
644
- * v2.get('/users', getUsersV2);
645
- * v2.post('/users', createUserV2);
646
- * });
647
- * // Creates: GET /v1/users, POST /v1/users, GET /v2/users, POST /v2/users
648
- */
649
- version(version, callback) {
650
- const versionPrefix = `/v${version}`;
651
- return this.group(versionPrefix, callback);
652
- }
653
-
654
- /**
655
- * Mount another router at the specified path
656
- *
657
- * Mounts a sub-router at the given path, allowing for modular route organization.
658
- *
659
- * @param {string} path - Path prefix where the router should be mounted
660
- * @param {Router} router - Router instance to mount
661
- * @returns {Router} The router instance for method chaining
662
- *
663
- * @since 1.0.0
664
- *
665
- * @example
666
- * const userRouter = new Router();
667
- * userRouter.get('/', getUsersHandler);
668
- * userRouter.get('/:id', getUserHandler);
669
- *
670
- * const apiRouter = new Router();
671
- * apiRouter.mount('/users', userRouter);
672
- * // Creates routes: GET /users/, GET /users/:id
673
- */
674
- mount(path, router) {
675
- this.use(path, (ctx, next) => {
676
- return router.handle(ctx, next);
677
- });
678
- return this;
679
- }
680
-
681
- /**
682
- * Get all routes (layers with route objects)
683
- *
684
- * Returns an array of layers that contain route objects, filtering out
685
- * middleware-only layers.
686
- *
687
- * @returns {Array} Array of route layers
688
- *
689
- * @since 1.0.0
690
- *
691
- * @example
692
- * const routes = router.routes;
693
- * console.log(`Router has ${routes.length} routes`);
694
- */
695
- get routes() {
696
- return this.stack.filter(layer => layer.route);
697
- }
698
-
699
- /**
700
- * Returns router middleware function
701
- *
702
- * @returns {Function} Middleware function for this router
703
- * @since 1.0.0
704
- *
705
- * @example
706
- * // Mount router on app
707
- * const router = new Router();
708
- * router.get('/users', handler);
709
- * app.use('/api', router.routes());
710
- */
711
- routes() {
712
- const router = this;
713
- return function routerMiddleware(ctx, next) {
714
- return router.handle(ctx, next);
715
- };
716
- }
717
-
718
- /**
719
- * Alias for routes() method
720
- * @returns {Function} Middleware function
721
- */
722
- middleware(prefix) {
723
- const router = this;
724
- return function routerMiddleware(ctx, next) {
725
- // If prefix is provided, adjust the path
726
- if (prefix && ctx.path.startsWith(prefix)) {
727
- const originalPath = ctx.path;
728
- ctx.path = ctx.path.slice(prefix.length) || '/';
729
-
730
- return router.handle(ctx, next).then(() => {
731
- ctx.path = originalPath;
732
- }).catch(err => {
733
- ctx.path = originalPath;
734
- throw err;
735
- });
736
- }
737
- return router.handle(ctx, next);
738
- };
739
- }
740
- }
741
-
742
- /**
743
- * Get regular expression flags based on options
744
- *
745
- * @param {Object} options - Router options
746
- * @param {boolean} options.sensitive - Case sensitivity flag
747
- * @returns {string} Regular expression flags
748
- *
749
- * @private
750
- * @since 1.0.0
751
- */
752
- function getFlags(options) {
753
- return options.sensitive ? '' : 'i';
754
- }
755
-
756
- module.exports = Router;