@vyriy/router 0.2.0 → 0.3.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.
package/AGENTS.md ADDED
@@ -0,0 +1,65 @@
1
+ # Vyriy Package Agent Guide
2
+
3
+ This package belongs to the Vyriy toolkit. Keep changes calm, explicit, reusable, and easy to reason about.
4
+
5
+ ## Architecture
6
+
7
+ - Prefer simple modules over clever frameworks or hidden conventions.
8
+ - Keep package boundaries explicit and avoid project-specific coupling.
9
+ - Extract only proven reusable behavior.
10
+ - Keep public APIs small, typed, documented, and stable.
11
+ - Prefer SSR-friendly and SSG-friendly code paths.
12
+ - Keep integrations replaceable and avoid hard coupling to a CMS or runtime host.
13
+ - Prefer AWS serverless-compatible assumptions when infrastructure concerns appear.
14
+
15
+ ## File Shape
16
+
17
+ - Prefer one exported runtime method, component, or helper per production file when it stays readable.
18
+ - Prefer one matching test file per production file, for example `feature.ts` and `feature.test.ts`.
19
+ - Use focused folders when behavior naturally splits into several related files.
20
+ - Keep `index.ts` as a public re-export surface only. Do not place implementation logic in it.
21
+ - Use `.js` relative import and export specifiers in TypeScript source where package style requires it.
22
+ - Add `types.ts` when public shared types are part of the package contract.
23
+ - Keep constants near the code that owns them unless they are shared or clarify repeated behavior.
24
+
25
+ ## Public Surface
26
+
27
+ - Every new public export should be re-exported from `index.ts`.
28
+ - Add or update `index.test.ts` when the public export surface changes.
29
+ - Add JSDoc for public exports when behavior, parameters, return values, or usage expectations need explanation.
30
+ - Do not hand-maintain source package `exports` maps unless the package has a real custom publishing need.
31
+
32
+ ## Tests
33
+
34
+ - Tests use Jest and `@jest/globals`.
35
+ - Cover public behavior and meaningful edge cases.
36
+ - Prefer behavior-focused tests over private implementation lock-in.
37
+ - When mocking modules, install mocks before loading the module under test.
38
+ - Use focused validation when changing package behavior:
39
+
40
+ ```bash
41
+ yarn jest packages/<package> --runInBand --coverage=false
42
+ ```
43
+
44
+ ## Documentation
45
+
46
+ - Keep `README.md` concise and usage-oriented.
47
+ - Start package READMEs with `# @vyriy/<package>`.
48
+ - Document real public exports, supported options, and examples that actually work.
49
+ - Keep `doc.mdx` as the Storybook/docs wrapper for the README when the package participates in docs.
50
+ - For component packages, include Storybook coverage for supported states and common usage.
51
+
52
+ ## Components
53
+
54
+ - Prefer lightweight React 19+ components with TypeScript.
55
+ - Keep components SSR-friendly and avoid browser globals during render.
56
+ - Prefer composable props and Bootstrap-compatible ergonomics where practical.
57
+ - Put each public component in its own file with a matching test.
58
+ - Add Storybook stories when a component has visual states, variants, or interaction states.
59
+
60
+ ## Change Discipline
61
+
62
+ - Keep changes scoped to the requested behavior.
63
+ - Avoid unrelated refactors and metadata churn.
64
+ - Sync implementation, tests, README, `doc.mdx`, and public re-exports together.
65
+ - Prefer the option that is simpler to explain, easier to evolve, and calmer to maintain.
package/README.md CHANGED
@@ -9,6 +9,7 @@ This package provides a small API Gateway router for Lambda handlers.
9
9
  It is intentionally kept small:
10
10
 
11
11
  - matches by HTTP method and exact path
12
+ - supports simple prefix dispatch for handler factories such as static file serving
12
13
  - passes API Gateway event data into handlers
13
14
  - returns a Lambda-friendly response shape
14
15
 
@@ -32,6 +33,7 @@ yarn add @vyriy/router
32
33
 
33
34
  ```ts
34
35
  import { createRouter } from '@vyriy/router';
36
+ import { staticFiles } from '@vyriy/server/static';
35
37
 
36
38
  const router = createRouter();
37
39
 
@@ -46,6 +48,26 @@ router.get('/health', async ({ event, query, headers, pathParameters, body }) =>
46
48
  body,
47
49
  }),
48
50
  }));
51
+
52
+ router.prefix('/static', staticFiles('./public'));
53
+
54
+ router.fallback(async ({ event }) => ({
55
+ statusCode: 404,
56
+ body: JSON.stringify({
57
+ message: 'Not Found',
58
+ path: event.path,
59
+ }),
60
+ }));
61
+ ```
62
+
63
+ Prefix handlers receive the relative matched path in `pathParameters.proxy`, so they can behave like normal handlers:
64
+
65
+ ```ts
66
+ router.prefix('/events', async ({ pathParameters, responseStream }) => {
67
+ responseStream?.setContentType?.('text/plain');
68
+ responseStream?.write(`Path: ${pathParameters?.proxy}`);
69
+ responseStream?.end();
70
+ });
49
71
  ```
