@vyriy/router 0.8.3 → 0.8.5

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 CHANGED
@@ -16,11 +16,15 @@ This package provides a small router for Lambda handlers and native Node HTTP se
16
16
 
17
17
  It is intentionally kept small:
18
18
 
19
- - matches by HTTP method and exact path
19
+ - matches by HTTP method and exact path through an O(1) hash lookup
20
+ - matches `:param` segments (for example `/api/tenants/:tenantId`) and exposes the captured values
21
+ - matches any HTTP method on a path through `all(path, handler)`
20
22
  - passes API Gateway event data into handlers (or raw Node request/response for the HTTP router)
21
23
  - returns a Lambda-friendly response shape (the stream and HTTP routers write the response instead)
22
24
 
23
- It does not try to be a path parser or dispatcher. If you later need regular expressions, wildcard matching, route params extraction, or more advanced dispatch rules, that logic should live in a separate package or layer.
25
+ Matching stays fast: exact static paths are resolved first through the hash lookup, and `:param` routes are only scanned when that lookup misses, so static traffic never pays for parameter matching. Resolution runs from the most specific match to the most general: exact path, dynamic path, `all` path, fallback. Parameter matching is segment-based (no regular expressions), and static segments win over `:param` segments from left to right.
26
+
27
+ It still does not try to be a general dispatcher. If you need regular expressions, wildcards, or more advanced dispatch rules, that logic should live in a separate package or layer.
24
28
 
25
29
  ## Install
26
30
 
