@aura-stack/router 0.1.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.
Files changed (43) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +17 -114
  3. package/dist/assert.cjs +64 -6
  4. package/dist/assert.d.cts +21 -1
  5. package/dist/assert.d.ts +21 -1
  6. package/dist/assert.js +8 -3
  7. package/dist/chunk-6PZEXNTS.js +31 -0
  8. package/dist/{chunk-RVJ2F7OL.js → chunk-FWDOXDWG.js} +7 -7
  9. package/dist/{chunk-RFYOPPMW.js → chunk-GJC3ODME.js} +15 -6
  10. package/dist/chunk-JIA6NLL6.js +143 -0
  11. package/dist/chunk-JNMXLKDG.js +33 -0
  12. package/dist/chunk-PT4GU6PH.js +78 -0
  13. package/dist/context.cjs +50 -47
  14. package/dist/context.d.cts +3 -2
  15. package/dist/context.d.ts +3 -2
  16. package/dist/context.js +3 -4
  17. package/dist/endpoint.cjs +29 -29
  18. package/dist/endpoint.d.cts +18 -17
  19. package/dist/endpoint.d.ts +18 -17
  20. package/dist/endpoint.js +5 -7
  21. package/dist/error.cjs +19 -7
  22. package/dist/error.d.cts +28 -3
  23. package/dist/error.d.ts +28 -3
  24. package/dist/error.js +9 -3
  25. package/dist/index.cjs +195 -116
  26. package/dist/index.d.cts +3 -1
  27. package/dist/index.d.ts +3 -1
  28. package/dist/index.js +19 -9
  29. package/dist/{middleware.cjs → middlewares.cjs} +20 -14
  30. package/dist/{middleware.d.cts → middlewares.d.cts} +1 -0
  31. package/dist/{middleware.d.ts → middlewares.d.ts} +1 -0
  32. package/dist/{middleware.js → middlewares.js} +2 -2
  33. package/dist/router.cjs +182 -103
  34. package/dist/router.d.cts +24 -2
  35. package/dist/router.d.ts +24 -2
  36. package/dist/router.js +13 -8
  37. package/dist/types.d.cts +68 -11
  38. package/dist/types.d.ts +68 -11
  39. package/package.json +10 -2
  40. package/dist/chunk-6UBPSXKR.js +0 -36
  41. package/dist/chunk-ENOBC3XN.js +0 -23
  42. package/dist/chunk-NNCUFWPI.js +0 -78
  43. package/dist/chunk-VBI7H3AK.js +0 -75
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Aura Stack
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Aura Stack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,128 +1,31 @@
1
1
  # `@aura-stack/router`
2
2
 
3
- A modern, **TypeScript-first** router and endpoint definition library for Node.js.
4
- Build fully-typed APIs with declarative endpoints, automatic parameter inference, and first-class middleware support — all returning native `Response` objects for seamless compatibility with the Fetch API.
3
+ <div align="center">
5
4
 
6
- ## Table of Contents
5
+ **A modern, TypeScript-first router and endpoint definition library**
7
6
 
