@aura-stack/router 0.3.0 → 0.5.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 (44) hide show
  1. package/README.md +2 -2
  2. package/dist/assert.cjs +17 -0
  3. package/dist/assert.d.ts +12 -2
  4. package/dist/assert.js +6 -2
  5. package/dist/{chunk-6PZEXNTS.js → chunk-4UYDR5IO.js} +2 -2
  6. package/dist/{chunk-GJC3ODME.js → chunk-B6PMGVSL.js} +9 -1
  7. package/dist/{chunk-FWDOXDWG.js → chunk-BWIKAYZV.js} +9 -9
  8. package/dist/{chunk-JNMXLKDG.js → chunk-FU35BPU7.js} +11 -2
  9. package/dist/{chunk-JIA6NLL6.js → chunk-TEDN6QMU.js} +39 -19
  10. package/dist/{chunk-PT4GU6PH.js → chunk-XB5P5CQZ.js} +22 -9
  11. package/dist/chunk-Z6JJAIWN.js +37 -0
  12. package/dist/context.cjs +27 -8
  13. package/dist/context.d.ts +12 -20
  14. package/dist/context.js +5 -5
  15. package/dist/cookie.cjs +24 -0
  16. package/dist/cookie.d.ts +1 -0
  17. package/dist/cookie.js +2 -0
  18. package/dist/endpoint.d.ts +2 -0
  19. package/dist/endpoint.js +3 -3
  20. package/dist/error.cjs +9 -0
  21. package/dist/error.d.ts +7 -1
  22. package/dist/error.js +3 -1
  23. package/dist/headers.cjs +61 -0
  24. package/dist/headers.d.ts +20 -0
  25. package/dist/headers.js +6 -0
  26. package/dist/index.cjs +105 -28
  27. package/dist/index.d.ts +4 -2
  28. package/dist/index.js +14 -8
  29. package/dist/middlewares.cjs +8 -8
  30. package/dist/middlewares.d.ts +5 -3
  31. package/dist/middlewares.js +2 -2
  32. package/dist/router.cjs +101 -28
  33. package/dist/router.d.ts +2 -0
  34. package/dist/router.js +6 -5
  35. package/dist/types.d.ts +29 -6
  36. package/package.json +39 -13
  37. package/dist/assert.d.cts +0 -52
  38. package/dist/context.d.cts +0 -85
  39. package/dist/endpoint.d.cts +0 -60
  40. package/dist/error.d.cts +0 -65
  41. package/dist/index.d.cts +0 -6
  42. package/dist/middlewares.d.cts +0 -23
  43. package/dist/router.d.cts +0 -37
  44. package/dist/types.d.cts +0 -191