@@ -65,6 +69,57 @@ router.fallback(async ({ event }) => ({
65
69
  export const handler = router.handle();
66
70
  ```
67
71
 
72
+ ## Route Parameters
73
+
74
+ Any segment that starts with `:` is a named parameter. Captured values are merged
75
+ into `pathParameters` (alongside any values API Gateway already provided), and
76
+ captured values win on key conflicts:
77
+
78
+ ```ts
79
+ router.get('/api/tenants/:tenantId/runs/:runId', async ({ pathParameters }) => ({
80
+ body: JSON.stringify({
81
+ tenantId: pathParameters?.tenantId,
82
+ runId: pathParameters?.runId,
83
+ }),
84
+ }));
85
+ ```
86
+
87
+ Values are URL-decoded (`/users/john%20doe` yields `john doe`). When two dynamic
88
+ routes could match the same path, the one whose static segment appears earlier
89
+ from left to right wins, so `/a/b/:y` is preferred over `/a/:x/c` for `/a/b/c`.
90
+ Registering two routes that resolve to the same pattern (such as `/a/:x` and
91
+ `/a/:y`), reusing a parameter name, or using an empty `:` name throws at
92
+ registration time.
93
+
94
+ The native HTTP router exposes captured values on `request.params` instead, since
95
+ its handlers receive the raw request and response:
96
+
97
+ ```ts
98
+ import type { RequestWithParams } from '@vyriy/router/http';
99
+
100
+ httpRouter.get('/api/tenants/:tenantId', (request, response) => {
101
+ const { tenantId } = (request as RequestWithParams).params ?? {};
102
+
103
+ response.writeHead(200).end(JSON.stringify({ tenantId }));
104
+ });
105
+ ```
106
+
107
+ ## All Methods
108
+
109
+ Every variant supports `all(path, handler)` for routes that accept any HTTP
110
+ method, which suits transports that multiplex methods on one path (such as MCP
111
+ Streamable HTTP). Method-specific routes take precedence over `all` routes on the
112
+ same path, and `all` paths may use `:param` segments too:
113
+
114
+ ```ts
115
+ router.all('/webhook/:provider', async ({ pathParameters, event }) => ({
116
+ body: JSON.stringify({
117
+ provider: pathParameters?.provider,
118
+ method: event.httpMethod,
119
+ }),
120
+ }));
121
+ ```
122
+
68
123
  ## Stream Router
69
124
 
70
125
  Use the streaming router when handlers write directly to a Lambda response stream. The stream is passed as the second handler argument, and stream handlers do not return a response object.
@@ -246,6 +301,8 @@ The low-level `Router` classes are exported from each entry: `Router` from `@vyr
246
301
  - `createRouter()` returns a chainable router API.
247
302
  - `createStreamRouter()` returns a chainable response streaming router API.
248
303
  - `createHttpRouter()` returns a chainable native HTTP router API.
304
+ - Paths may contain `:param` segments on every method helper, `all`, and `on`.
305
+ - `router.all(path, handler)` registers a handler for any HTTP method on a path.
249
306
  - `router.get(path, handler)` registers a `GET` handler.
250
307
  - `router.post(path, handler)` registers a `POST` handler.
251
308
  - `router.put(path, handler)` registers a `PUT` handler.
@@ -254,6 +311,7 @@ The low-level `Router` classes are exported from each entry: `Router` from `@vyr
254
311
  - `router.fallback(handler)` registers a handler for unmatched requests.
255
312
  - `router.handle()` returns `(event) => router.route(event)` for API Gateway wrappers.
256
313
  - `router.route(event)` resolves the matching route and returns an API Gateway response.
314
+ - `streamRouter.all(path, handler)` registers a stream handler for any HTTP method on a path.
257
315
  - `streamRouter.handle()` returns `(event, responseStream) => streamRouter.route(event, responseStream)` for stream wrappers.
258
316
  - `streamRouter.route(event, responseStream)` resolves the matching route and writes to the stream.
259
317
  - `httpRouter.all(path, handler)` registers a handler for any HTTP method on an exact path.
@@ -265,9 +323,11 @@ Route handlers may omit `statusCode`; the router normalizes missing status codes
265
323
  The low-level `Router`, `StreamRouter`, and `HttpRouter` classes are also available from `@vyriy/router` (each variant additionally exports its class as `Router` from its own subpath):
266
324
 
267
325
  - `router.on(method, path, handler)`
326
+ - `router.all(path, handler)`
268
327
  - `router.fallback(handler)`
269
328
  - `router.route(event)`
270
329
  - `streamRouter.on(method, path, handler)`
330
+ - `streamRouter.all(path, handler)`
271
331
  - `streamRouter.fallback(handler)`
272
332
  - `streamRouter.route(event, responseStream)`
273
333
  - `httpRouter.on(method, path, handler)`
package/base.d.ts CHANGED
@@ -1,6 +1,18 @@
1
+ export type RouteParams = Record<string, string>;
2
+ export type Match<CurrentHandler> = {
3
+ handler: CurrentHandler;
4
+ params: RouteParams;
5
+ };
6
+ export declare const mergeParams: (existing: Record<string, string | undefined> | null | undefined, params: RouteParams) => Record<string, string | undefined> | undefined;
1
7
  export declare class BaseRouter<CurrentHandler> {
2
8
  protected fallbackHandler?: CurrentHandler;
3
9
  protected readonly routes: Record<string, Record<string, CurrentHandler>>;
10
+ private readonly dynamicRoutes;
11
+ private readonly dynamicSignatures;
4
12
  on(method: string, path: string, handler: CurrentHandler): this;
13
+ all(path: string, handler: CurrentHandler): this;
5
14
  fallback(handler: CurrentHandler): this;
15
+ protected match(method: string, pathname: string): Match<CurrentHandler> | undefined;
16
+ private register;
17
+ private registerDynamic;
6
18
  }
package/base.js CHANGED
@@ -1,25 +1,143 @@
1
1
  import { METHODS } from 'node:http';
2
2
  const SUPPORTED_METHODS = new Set(METHODS.map((method) => method.toUpperCase()));
3
- const registerRoute = (routes, method, path, handler) => {
4
- const normalizedMethod = method.toUpperCase();
5
- if (!SUPPORTED_METHODS.has(normalizedMethod)) {
6
- throw new Error(`Unsupported HTTP method: ${normalizedMethod}`);
3
+ const ALL_METHODS = '*';
4
+ const EMPTY_PARAMS = Object.freeze({});
5
+ const splitPath = (path) => path.split('/');
6
+ const methodLabel = (method) => (method === ALL_METHODS ? 'ALL' : method);
7
+ const decodeSegment = (value) => {
8
+ try {
9
+ return decodeURIComponent(value);
7
10
  }
8
- const routeGroup = (routes[normalizedMethod] ??= {});
9
- if (routeGroup[path]) {
10
- throw new Error(`${normalizedMethod} ${path} already exists!`);
11
+ catch {
12
+ return value;
11
13
  }
12
- routeGroup[path] = handler;
14
+ };
15
+ const parsePattern = (path) => {
16
+ const segments = splitPath(path);
17
+ const mask = segments.map((segment) => (segment.startsWith(':') ? 1 : 0));
18
+ const names = new Set();
19
+ segments.forEach((segment) => {
20
+ if (!segment.startsWith(':')) {
21
+ return;
22
+ }
23
+ const name = segment.slice(1);
24
+ if (!name) {
25
+ throw new Error(`Invalid route parameter in ${path}`);
26
+ }
27
+ if (names.has(name)) {
28
+ throw new Error(`Duplicate route parameter ":${name}" in ${path}`);
29
+ }
30
+ names.add(name);
31
+ });
32
+ return { segments, mask, dynamic: mask.includes(1) };
33
+ };
34
+ const signatureOf = (segments, mask) => segments.map((segment, index) => (mask[index] ? ':' : segment)).join('/');
35
+ const compareSpecificity = (left, right) => {
36
+ const length = Math.min(left.mask.length, right.mask.length);
37
+ for (let index = 0; index < length; index += 1) {
38
+ if (left.mask[index] !== right.mask[index]) {
39
+ return left.mask[index] - right.mask[index];
40
+ }
41
+ }
42
+ return left.mask.length - right.mask.length;
43
+ };
44
+ const matchDynamic = (routes, segments) => {
45
+ if (!routes) {
46
+ return undefined;
47
+ }
48
+ for (const route of routes) {
49
+ if (route.segments.length !== segments.length) {
50
+ continue;
51
+ }
52
+ const params = {};
53
+ let matched = true;
54
+ for (let index = 0; index < segments.length; index += 1) {
55
+ if (route.mask[index]) {
56
+ params[route.segments[index].slice(1)] = decodeSegment(segments[index]);
57
+ continue;
58
+ }
59
+ if (route.segments[index] !== segments[index]) {
60
+ matched = false;
61
+ break;
62
+ }
63
+ }
64
+ if (matched) {
65
+ return { handler: route.handler, params };
66
+ }
67
+ }
68
+ return undefined;
69
+ };
70
+ export const mergeParams = (existing, params) => {
71
+ if (Object.keys(params).length === 0) {
72
+ return existing ?? undefined;
73
+ }
74
+ return { ...existing, ...params };
13
75
  };
14
76
  export class BaseRouter {
15
77
  fallbackHandler;
16
78
  routes = {};
79
+ dynamicRoutes = {};
80
+ dynamicSignatures = {};
17
81
  on(method, path, handler) {
18
- registerRoute(this.routes, method, path, handler);
82
+ const normalizedMethod = method.toUpperCase();
83
+ if (!SUPPORTED_METHODS.has(normalizedMethod)) {
84
+ throw new Error(`Unsupported HTTP method: ${normalizedMethod}`);
85
+ }
86
+ this.register(normalizedMethod, path, handler);
87
+ return this;
88
+ }
89
+ all(path, handler) {
90
+ this.register(ALL_METHODS, path, handler);
19
91
  return this;
20
92
  }
21
93
  fallback(handler) {
22
94
  this.fallbackHandler = handler;
23
95
  return this;
24
96
  }
97
+ match(method, pathname) {
98
+ const exact = this.routes[method]?.[pathname];
99
+ if (exact) {
100
+ return { handler: exact, params: EMPTY_PARAMS };
101
+ }
102
+ const segments = splitPath(pathname);
103
+ const dynamic = matchDynamic(this.dynamicRoutes[method], segments);
104
+ if (dynamic) {
105
+ return dynamic;
106
+ }
107
+ const allExact = this.routes[ALL_METHODS]?.[pathname];
108
+ if (allExact) {
109
+ return { handler: allExact, params: EMPTY_PARAMS };
110
+ }
111
+ const allDynamic = matchDynamic(this.dynamicRoutes[ALL_METHODS], segments);
112
+ if (allDynamic) {
113
+ return allDynamic;
114
+ }
115
+ if (this.fallbackHandler) {
116
+ return { handler: this.fallbackHandler, params: EMPTY_PARAMS };
117
+ }
118
+ return undefined;
119
+ }
120
+ register(method, path, handler) {
121
+ const { segments, mask, dynamic } = parsePattern(path);
122
+ if (dynamic) {
123
+ this.registerDynamic(method, path, segments, mask, handler);
124
+ return;
125
+ }
126
+ const routeGroup = (this.routes[method] ??= {});
127
+ if (routeGroup[path]) {
128
+ throw new Error(`${methodLabel(method)} ${path} already exists!`);
129
+ }
130
+ routeGroup[path] = handler;
131
+ }
132
+ registerDynamic(method, path, segments, mask, handler) {
133
+ const signature = signatureOf(segments, mask);
134
+ const signatures = (this.dynamicSignatures[method] ??= new Set());
135
+ if (signatures.has(signature)) {
136
+ throw new Error(`${methodLabel(method)} ${path} already exists!`);
137
+ }
138
+ signatures.add(signature);
139
+ const list = (this.dynamicRoutes[method] ??= []);
140
+ list.push({ segments, mask, handler });
141
+ list.sort(compareSpecificity);
142
+ }
25
143
  }
package/create.js CHANGED
@@ -2,6 +2,10 @@ import { Router } from './router.js';
2
2
  export const createRouter = () => {
3
3
  const instance = new Router();
4
4
  const api = {
5
+ all(path, handler) {
6
+ instance.all(path, handler);
7
+ return api;
8
+ },
5
9
  get(path, handler) {
6
10
  instance.on('GET', path, handler);
7
11
  return api;
package/http/router.d.ts CHANGED
@@ -2,7 +2,5 @@ import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { BaseRouter } from '../base.js';
3
3
  import type { Handler } from './types.js';
4
4
  export declare class Router extends BaseRouter<Handler> {
5
- private readonly allRoutes;
6
- all(path: string, handler: Handler): this;
7
5
  route(request: IncomingMessage, response: ServerResponse): Promise<void>;
8
6
  }
package/http/router.js CHANGED
@@ -1,20 +1,13 @@
1
1
  import { STATUS_CODES } from 'node:http';
2
2
  import { BaseRouter } from '../base.js';
3
3
  export class Router extends BaseRouter {
4
- allRoutes = {};
5
- all(path, handler) {
6
- if (this.allRoutes[path]) {
7
- throw new Error(`ALL ${path} already exists!`);
8
- }
9
- this.allRoutes[path] = handler;
10
- return this;
11
- }
12
4
  async route(request, response) {
13
5
  const method = (request.method ?? 'GET').toUpperCase();
14
6
  const pathname = (request.url ?? '/').split('?')[0];
15
- const handler = this.routes[method]?.[pathname] ?? this.allRoutes[pathname] ?? this.fallbackHandler;
16
- if (handler) {
17
- await handler(request, response);
7
+ const matched = this.match(method, pathname);
8
+ if (matched) {
9
+ request.params = matched.params;
10
+ await matched.handler(request, response);
18
11
  return;
19
12
  }
20
13
  response
package/http/types.d.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import type { HttpHandler } from '@vyriy/handler';
3
+ import type { RouteParams } from '../base.js';
4
+ export type { RouteParams } from '../base.js';
3
5
  export type Handler = HttpHandler;
6
+ export type RequestWithParams = IncomingMessage & {
7
+ params?: RouteParams;
8
+ };
4
9
  export type RouterApi = {
5
10
  all(path: string, handler: Handler): RouterApi;
6
11
  get(path: string, handler: Handler): RouterApi;
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@vyriy/router",
3
- "version": "0.8.3",
3
+ "version": "0.8.5",
4
4
  "description": "Router utility for Vyriy projects",
5
5
  "homepage": "https://vyriy.dev/docs/router/",
6
6
  "type": "module",
7
7
  "dependencies": {
8
8
  "@types/aws-lambda": "^8.10.162",
9
- "@vyriy/handler": "0.8.3"
9
+ "@vyriy/handler": "0.8.5"
10
10
  },
11
11
  "agents": "./AGENTS.md",
12
12
  "license": "MIT",
package/router.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { STATUS_CODES } from 'node:http';
2
- import { BaseRouter } from './base.js';
2
+ import { BaseRouter, mergeParams } from './base.js';
3
3
  const normalizeResult = (result) => ({
4
4
  statusCode: result.statusCode ?? 200,
5
5
  body: result.body,
@@ -10,27 +10,17 @@ const normalizeResult = (result) => ({
10
10
  export class Router extends BaseRouter {
11
11
  async route(event) {
12
12
  const { httpMethod, path, queryStringParameters, body, headers, pathParameters } = event;
13
- const exactHandler = this.routes[httpMethod]?.[path];
14
- if (exactHandler) {
15
- const result = await exactHandler({
13
+ const matched = this.match(httpMethod, path);
14
+ if (matched) {
15
+ const result = await matched.handler({
16
16
  query: queryStringParameters ?? undefined,
17
17
  body: body ?? undefined,
18
18
  headers,
19
- pathParameters: pathParameters ?? undefined,
19
+ pathParameters: mergeParams(pathParameters, matched.params),
20
20
  event,
21
21
  });
22
22
  return normalizeResult(result);
23
23
  }
24
- if (this.fallbackHandler) {
25
- const fallbackResult = await this.fallbackHandler({
26
- query: queryStringParameters ?? undefined,
27
- body: body ?? undefined,
28
- headers,
29
- pathParameters: pathParameters ?? undefined,
30
- event,
31
- });
32
- return normalizeResult(fallbackResult);
33
- }
34
24
  return {
35
25
  statusCode: 404,
36
26
  body: JSON.stringify({
package/stream/create.js CHANGED
@@ -2,6 +2,10 @@ import { Router } from './router.js';
2
2
  export const createRouter = () => {
3
3
  const instance = new Router();
4
4
  const api = {
5
+ all(path, handler) {
6
+ instance.all(path, handler);
7
+ return api;
8
+ },
5
9
  get(path, handler) {
6
10
  instance.on('GET', path, handler);
7
11
  return api;
package/stream/router.js CHANGED
@@ -1,25 +1,15 @@
1
1
  import { STATUS_CODES } from 'node:http';
2
- import { BaseRouter } from '../base.js';
2
+ import { BaseRouter, mergeParams } from '../base.js';
3
3
  export class Router extends BaseRouter {
4
4
  async route(event, responseStream) {
5
5
  const { httpMethod, path, queryStringParameters, body, headers, pathParameters } = event;
6
- const exactHandler = this.routes[httpMethod]?.[path];
7
- if (exactHandler) {
8
- await exactHandler({
6
+ const matched = this.match(httpMethod, path);
7
+ if (matched) {
8
+ await matched.handler({
9
9
  query: queryStringParameters ?? undefined,
10
10
  body: body ?? undefined,
11
11
  headers,
12
- pathParameters: pathParameters ?? undefined,
13
- event,
14
- }, responseStream);
15
- return;
16
- }
17
- if (this.fallbackHandler) {
18
- await this.fallbackHandler({
19
- query: queryStringParameters ?? undefined,
20
- body: body ?? undefined,
21
- headers,
22
- pathParameters: pathParameters ?? undefined,
12
+ pathParameters: mergeParams(pathParameters, matched.params),
23
13
  event,
24
14
  }, responseStream);
25
15
  return;
package/stream/types.d.ts CHANGED
@@ -13,6 +13,7 @@ export type ResponseStream = {
13
13
  export type Handler = (params: HandlerParams, responseStream: ResponseStream) => MaybePromise<void>;
14
14
  export type RouterHandler = (event: APIGatewayProxyEvent, responseStream: ResponseStream) => Promise<void>;
15
15
  export type RouterApi = {
16
+ all(path: string, handler: Handler): RouterApi;
16
17
  get(path: string, handler: Handler): RouterApi;
17
18
  handle(): RouterHandler;
18
19
  post(path: string, handler: Handler): RouterApi;
package/types.d.ts CHANGED
@@ -19,6 +19,7 @@ export type HandlerParams = {
19
19
  export type Handler = (params: HandlerParams) => MaybePromise<RouteHandlerResult>;
20
20
  export type RouterHandler = (event: APIGatewayProxyEvent) => Promise<RouteResult>;
21
21
  export type RouterApi = {
22
+ all(path: string, handler: Handler): RouterApi;
22
23
  get(path: string, handler: Handler): RouterApi;
23
24
  handle(): RouterHandler;
24
25
  post(path: string, handler: Handler): RouterApi;