8
- - [Features](#features)
9
- - [Installation](#installation)
10
- - [Quick Start](#quick-start)
11
- - [Defining Endpoints](#defining-endpoints)
12
- - [Validation & Middlewares](#validation--middlewares)
13
- - [API Reference](#api-reference)
7
+ Build fully-typed APIs with declarative endpoints, automatic parameter inference, and first-class middleware support — all returning native `Response` objects.
14
8
 
15
- ## Features
9
+ [![npm version](https://img.shields.io/npm/v/@aura-stack/router.svg)](https://www.npmjs.com/package/@aura-stack/router)
10
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
11
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
16
12
 
17
- - `Type-safe routing` only configured HTTP methods are available at compile time.
18
- - `Declarative API` — define endpoints using `createEndpoint` and group them with `createRouter`.
19
- - `Typed params & queries` — automatic inference of path (`/users/:id`) and search parameters.
20
- - `Schema validation` — built-in support for `zod` to validate request bodies, queries, or params.
21
- - `Middleware chaining` — supports global and per-endpoint middleware execution, with short-circuit control.
13
+ [Documentation](https://aura-stack-router.vercel.app) · [Quick Start](https://aura-stack-router.vercel.app/docs)
22
14
 
23
- ## Installation
15
+ </div>
24
16
 
25
- ```bash
26
- pnpm add @aura-stack/router
27
- # or
28
- npm install @aura-stack/router
29
- # or
30
- yarn add @aura-stack/router
31
- ```
17
+ ---
32
18
 
33
- ## Quick Start
19
+ ## Documentation
34
20
 
35
- ```ts
36
- import { createEndpoint, createRouter } from "@aura-stack/router"
21
+ Visit our [**documentation website**](https://aura-stack-router.vercel.app) for comprehensive guides, examples, and API references.
37
22
 
38
- const session = createEndpoint("GET", "/auth/session", async (_, ctx) => {
39
- return Response.json(
40
- {
41
- session: {
42
- userId: "uuid",
43
- username: "John",
44
- },
45
- },
46
- { headers: ctx.headers }
47
- )
48
- })
23
+ ## License
49
24
 
50
- const { GET } = createRouter([session])
51
- ```
25
+ This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
52
26
 
53
- ## Defining Endpoints
27
+ ---
54
28
 
55
- ```ts
56
- import { z } from "zod"
57
- import { createEndpoint, createEndpointConfig } from "@aura-stack/router"
58
-
59
- const credentialsConfig = createEndpointConfig({
60
- schemas: {
61
- body: z.object({
62
- username: z.string(),
63
- password: z.string(),
64
- }),
65
- },
66
- })
67
-
68
- export const signIn = createEndpoint(
69
- "POST",
70
- "/auth/credentials",
71
- async (request, ctx) => {
72
- const { body, headers } = ctx
73
- headers.set("x-login", "success")
74
- return Response.json({ status: "ok", body }, { headers })
75
- },
76
- credentialsConfig
77
- )
78
- ```
79
-
80
- ## Validation & Middlewares
81
-
82
- **Validation.** Provide Zod schemas in `createEndpointConfig`:
83
-
84
- ```ts
85
- import { createEndpoint, createEndpointConfig } from "@aura-stack/router"
86
-
87
- const config = createEndpointConfig({
88
- schemas: {
89
- searchParams: z.object({
90
- redirect_uri: z.string(),
91
- }),
92
- },
93
- })
94
-
95
- const oauth = createEndpoint(
96
- "GET",
97
- "/auth/signin/:provider",
98
- async (_req, ctx) => {
99
- const { provider } = ctx.params
100
- const { redirect_uri } = ctx.searchParams
101
- return Response.json({ provider, redirect_uri }, { status: 302 })
102
- },
103
- config
104
- )
105
- ```
106
-
107
- If validation fails, the helper throws an informative error before your handler executes.
108
-
109
- **Middlewares.** Provide async middleware functions to read or modify the request.
110
-
111
- ```ts
112
- import { createRouter, type GlobalMiddleware } from "@aura-stack/router"
113
-
114
- const audit: GlobalMiddleware = async (request) => {
115
- request.headers.set("x-request-id", crypto.randomUUID())
116
- return request
117
- }
118
-
119
- const router = createRouter([oauth], { middlewares: [audit] })
120
- ```
121
-
122
- ## API Reference
123
-
124
- | Function | Description |
125
- | ------------------------------------------------- | -------------------------------------------------------------------------- |
126
- | `createEndpoint(method, route, handler, config?)` | Define a type-safe endpoint with optional validation and middlewares. |
127
- | `createEndpointConfig(config)` | Helper that preserves Zod inference for endpoint schemas. |
128
- | `createRouter(endpoints, config?)` | Build a router that dispatches native Fetch requests to the right handler. |
29
+ <p align="center">
30
+ Made with ❤️ by <a href="https://github.com/aura-stack-js">Aura Stack team</a>
31
+ </p>
package/dist/assert.cjs CHANGED
@@ -20,19 +20,72 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/assert.ts
21
21
  var assert_exports = {};
22
22
  __export(assert_exports, {
23
+ isRouterError: () => isRouterError,
23
24
  isSupportedBodyMethod: () => isSupportedBodyMethod,
24
25
  isSupportedMethod: () => isSupportedMethod,
25
26
  isValidHandler: () => isValidHandler,
26
- isValidRoute: () => isValidRoute
27
+ isValidRoute: () => isValidRoute,
28
+ supportedProtocols: () => supportedProtocols
27
29
  });
28
30
  module.exports = __toCommonJS(assert_exports);
29
- var supportedMethods = ["GET", "POST", "DELETE", "PUT", "PATCH"];
30
- var supportedBodyMethods = ["POST", "PUT", "PATCH"];
31
+
32
+ // src/error.ts
33
+ var statusCode = {
34
+ OK: 200,
35
+ CREATED: 201,
36
+ ACCEPTED: 202,
37
+ NO_CONTENT: 204,
38
+ MULTIPLE_CHOICES: 300,
39
+ MOVED_PERMANENTLY: 301,
40
+ FOUND: 302,
41
+ SEE_OTHER: 303,
42
+ NOT_MODIFIED: 304,
43
+ TEMPORARY_REDIRECT: 307,
44
+ BAD_REQUEST: 400,
45
+ UNAUTHORIZED: 401,
46
+ PAYMENT_REQUIRED: 402,
47
+ FORBIDDEN: 403,
48
+ NOT_FOUND: 404,
49
+ METHOD_NOT_ALLOWED: 405,
50
+ NOT_ACCEPTABLE: 406,
51
+ PROXY_AUTHENTICATION_REQUIRED: 407,
52
+ UNPROCESSABLE_ENTITY: 422,
53
+ INTERNAL_SERVER_ERROR: 500,
54
+ NOT_IMPLEMENTED: 501,
55
+ BAD_GATEWAY: 502,
56
+ SERVICE_UNAVAILABLE: 503,
57
+ HTTP_VERSION_NOT_SUPPORTED: 505
58
+ };
59
+ var statusText = Object.keys(statusCode).reduce(
60
+ (previous, status) => {
61
+ return { ...previous, [status]: status };
62
+ },
63
+ {}
64
+ );
65
+ var AuraStackRouterError = class extends Error {
66
+ constructor(type, message, name) {
67
+ super(message);
68
+ this.name = name ?? "RouterError";
69
+ this.status = statusCode[type];
70
+ this.statusText = statusText[type];
71
+ }
72
+ };
73
+ var RouterError = class extends AuraStackRouterError {
74
+ constructor(type, message, name) {
75
+ super(type, message, name);
76
+ this.name = name ?? "RouterError";
77
+ }
78
+ };
79
+
80
+ // src/assert.ts
81
+ var supportedMethods = /* @__PURE__ */ new Set(["GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD", "TRACE", "CONNECT"]);
82
+ var supportedBodyMethods = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
83
+ var supportedProtocols = /* @__PURE__ */ new Set(["http:", "https:"]);
31
84
  var isSupportedMethod = (method) => {
32
- return supportedMethods.includes(method);
85
+ return supportedMethods.has(method);
33
86
  };
34
87
  var isSupportedBodyMethod = (method) => {
35
- return supportedBodyMethods.includes(method);
88
+ return supportedBodyMethods.has(method);
36
89
  };
37
90
  var isValidRoute = (route) => {
38
91
  const routePattern = /^\/[a-zA-Z0-9/_:-]*$/;
@@ -41,10 +94,15 @@ var isValidRoute = (route) => {
41
94
  var isValidHandler = (handler) => {
42
95
  return typeof handler === "function";
43
96
  };
97
+ var isRouterError = (error) => {
98
+ return error instanceof RouterError;
99
+ };
44
100
  // Annotate the CommonJS export names for ESM import in node:
45
101
  0 && (module.exports = {
102
+ isRouterError,
46
103
  isSupportedBodyMethod,
47
104
  isSupportedMethod,
48
105
  isValidHandler,
49
- isValidRoute
106
+ isValidRoute,
107
+ supportedProtocols
50
108
  });
package/dist/assert.d.cts CHANGED
@@ -1,6 +1,8 @@
1
+ import { RouterError } from './error.cjs';
1
2
  import { HTTPMethod, RoutePattern, RouteHandler } from './types.cjs';
2
3
  import 'zod';
3
4
 
5
+ declare const supportedProtocols: Set<string>;
4
6
  /**
5
7
  * Checks if the provided method is a supported HTTP method.
6
8
  *
@@ -28,5 +30,23 @@ declare const isValidRoute: (route: string) => route is RoutePattern;
28
30
  * @returns True if the handler is valid, false otherwise.
29
31
  */
30
32
  declare const isValidHandler: (handler: unknown) => handler is RouteHandler<any, any>;
33
+ /**
34
+ * Asserts that the error is an instance of RouterError. It is useful if you want
35
+ * to check if the error thrown by the router is an RouterError or by other sources.
36
+ *
37
+ * @param error - The error to check
38
+ * @returns True if the error is an instance of RouterError, false otherwise.
39
+ * @example
40
+ * import { isRouterError } from "aura-stack/router";
41
+ *
42
+ * try {
43
+ * // Some router operation that may throw an error
44
+ * } catch (error) {
45
+ * if (isRouterError(error)) {
46
+ * // Handle RouterError
47
+ * }
48
+ * }
49
+ */
50
+ declare const isRouterError: (error: unknown) => error is RouterError;
31
51
 
32
- export { isSupportedBodyMethod, isSupportedMethod, isValidHandler, isValidRoute };
52
+ export { isRouterError, isSupportedBodyMethod, isSupportedMethod, isValidHandler, isValidRoute, supportedProtocols };
package/dist/assert.d.ts CHANGED
@@ -1,6 +1,8 @@
1
+ import { RouterError } from './error.js';
1
2
  import { HTTPMethod, RoutePattern, RouteHandler } from './types.js';
2
3
  import 'zod';
3
4
 
5
+ declare const supportedProtocols: Set<string>;
4
6
  /**
5
7
  * Checks if the provided method is a supported HTTP method.
6
8
  *
@@ -28,5 +30,23 @@ declare const isValidRoute: (route: string) => route is RoutePattern;
28
30
  * @returns True if the handler is valid, false otherwise.
29
31
  */
30
32
  declare const isValidHandler: (handler: unknown) => handler is RouteHandler<any, any>;
33
+ /**
34
+ * Asserts that the error is an instance of RouterError. It is useful if you want
35
+ * to check if the error thrown by the router is an RouterError or by other sources.
36
+ *
37
+ * @param error - The error to check
38
+ * @returns True if the error is an instance of RouterError, false otherwise.
39
+ * @example
40
+ * import { isRouterError } from "aura-stack/router";
41
+ *
42
+ * try {
43
+ * // Some router operation that may throw an error
44
+ * } catch (error) {
45
+ * if (isRouterError(error)) {
46
+ * // Handle RouterError
47
+ * }
48
+ * }
49
+ */
50
+ declare const isRouterError: (error: unknown) => error is RouterError;
31
51
 
32
- export { isSupportedBodyMethod, isSupportedMethod, isValidHandler, isValidRoute };
52
+ export { isRouterError, isSupportedBodyMethod, isSupportedMethod, isValidHandler, isValidRoute, supportedProtocols };
package/dist/assert.js CHANGED
@@ -1,12 +1,17 @@
1
1
  import {
2
+ isRouterError,
2
3
  isSupportedBodyMethod,
3
4
  isSupportedMethod,
4
5
  isValidHandler,
5
- isValidRoute
6
- } from "./chunk-ENOBC3XN.js";
6
+ isValidRoute,
7
+ supportedProtocols
8
+ } from "./chunk-JNMXLKDG.js";
9
+ import "./chunk-GJC3ODME.js";
7
10
  export {
11
+ isRouterError,
8
12
  isSupportedBodyMethod,
9
13
  isSupportedMethod,
10
14
  isValidHandler,
11
- isValidRoute
15
+ isValidRoute,
16
+ supportedProtocols
12
17
  };
@@ -0,0 +1,31 @@
1
+ import {
2
+ isSupportedMethod,
3
+ isValidHandler,
4
+ isValidRoute
5
+ } from "./chunk-JNMXLKDG.js";
6
+ import {
7
+ RouterError
8
+ } from "./chunk-GJC3ODME.js";
9
+
10
+ // src/endpoint.ts
11
+ var createEndpoint = (method, route, handler, config = {}) => {
12
+ if (!isSupportedMethod(method)) {
13
+ throw new RouterError("METHOD_NOT_ALLOWED", `Unsupported HTTP method: ${method}`);
14
+ }
15
+ if (!isValidRoute(route)) {
16
+ throw new RouterError("BAD_REQUEST", `Invalid route format: ${route}`);
17
+ }
18
+ if (!isValidHandler(handler)) {
19
+ throw new RouterError("BAD_REQUEST", "Handler must be a function");
20
+ }
21
+ return { method, route, handler, config };
22
+ };
23
+ function createEndpointConfig(...args) {
24
+ if (typeof args[0] === "string") return args[1];
25
+ return args[0];
26
+ }
27
+
28
+ export {
29
+ createEndpoint,
30
+ createEndpointConfig
31
+ };
@@ -1,13 +1,13 @@
1
1
  import {
2
- AuraStackRouterError
3
- } from "./chunk-RFYOPPMW.js";
2
+ RouterError
3
+ } from "./chunk-GJC3ODME.js";
4
4
 
5
- // src/middleware.ts
5
+ // src/middlewares.ts
6
6
  var executeGlobalMiddlewares = async (request, middlewares) => {
7
7
  if (!middlewares) return request;
8
8
  for (const middleware of middlewares) {
9
9
  if (typeof middleware !== "function") {
10
- throw new AuraStackRouterError("BAD_REQUEST", "Global middlewares must be functions");
10
+ throw new RouterError("BAD_REQUEST", "Global middlewares must be functions");
11
11
  }
12
12
  const executed = await middleware(request);
13
13
  if (executed instanceof Response) {
@@ -16,7 +16,7 @@ var executeGlobalMiddlewares = async (request, middlewares) => {
16
16
  request = executed;
17
17
  }
18
18
  if (!request || !(request instanceof Request)) {
19
- throw new AuraStackRouterError("BAD_REQUEST", "Global middleware must return a Request or Response object");
19
+ throw new RouterError("BAD_REQUEST", "Global middleware must return a Request or Response object");
20
20
  }
21
21
  return request;
22
22
  };
@@ -25,13 +25,13 @@ var executeMiddlewares = async (request, context, middlewares = []) => {
25
25
  let ctx = context;
26
26
  for (const middleware of middlewares) {
27
27
  if (typeof middleware !== "function") {
28
- throw new AuraStackRouterError("BAD_REQUEST", "Middleware must be a function");
28
+ throw new RouterError("BAD_REQUEST", "Middleware must be a function");
29
29
  }
30
30
  ctx = await middleware(request, ctx);
31
31
  }
32
32
  return ctx;
33
33
  } catch {
34
- throw new AuraStackRouterError("BAD_REQUEST", "Handler threw an error");
34
+ throw new RouterError("BAD_REQUEST", "Handler threw an error");
35
35
  }
36
36
  };
37
37
 
@@ -25,21 +25,30 @@ var statusCode = {
25
25
  SERVICE_UNAVAILABLE: 503,
26
26
  HTTP_VERSION_NOT_SUPPORTED: 505
27
27
  };
28
- var statusText = Object.entries(statusCode).reduce(
29
- (previous, [status, code]) => {
30
- return { ...previous, [code]: status };
28
+ var statusText = Object.keys(statusCode).reduce(
29
+ (previous, status) => {
30
+ return { ...previous, [status]: status };
31
31
  },
32
32
  {}
33
33
  );
34
34
  var AuraStackRouterError = class extends Error {
35
35
  constructor(type, message, name) {
36
36
  super(message);
37
- this.name = name ?? "AuraStackRouterError";
37
+ this.name = name ?? "RouterError";
38
38
  this.status = statusCode[type];
39
- this.statusText = statusText[this.status];
39
+ this.statusText = statusText[type];
40
+ }
41
+ };
42
+ var RouterError = class extends AuraStackRouterError {
43
+ constructor(type, message, name) {
44
+ super(type, message, name);
45
+ this.name = name ?? "RouterError";
40
46
  }
41
47
  };
42
48
 
43
49
  export {
44
- AuraStackRouterError
50
+ statusCode,
51
+ statusText,
52
+ AuraStackRouterError,
53
+ RouterError
45
54
  };
@@ -0,0 +1,143 @@
1
+ import {
2
+ getBody,
3
+ getHeaders,
4
+ getRouteParams,
5
+ getSearchParams
6
+ } from "./chunk-PT4GU6PH.js";
7
+ import {
8
+ isRouterError,
9
+ isSupportedMethod
10
+ } from "./chunk-JNMXLKDG.js";
11
+ import {
12
+ executeGlobalMiddlewares,
13
+ executeMiddlewares
14
+ } from "./chunk-FWDOXDWG.js";
15
+ import {
16
+ RouterError,
17
+ statusText
18
+ } from "./chunk-GJC3ODME.js";
19
+
20
+ // src/router.ts
21
+ var createNode = () => ({
22
+ statics: /* @__PURE__ */ new Map(),
23
+ endpoints: /* @__PURE__ */ new Map()
24
+ });
25
+ var insert = (root, endpoint) => {
26
+ if (!root || !endpoint) return;
27
+ let node = root;
28
+ const segments = endpoint.route === "/" ? [] : endpoint.route.split("/").filter(Boolean);
29
+ for (const segment of segments) {
30
+ if (segment.startsWith(":")) {
31
+ const name = segment.slice(1);
32
+ if (!node.param) {
33
+ node.param = { name, node: createNode() };
34
+ } else if (node.param.name !== name) {
35
+ throw new RouterError(
36
+ "BAD_REQUEST",
37
+ `Conflicting in the route by the dynamic segment "${node.param.name}" and "${name}"`
38
+ );
39
+ }
40
+ node = node.param.node;
41
+ } else {
42
+ if (!node.statics.has(segment)) {
43
+ node.statics.set(segment, createNode());
44
+ }
45
+ node = node.statics.get(segment);
46
+ }
47
+ }
48
+ if (node.endpoints.has(endpoint.method)) {
49
+ throw new RouterError("BAD_REQUEST", `Duplicate endpoint for ${endpoint?.method} ${endpoint?.route}`);
50
+ }
51
+ node.endpoints.set(endpoint.method, endpoint);
52
+ };
53
+ var search = (method, root, pathname) => {
54
+ let node = root;
55
+ const params = {};
56
+ const segments = pathname === "/" ? [] : pathname.split("/").filter(Boolean);
57
+ for (const segment of segments) {
58
+ if (node?.statics.has(segment)) {
59
+ node = node.statics.get(segment);
60
+ } else if (node?.param) {
61
+ params[node.param.name] = decodeURIComponent(segment);
62
+ node = node.param.node;
63
+ } else {
64
+ throw new RouterError("NOT_FOUND", `No route found for path: ${pathname}`);
65
+ }
66
+ }
67
+ if (!node.endpoints.has(method)) {
68
+ throw new RouterError("NOT_FOUND", `No route found for path: ${pathname}`);
69
+ }
70
+ return { endpoint: node.endpoints.get(method), params };
71
+ };
72
+ var handleError = async (error, request, config) => {
73
+ if (config.onError) {
74
+ try {
75
+ const response = await config.onError(error, request);
76
+ return response;
77
+ } catch {
78
+ return Response.json(
79
+ { message: "A critical failure occurred during error handling" },
80
+ { status: 500, statusText: statusText.INTERNAL_SERVER_ERROR }
81
+ );
82
+ }
83
+ }
84
+ if (isRouterError(error)) {
85
+ const { message, status, statusText: statusText2 } = error;
86
+ return Response.json({ message }, { status, statusText: statusText2 });
87
+ }
88
+ return Response.json({ message: "Internal Server Error" }, { status: 500, statusText: statusText.INTERNAL_SERVER_ERROR });
89
+ };
90
+ var handleRequest = async (method, request, config, root) => {
91
+ try {
92
+ if (!isSupportedMethod(request.method)) {
93
+ throw new RouterError("METHOD_NOT_ALLOWED", `The HTTP method '${request.method}' is not supported`);
94
+ }
95
+ const globalRequest = await executeGlobalMiddlewares(request, config.middlewares);
96
+ if (globalRequest instanceof Response) return globalRequest;
97
+ const url = new URL(globalRequest.url);
98
+ const pathnameWithBase = url.pathname;
99
+ if (globalRequest.method !== method) {
100
+ throw new RouterError("METHOD_NOT_ALLOWED", `The HTTP method '${globalRequest.method}' is not allowed`);
101
+ }
102
+ const { endpoint, params } = search(method, root, pathnameWithBase);
103
+ if (endpoint.method !== globalRequest.method) {
104
+ throw new RouterError("METHOD_NOT_ALLOWED", `The HTTP method '${globalRequest.method}' is not allowed`);
105
+ }
106
+ const dynamicParams = getRouteParams(params, endpoint.config);
107
+ const body = await getBody(globalRequest, endpoint.config);
108
+ const searchParams = getSearchParams(globalRequest.url, endpoint.config);
109
+ const headers = getHeaders(globalRequest);
110
+ const context = {
111
+ params: dynamicParams,
112
+ searchParams,
113
+ headers,
114
+ body
115
+ };
116
+ await executeMiddlewares(globalRequest, context, endpoint.config.middlewares);
117
+ const response = await endpoint.handler(globalRequest, context);
118
+ return response;
119
+ } catch (error) {
120
+ return handleError(error, request, config);
121
+ }
122
+ };
123
+ var createRouter = (endpoints, config = {}) => {
124
+ const root = createNode();
125
+ const server = {};
126
+ const methods = /* @__PURE__ */ new Set();
127
+ for (const endpoint of endpoints) {
128
+ const withBasePath = config.basePath ? `${config.basePath}${endpoint.route}` : endpoint.route;
129
+ insert(root, { ...endpoint, route: withBasePath });
130
+ methods.add(endpoint.method);
131
+ }
132
+ for (const method of methods) {
133
+ server[method] = (request) => handleRequest(method, request, config, root);
134
+ }
135
+ return server;
136
+ };
137
+
138
+ export {
139
+ createNode,
140
+ insert,
141
+ search,
142
+ createRouter
143
+ };
@@ -0,0 +1,33 @@
1
+ import {
2
+ RouterError
3
+ } from "./chunk-GJC3ODME.js";
4
+
5
+ // src/assert.ts
6
+ var supportedMethods = /* @__PURE__ */ new Set(["GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD", "TRACE", "CONNECT"]);
7
+ var supportedBodyMethods = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
8
+ var supportedProtocols = /* @__PURE__ */ new Set(["http:", "https:"]);
9
+ var isSupportedMethod = (method) => {
10
+ return supportedMethods.has(method);
11
+ };
12
+ var isSupportedBodyMethod = (method) => {
13
+ return supportedBodyMethods.has(method);
14
+ };
15
+ var isValidRoute = (route) => {
16
+ const routePattern = /^\/[a-zA-Z0-9/_:-]*$/;
17
+ return routePattern.test(route);
18
+ };
19
+ var isValidHandler = (handler) => {
20
+ return typeof handler === "function";
21
+ };
22
+ var isRouterError = (error) => {
23
+ return error instanceof RouterError;
24
+ };
25
+
26
+ export {
27
+ supportedProtocols,
28
+ isSupportedMethod,
29
+ isSupportedBodyMethod,
30
+ isValidRoute,
31
+ isValidHandler,
32
+ isRouterError
33
+ };