50
72
 
51
73
  ## Exports
@@ -65,11 +87,15 @@ import { Router } from '@vyriy/router/router';
65
87
  - `router.put(path, handler)` registers a `PUT` handler.
66
88
  - `router.delete(path, handler)` registers a `DELETE` handler.
67
89
  - `router.patch(path, handler)` registers a `PATCH` handler.
90
+ - `router.prefix(pathPrefix, handler)` registers a handler for every request under a URL prefix.
91
+ - `router.fallback(handler)` registers a handler for unmatched requests.
68
92
  - `router.route(event)` resolves the matching route and returns an API Gateway response.
69
93
 
70
94
  The low-level `Router` class is also available from `@vyriy/router/router` and exposes only:
71
95
 
72
96
  - `router.on(method, path, handler)`
97
+ - `router.prefix(pathPrefix, handler)`
98
+ - `router.fallback(handler)`
73
99
  - `router.route(event)`
74
100
 
75
101
  Route handlers receive:
@@ -80,6 +106,7 @@ type HandlerParams = {
80
106
  body?: string;
81
107
  headers?: APIGatewayProxyEvent['headers'];
82
108
  pathParameters?: APIGatewayProxyEvent['pathParameters'];
109
+ responseStream?: ResponseStream;
83
110
  event: APIGatewayProxyEvent;
84
111
  };
