@aura-stack/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/dist/assert.cjs CHANGED
@@ -20,14 +20,67 @@ 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 = /* @__PURE__ */ new Set(["GET", "POST", "DELETE", "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"]);
30
82
  var supportedBodyMethods = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
83
+ var supportedProtocols = /* @__PURE__ */ new Set(["http:", "https:"]);
31
84
  var isSupportedMethod = (method) => {
32
85
  return supportedMethods.has(method);
33
86
  };
@@ -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-JRJKKBSH.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
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
+ };
@@ -1,6 +1,11 @@
1
+ import {
2
+ RouterError
3
+ } from "./chunk-GJC3ODME.js";
4
+
1
5
  // src/assert.ts
2
- var supportedMethods = /* @__PURE__ */ new Set(["GET", "POST", "DELETE", "PUT", "PATCH"]);
6
+ var supportedMethods = /* @__PURE__ */ new Set(["GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD", "TRACE", "CONNECT"]);
3
7
  var supportedBodyMethods = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
8
+ var supportedProtocols = /* @__PURE__ */ new Set(["http:", "https:"]);
4
9
  var isSupportedMethod = (method) => {
5
10
  return supportedMethods.has(method);
6
11
  };
@@ -14,10 +19,15 @@ var isValidRoute = (route) => {
14
19
  var isValidHandler = (handler) => {
15
20
  return typeof handler === "function";
16
21
  };
22
+ var isRouterError = (error) => {
23
+ return error instanceof RouterError;
24
+ };
17
25
 
18
26
  export {
27
+ supportedProtocols,
19
28
  isSupportedMethod,
20
29
  isSupportedBodyMethod,
21
30
  isValidRoute,
22
- isValidHandler
31
+ isValidHandler,
32
+ isRouterError
23
33
  };
@@ -0,0 +1,78 @@
1
+ import {
2
+ isSupportedBodyMethod
3
+ } from "./chunk-JNMXLKDG.js";
4
+ import {
5
+ RouterError
6
+ } from "./chunk-GJC3ODME.js";
7
+
8
+ // src/context.ts
9
+ var getRouteParams = (params, config) => {
10
+ if (config.schemas?.params) {
11
+ const parsed = config.schemas.params.safeParse(params);
12
+ if (!parsed.success) {
13
+ throw new RouterError("UNPROCESSABLE_ENTITY", "Invalid route parameters");
14
+ }
15
+ return parsed.data;
16
+ }
17
+ return params;
18
+ };
19
+ var getSearchParams = (url, config) => {
20
+ const route = new URL(url);
21
+ if (config.schemas?.searchParams) {
22
+ const parsed = config.schemas.searchParams.safeParse(Object.fromEntries(route.searchParams.entries()));
23
+ if (!parsed.success) {
24
+ throw new RouterError("UNPROCESSABLE_ENTITY", "Invalid search parameters");
25
+ }
26
+ return parsed.data;
27
+ }
28
+ return new URLSearchParams(route.searchParams.toString());
29
+ };
30
+ var getHeaders = (request) => {
31
+ return new Headers(request.headers);
32
+ };
33
+ var getBody = async (request, config) => {
34
+ if (!isSupportedBodyMethod(request.method)) {
35
+ return null;
36
+ }
37
+ const clone = request.clone();
38
+ const contentType = clone.headers.get("Content-Type") ?? "";
39
+ if (contentType.includes("application/json") || config.schemas?.body) {
40
+ const json = await clone.json();
41
+ if (config.schemas?.body) {
42
+ const parsed = config.schemas.body.safeParse(json);
43
+ if (!parsed.success) {
44
+ throw new RouterError("UNPROCESSABLE_ENTITY", "Invalid request body");
45
+ }
46
+ return parsed.data;
47
+ }
48
+ return json;
49
+ }
50
+ try {
51
+ if (createContentTypeRegex(["application/x-www-form-urlencoded", "multipart/form-data"], contentType)) {
52
+ return await clone.formData();
53
+ }
54
+ if (createContentTypeRegex(["text/", "application/xml"], contentType)) {
55
+ return await clone.text();
56
+ }
57
+ if (createContentTypeRegex(["application/octet-stream"], contentType)) {
58
+ return await clone.arrayBuffer();
59
+ }
60
+ if (createContentTypeRegex(["image/", "video/", "audio/", "application/pdf"], contentType)) {
61
+ return await clone.blob();
62
+ }
63
+ return null;
64
+ } catch {
65
+ throw new RouterError("UNPROCESSABLE_ENTITY", "Invalid request body, the content-type does not match the body format");
66
+ }
67
+ };
68
+ var createContentTypeRegex = (contentTypes, contenType) => {
69
+ const regex = new RegExp(`${contentTypes.join("|")}`);
70
+ return regex.test(contenType);
71
+ };
72
+
73
+ export {
74
+ getRouteParams,
75
+ getSearchParams,
76
+ getHeaders,
77
+ getBody
78
+ };