package/dist/index.d.cts DELETED
@@ -1,6 +0,0 @@
1
- export { createEndpoint, createEndpointConfig } from './endpoint.cjs';
2
- export { createRouter } from './router.cjs';
3
- export { isRouterError } from './assert.cjs';
4
- export { RouterError, statusCode, statusText } from './error.cjs';
5
- export { ContentType, ContextBody, ContextParams, ContextSearchParams, EndpointConfig, EndpointSchemas, GetHttpHandlers, GetRouteParams, GlobalMiddleware, HTTPMethod, InferMethod, MiddlewareFunction, Prettify, RequestContext, RouteEndpoint, RouteHandler, RoutePattern, RouterConfig } from './types.cjs';
6
- import 'zod';
@@ -1,23 +0,0 @@
1
- import { RouterConfig, EndpointConfig, RequestContext, MiddlewareFunction } from './types.cjs';
2
- import 'zod';
3
- import './error.cjs';
4
-
5
- /**
6
- * Executes the middlewares in sequence, passing the request to each middleware.
7
- *
8
- * @param request - Original request made from the client
9
- * @param middlewares - Array of global middleware functions to be executed
10
- * @returns - The modified request after all middlewares have been executed
11
- */
12
- declare const executeGlobalMiddlewares: (request: Request, middlewares: RouterConfig["middlewares"]) => Promise<Request | Response>;
13
- /**
14
- * Executes middlewares in sequence, passing the request and context to each middleware.
15
- *
16
- * @param request - Original request made from the client
17
- * @param context - Context object of the endpoint functionality
18
- * @param middlewares - Array of middleware functions to be executed
19
- * @returns The modified context after all middlewares have been executed
20
- */
21
- declare const executeMiddlewares: <const RouteParams extends Record<string, string>, const Config extends EndpointConfig>(request: Request, context: RequestContext<RouteParams, Config>, middlewares?: MiddlewareFunction<RouteParams, Config>[]) => Promise<RequestContext<RouteParams, Config>>;
22
-
23
- export { executeGlobalMiddlewares, executeMiddlewares };
package/dist/router.d.cts DELETED
@@ -1,37 +0,0 @@
1
- import { RouteEndpoint, RouterConfig, GetHttpHandlers, HTTPMethod, RoutePattern, EndpointSchemas, MiddlewareFunction } from './types.cjs';
2
- import 'zod';
3
- import './error.cjs';
4
-
5
- interface TrieNode {
6
- statics: Map<string, TrieNode>;
7
- param?: {
8
- name: string;
9
- node: TrieNode;
10
- };
11
- endpoints: Map<HTTPMethod, RouteEndpoint>;
12
- }
13
- declare const createNode: () => TrieNode;
14
- declare const insert: (root: TrieNode, endpoint: RouteEndpoint) => void;
15
- declare const search: (method: HTTPMethod, root: TrieNode, pathname: string) => {
16
- endpoint: RouteEndpoint<HTTPMethod, RoutePattern, {
17
- schemas?: EndpointSchemas | undefined;
18
- middlewares?: MiddlewareFunction<{} | {
19
- [x: string]: string;
20
- }, {
21
- schemas: EndpointSchemas;
22
- }>[] | undefined;
23
- }>;
24
- params: Record<string, string>;
25
- };
26
- /**
27
- * Creates the entry point for the server, handling the endpoints defined in the router.
28
- * It groups endpoints by HTTP method and matches incoming requests to the appropriate endpoint.
29
- * It accepts an optional configuration object to set a base path and middlewares for all endpoints.
30
- *
31
- * @param endpoints - Array of route endpoints to be handled by the router
32
- * @param config - Optional configuration object for the router
33
- * @returns An object with methods corresponding to HTTP methods, each handling requests for that method
34
- */
35
- declare const createRouter: <const Endpoints extends RouteEndpoint[]>(endpoints: Endpoints, config?: RouterConfig) => GetHttpHandlers<Endpoints>;
36
-
37
- export { createNode, createRouter, insert, search };
package/dist/types.d.cts DELETED
@@ -1,191 +0,0 @@
1
- import { ZodObject, z } from 'zod';
2
- import { RouterError } from './error.cjs';
3
-
4
- /**
5
- * Route pattern must start with a slash and can contain parameters prefixed with a colon.
6
- * @example
7
- * const getUser:RoutePattern = "/users/:userId"
8
- * const getPostsComments:RoutePattern = "/posts/:postId/comments/:commentId"
9
- */
10
- type RoutePattern = `/${string}` | `/${string}/:${string}`;
11
- /**
12
- * HTTP methods defined in HTTP/1.1 specification.
13
- * @see https://datatracker.ietf.org/doc/html/rfc7231#section-4.3
14
- */
15
- type HTTPMethod = "GET" | "POST" | "DELETE" | "PUT" | "PATCH" | "OPTIONS" | "HEAD" | "TRACE" | "CONNECT";
16
- /**
17
- * Content types supported by the router.
18
- */
19
- type ContentType = "application/json" | "application/x-www-form-urlencoded" | "text/plain" | "multipart/form-data" | "application/xml" | "application/octet-stream" | `text/${string}` | `image/${string}` | `video/${string}` | `audio/${string}` | "application/pdf";
20
- type Prettify<Obj extends object> = {
21
- [Key in keyof Obj]: Obj[Key];
22
- } & {};
23
- /**
24
- * Extracts route parameters from a given route pattern through colon-prefixed segments.
25
- * Returns an object type where keys are parameter names and values are strings.
26
- * If no parameters are found, returns an empty object type.
27
- *
28
- * @example
29
- * // Expected: { userId: string }
30
- * type UserParams = Params<"/users/:userId">;
31
- *
32
- * // Expected: { postId: string; commentId: string }
33
- * type PostCommentParams = Params<"/posts/:postId/comments/:commentId">;
34
- *
35
- * // Expected: {}
36
- * type NoParams = Params<"/about">;
37
- */
38
- type GetRouteParams<Route extends RoutePattern> = Route extends `/${string}/:${infer Param}/${infer Str}` ? Prettify<{
39
- [K in Param]: string;
40
- } & GetRouteParams<`/${Str}`>> : Route extends `/${string}/:${infer Param}` ? Prettify<{
41
- [K in Param]: string;
42
- }> : Route extends `/:${infer Param}` ? Prettify<{
43
- [K in Param]: string;
44
- }> : {};
45
- /**
46
- * Available schemas validation for an endpoint. It can include body and searchParams schemas.
47
- */
48
- interface EndpointSchemas {
49
- body?: ZodObject<any>;
50
- searchParams?: ZodObject<any>;
51
- params?: ZodObject<any>;
52
- }
53
- /**
54
- * Configuration for an endpoint, including optional schemas for request validation and middlewares.
55
- */
56
- type EndpointConfig<RouteParams extends RoutePattern = RoutePattern, Schemas extends EndpointSchemas = EndpointSchemas> = Prettify<{
57
- schemas?: Schemas;
58
- middlewares?: MiddlewareFunction<GetRouteParams<RouteParams>, {
59
- schemas: Schemas;
60
- }>[];
61
- }>;
62
- /**
63
- * Infer the type of search parameters from the provided value in the `EndpointConfig`.
64
- */
65
- type ContextSearchParams<Schemas extends EndpointConfig["schemas"]> = Schemas extends {
66
- searchParams: ZodObject;
67
- } ? {
68
- searchParams: z.infer<Schemas["searchParams"]>;
69
- } : {
70
- searchParams: URLSearchParams;
71
- };
72
- /**
73
- * Infer the type of body from the provided value in the `EndpointConfig`.
74
- */
75
- type ContextBody<Schemas extends EndpointConfig["schemas"]> = Schemas extends {
76
- body: ZodObject;
77
- } ? {
78
- body: z.infer<Schemas["body"]>;
79
- } : {
80
- body: undefined;
81
- };
82
- /**
83
- * Infer the type of route parameters from the provided value in the `EndpointConfig`.
84
- */
85
- type ContextParams<Schemas extends EndpointConfig["schemas"], Default = Record<string, string>> = Schemas extends {
86
- params: ZodObject;
87
- } ? {
88
- params: z.infer<Schemas["params"]>;
89
- } : {
90
- params: Default;
91
- };
92
- /**
93
- * Context object passed to route handlers and middlewares defined in the
94
- * `createEndpoint/createEndpointConfig` function or globally in the `createRouter` function.
95
- */
96
- interface RequestContext<RouteParams = Record<string, string>, Config extends EndpointConfig = EndpointConfig> {
97
- params: ContextParams<Config["schemas"], RouteParams>["params"];
98
- headers: Headers;
99
- body: ContextBody<Config["schemas"]>["body"];
100
- searchParams: ContextSearchParams<Config["schemas"]>["searchParams"];
101
- }
102
- /**
103
- * Global middleware function type that represent a function that runs before the route matching.
104
- */
105
- type GlobalMiddleware = (request: Request) => Promise<Request | Response>;
106
- /**
107
- * Middleware function type that represent a function that runs before the route handler
108
- * defined in the `createEndpoint/createEndpointConfig` function or globally in the `createRouter` function.
109
- */
110
- type MiddlewareFunction<RouteParams = Record<string, string>, Config extends EndpointConfig = EndpointConfig> = (request: Request, ctx: Prettify<RequestContext<RouteParams, Config>>) => Promise<RequestContext<RouteParams, Config>>;
111
- /**
112
- * Defines a route handler function that processes an incoming request and returns a response.
113
- * The handler receives the request object and a context containing route parameters, headers,
114
- * and optionally validated body and search parameters based on the endpoint configuration.
115
- */
116
- type RouteHandler<Route extends RoutePattern, Config extends EndpointConfig> = (request: Request, ctx: Prettify<RequestContext<GetRouteParams<Route>, Config>>) => Response | Promise<Response>;
117
- /**
118
- * Represents a route endpoint definition, specifying the HTTP method, route pattern,
119
- * handler function with inferred context types, and associated configuration.
120
- */
121
- interface RouteEndpoint<Method extends HTTPMethod = HTTPMethod, Route extends RoutePattern = RoutePattern, Config extends EndpointConfig = EndpointConfig> {
122
- method: Method;
123
- route: Route;
124
- handler: RouteHandler<Route, Config>;
125
- config: Config;
126
- }
127
- /**
128
- * Infer the HTTP methods defined in the provided array of route endpoints.
129
- */
130
- type InferMethod<Endpoints extends RouteEndpoint[]> = Endpoints extends unknown[] ? Endpoints[number]["method"] : "unknown";
131
- /**
132
- * Generates an object with HTTP methods available by the router from `createRouter` function.
133
- * Each method is a function that takes a request and context, returning a promise of a response.
134
- */
135
- type GetHttpHandlers<Endpoints extends RouteEndpoint[]> = {
136
- [Method in InferMethod<Endpoints>]: (req: Request) => Response | Promise<Response>;
137
- };
138
- /**
139
- * Configuration options for `createRouter` function.
140
- */
141
- interface RouterConfig {
142
- /**
143
- * Prefix path for all routes/endpoints defined in the router.
144
- *
145
- * @example
146
- * basePath: "/api/v1"
147
- *
148
- * // will match the "/users" endpoint.
149
- * new Request("https://example.com/api/v1/users")
150
- *
151
- * // will NOT match the "/users" endpoint.
152
- * new Request("https://example.com/users")
153
- */
154
- basePath?: RoutePattern;
155
- /**
156
- * Global middlewares that run before route matching for all endpoints in the router.
157
- * You can use this to modify the request or return a response early.
158
- *
159
- * @example
160
- * middlewares: [
161
- * async (request) => {
162
- * if(request.headers.get("Authorization")?.startsWith("Bearer ")) {
163
- * return Response.json({ message: "Unauthorized" }, { status: 401 })
164
- * }
165
- * return request
166
- * }
167
- * ]
168
- */
169
- middlewares?: GlobalMiddleware[];
170
- /**
171
- * Error handler function that runs when an error is thrown in a router handler or middleware.
172
- * It can be used to customize the default error response provided by the router. If is an internal
173
- * error the error is from the `RouterError` class, otherwise the error is a generic
174
- * `Error` instance which was caused by a handler or middleware, for how to distinguish them you can use
175
- * the `isRouterError` function from the `assert` module.
176
- *
177
- * @param error - The error thrown in the router
178
- * @param request - The original request that caused the error
179
- * @returns A response to be sent back to the client
180
- * @example
181
- * onError: (error, request) => {
182
- * if(isRouterError(error)) {
183
- * return Response.json({ message: error.message }, { status: error.statusCode })
184
- * }
185
- * return Response.json({ message: "Internal Server Error" }, { status: 500 })
186
- * }
187
- */
188
- onError?: (error: Error | RouterError, request: Request) => Response | Promise<Response>;
189
- }
190
-
191
- export type { ContentType, ContextBody, ContextParams, ContextSearchParams, EndpointConfig, EndpointSchemas, GetHttpHandlers, GetRouteParams, GlobalMiddleware, HTTPMethod, InferMethod, MiddlewareFunction, Prettify, RequestContext, RouteEndpoint, RouteHandler, RoutePattern, RouterConfig };