85
112
  ```
package/create.js CHANGED
@@ -18,10 +18,18 @@ export const createRouter = () => {
18
18
  router.on('DELETE', path, handler);
19
19
  return api;
20
20
  },
21
+ fallback(handler) {
22
+ router.fallback(handler);
23
+ return api;
24
+ },
21
25
  patch(path, handler) {
22
26
  router.on('PATCH', path, handler);
23
27
  return api;
24
28
  },
29
+ prefix(pathPrefix, handler) {
30
+ router.prefix(pathPrefix, handler);
31
+ return api;
32
+ },
25
33
  route(event) {
26
34
  return router.route(event);
27
35
  },
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@vyriy/router",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Router utility for Vyriy projects",
5
5
  "type": "module",
6
6
  "main": "./index.js",
7
7
  "dependencies": {
8
8
  "@types/aws-lambda": "^8.10.161"
9
9
  },
10
+ "agents": "./AGENTS.md",
10
11
  "license": "MIT",
11
12
  "repository": {
12
13
  "type": "git",
package/router.d.ts CHANGED
@@ -1,6 +1,10 @@
1
- import type { APIGatewayProxyEvent, APIGatewayProxyResult, Handler } from './types.js';
1
+ import type { APIGatewayProxyEvent, Handler, ResponseStream, RouteResult } from './types.js';
2
2
  export declare class Router {
3
+ private fallbackHandler?;
3
4
  private readonly routes;
5
+ private readonly staticRoutes;
4
6
  on(method: string, path: string, handler: Handler): this;
5
- route(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult>;
7
+ fallback(handler: Handler): this;
8
+ prefix(pathPrefix: string, handler: Handler): this;
9
+ route(event: APIGatewayProxyEvent, responseStream?: ResponseStream): Promise<RouteResult | void>;
6
10
  }
package/router.js CHANGED
@@ -1,7 +1,36 @@
1
1
  import { METHODS, STATUS_CODES } from 'node:http';
2
2
  const SUPPORTED_METHODS = new Set(METHODS.map((method) => method.toUpperCase()));
3
+ const removeLeadingSlashes = (value) => {
4
+ let start = 0;
5
+ while (value[start] === '/') {
6
+ start += 1;
7
+ }
8
+ return value.slice(start);
9
+ };
10
+ const removeTrailingSlashes = (value) => {
11
+ let end = value.length;
12
+ while (end > 0 && value[end - 1] === '/') {
13
+ end -= 1;
14
+ }
15
+ return value.slice(0, end);
16
+ };
17
+ const getPrefixPath = (eventPath, route) => {
18
+ if (eventPath !== route.pathPrefix && !eventPath.startsWith(`${route.pathPrefix}/`)) {
19
+ return undefined;
20
+ }
21
+ return decodeURIComponent(removeLeadingSlashes(eventPath.slice(route.pathPrefix.length)));
22
+ };
23
+ const normalizeResult = (result) => ({
24
+ statusCode: result.statusCode ?? 200,
25
+ body: result.body,
26
+ headers: result.headers,
27
+ isBase64Encoded: result.isBase64Encoded,
28
+ multiValueHeaders: result.multiValueHeaders,
29
+ });
3
30
  export class Router {
31
+ fallbackHandler;
4
32
  routes = {};
33
+ staticRoutes = [];
5
34
  on(method, path, handler) {
6
35
  const normalizedMethod = method.toUpperCase();
7
36
  if (!SUPPORTED_METHODS.has(normalizedMethod)) {
@@ -14,26 +43,67 @@ export class Router {
14
43
  routeGroup[path] = handler;
15
44
  return this;
16
45
  }
17
- async route(event) {
18
- const { httpMethod, path, queryStringParameters, body, headers, pathParameters } = event;
19
- const result = await this.routes[httpMethod]?.[path]?.({
20
- query: queryStringParameters ?? undefined,
21
- body: body ?? undefined,
22
- headers,
23
- pathParameters: pathParameters ?? undefined,
24
- event,
46
+ fallback(handler) {
47
+ this.fallbackHandler = handler;
48
+ return this;
49
+ }
50
+ prefix(pathPrefix, handler) {
51
+ this.staticRoutes.push({
52
+ handler,
53
+ pathPrefix: removeTrailingSlashes(pathPrefix) || '/',
25
54
  });
26
- return result
27
- ? {
28
- statusCode: result.statusCode ?? 200,
29
- body: result.body,
30
- headers: result.headers,
55
+ return this;
56
+ }
57
+ async route(event, responseStream) {
58
+ const { httpMethod, path, queryStringParameters, body, headers, pathParameters } = event;
59
+ const exactHandler = this.routes[httpMethod]?.[path];
60
+ if (exactHandler) {
61
+ const result = await exactHandler({
62
+ query: queryStringParameters ?? undefined,
63
+ body: body ?? undefined,
64
+ headers,
65
+ pathParameters: pathParameters ?? undefined,
66
+ responseStream,
67
+ event,
68
+ });
69
+ return result ? normalizeResult(result) : undefined;
70
+ }
71
+ for (const staticRoute of this.staticRoutes) {
72
+ const proxy = getPrefixPath(path, staticRoute);
73
+ if (proxy !== undefined) {
74
+ const prefixResult = await staticRoute.handler({
75
+ query: queryStringParameters ?? undefined,
76
+ body: body ?? undefined,
77
+ headers,
78
+ pathParameters: {
79
+ ...pathParameters,
80
+ proxy,
81
+ },
82
+ responseStream,
83
+ event,
84
+ });
85
+ if (prefixResult) {
86
+ return normalizeResult(prefixResult);
87
+ }
88
+ return undefined;
31
89
  }
32
- : {
33
- statusCode: 404,
34
- body: JSON.stringify({
35
- message: STATUS_CODES[404],
36
- }),
37
- };
90
+ }
91
+ if (this.fallbackHandler) {
92
+ const fallbackResult = await this.fallbackHandler({
93
+ query: queryStringParameters ?? undefined,
94
+ body: body ?? undefined,
95
+ headers,
96
+ pathParameters: pathParameters ?? undefined,
97
+ responseStream,
98
+ event,
99
+ });
100
+ return fallbackResult ? normalizeResult(fallbackResult) : undefined;
101
+ }
102
+ return {
103
+ statusCode: 404,
104
+ body: JSON.stringify({
105
+ message: STATUS_CODES[404],
106
+ }),
107
+ };
38
108
  }
39
109
  }
package/types.d.ts CHANGED
@@ -1,23 +1,37 @@
1
1
  import type { APIGatewayProxyEvent, APIGatewayProxyEventQueryStringParameters, APIGatewayProxyResult } from 'aws-lambda';
2
2
  export type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
3
- export type Result = {
3
+ export type RouteResult = {
4
4
  body: APIGatewayProxyResult['body'];
5
5
  headers?: APIGatewayProxyResult['headers'];
6
+ isBase64Encoded?: APIGatewayProxyResult['isBase64Encoded'];
7
+ multiValueHeaders?: APIGatewayProxyResult['multiValueHeaders'];
6
8
  statusCode?: APIGatewayProxyResult['statusCode'];
7
9
  };
10
+ export type ResponseStream = {
11
+ end: {
12
+ (): unknown;
13
+ (chunk: string | Buffer | Uint8Array): unknown;
14
+ };
15
+ setContentType?: (contentType: string) => unknown;
16
+ writableEnded?: boolean;
17
+ write(chunk: string | Buffer | Uint8Array): unknown;
18
+ };
8
19
  export type HandlerParams = {
9
20
  query?: APIGatewayProxyEventQueryStringParameters;
10
21
  body?: string;
11
22
  headers?: APIGatewayProxyEvent['headers'];
12
23
  pathParameters?: APIGatewayProxyEvent['pathParameters'];
24
+ responseStream?: ResponseStream;
13
25
  event: APIGatewayProxyEvent;
14
26
  };
15
- export type Handler = (params: HandlerParams) => Promise<Result | undefined>;
27
+ export type Handler = (params: HandlerParams) => Promise<RouteResult | void>;
16
28
  export type RouterApi = {
17
29
  get(path: string, handler: Handler): RouterApi;
18
30
  post(path: string, handler: Handler): RouterApi;
19
31
  put(path: string, handler: Handler): RouterApi;
20
32
  delete(path: string, handler: Handler): RouterApi;
33
+ fallback(handler: Handler): RouterApi;
21
34
  patch(path: string, handler: Handler): RouterApi;
22
- route(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult>;
35
+ prefix(pathPrefix: string, handler: Handler): RouterApi;
36
+ route(event: APIGatewayProxyEvent, responseStream?: ResponseStream): Promise<RouteResult | void>;
23
37
  };