@arkyn/server 3.0.1-beta.3 → 3.0.1-beta.30

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 (59) hide show
  1. package/README.md +368 -65
  2. package/dist/api/arkynLogRequest.d.ts.map +1 -1
  3. package/dist/api/arkynLogRequest.js +3 -4
  4. package/dist/api/makeRequest.d.ts +1 -1
  5. package/dist/api/makeRequest.d.ts.map +1 -1
  6. package/dist/api/makeRequest.js +3 -5
  7. package/dist/config/apiInstance.d.ts +17 -17
  8. package/dist/config/apiInstance.d.ts.map +1 -1
  9. package/dist/config/apiInstance.js +15 -15
  10. package/dist/config/arkynLogInstance.d.ts +2 -2
  11. package/dist/config/arkynLogInstance.d.ts.map +1 -1
  12. package/dist/config/arkynLogInstance.js +6 -5
  13. package/dist/mapper/arkynLogRequestMapper.js +2 -2
  14. package/dist/services/formParse.d.ts +3 -3
  15. package/dist/services/formParse.d.ts.map +1 -1
  16. package/dist/services/formParse.js +8 -5
  17. package/dist/services/measureRouteExecution.d.ts +3 -0
  18. package/dist/services/measureRouteExecution.d.ts.map +1 -0
  19. package/dist/services/measureRouteExecution.js +24 -0
  20. package/dist/services/schemaValidator.d.ts +3 -3
  21. package/dist/services/schemaValidator.d.ts.map +1 -1
  22. package/dist/services/schemaValidator.js +1 -1
  23. package/package.json +32 -21
  24. package/src/api/arkynLogRequest.ts +0 -112
  25. package/src/api/deleteRequest.ts +0 -22
  26. package/src/api/getRequest.ts +0 -20
  27. package/src/api/makeRequest.ts +0 -120
  28. package/src/api/patchRequest.ts +0 -22
  29. package/src/api/postRequest.ts +0 -22
  30. package/src/api/putRequest.ts +0 -22
  31. package/src/config/apiInstance.ts +0 -148
  32. package/src/config/arkynLogInstance.ts +0 -68
  33. package/src/http/badResponses/badGateway.ts +0 -63
  34. package/src/http/badResponses/badRequest.ts +0 -63
  35. package/src/http/badResponses/conflict.ts +0 -63
  36. package/src/http/badResponses/forbidden.ts +0 -63
  37. package/src/http/badResponses/notFound.ts +0 -63
  38. package/src/http/badResponses/notImplemented.ts +0 -63
  39. package/src/http/badResponses/serverError.ts +0 -63
  40. package/src/http/badResponses/unauthorized.ts +0 -63
  41. package/src/http/badResponses/unprocessableEntity.ts +0 -79
  42. package/src/http/successResponses/created.ts +0 -64
  43. package/src/http/successResponses/found.ts +0 -67
  44. package/src/http/successResponses/noContent.ts +0 -42
  45. package/src/http/successResponses/success.ts +0 -64
  46. package/src/http/successResponses/updated.ts +0 -64
  47. package/src/index.ts +0 -31
  48. package/src/mapper/arkynLogRequestMapper.ts +0 -73
  49. package/src/services/decodeErrorMessageFromRequest.ts +0 -36
  50. package/src/services/decodeRequestBody.ts +0 -43
  51. package/src/services/errorHandler.ts +0 -99
  52. package/src/services/formParse.ts +0 -83
  53. package/src/services/getCaller.ts +0 -82
  54. package/src/services/getScopedParams.ts +0 -43
  55. package/src/services/httpDebug.ts +0 -61
  56. package/src/services/schemaValidator.ts +0 -66
  57. package/src/types/ApiResponseDTO.ts +0 -19
  58. package/tsconfig.json +0 -21
  59. package/vitest.config.ts +0 -5
@@ -1,99 +0,0 @@
1
- import { BadGateway } from "../http/badResponses/badGateway";
2
- import { BadRequest } from "../http/badResponses/badRequest";
3
- import { Conflict } from "../http/badResponses/conflict";
4
- import { Forbidden } from "../http/badResponses/forbidden";
5
- import { NotFound } from "../http/badResponses/notFound";
6
- import { NotImplemented } from "../http/badResponses/notImplemented";
7
- import { ServerError } from "../http/badResponses/serverError";
8
- import { Unauthorized } from "../http/badResponses/unauthorized";
9
- import { UnprocessableEntity } from "../http/badResponses/unprocessableEntity";
10
-
11
- import { Created } from "../http/successResponses/created";
12
- import { Found } from "../http/successResponses/found";
13
- import { NoContent } from "../http/successResponses/noContent";
14
- import { Success } from "../http/successResponses/success";
15
- import { Updated } from "../http/successResponses/updated";
16
-
17
- /**
18
- * Handles errors and converts them into appropriate HTTP responses.
19
- *
20
- * This function takes an error object and determines its type to return
21
- * the corresponding HTTP response. It supports both success and error
22
- * response types, converting them into a standardized format using the
23
- * `toResponse` method when applicable.
24
- *
25
- * @param error - The error object to handle. It can be an instance of various
26
- * HTTP response classes or a generic error.
27
- *
28
- * @returns The corresponding HTTP response object if the error matches a known
29
- * type, or `undefined` if no match is found.
30
- *
31
- * ### Supported Success Responses:
32
- * - `Found`
33
- * - `Created`
34
- * - `Updated`
35
- * - `Success`
36
- * - `NoContent`
37
- *
38
- * ### Supported Error Responses:
39
- * - `BadGateway`
40
- * - `BadRequest`
41
- * - `Conflict`
42
- * - `Forbidden`
43
- * - `NotFound`
44
- * - `NotImplemented`
45
- * - `ServerError`
46
- * - `Unauthorized`
47
- * - `UnprocessableEntity`
48
- *
49
- * ### Example Usage:
50
- * ```typescript
51
- * try {
52
- * // Some operation that might throw an error
53
- * } catch (error) {
54
- * return errorHandler(error);
55
- * }
56
- * ```
57
- */
58
-
59
- function errorHandler(error: any): Response {
60
- switch (true) {
61
- case error instanceof Response:
62
- return error;
63
- case error instanceof Found:
64
- return error.toResponse();
65
- case error instanceof Created:
66
- return error.toResponse();
67
- case error instanceof Updated:
68
- return error.toResponse();
69
- case error instanceof Success:
70
- return error.toResponse();
71
- case error instanceof NoContent:
72
- return error.toResponse();
73
- }
74
-
75
- switch (true) {
76
- case error instanceof BadGateway:
77
- return error.toResponse();
78
- case error instanceof BadRequest:
79
- return error.toResponse();
80
- case error instanceof Conflict:
81
- return error.toResponse();
82
- case error instanceof Forbidden:
83
- return error.toResponse();
84
- case error instanceof NotFound:
85
- return error.toResponse();
86
- case error instanceof NotImplemented:
87
- return error.toResponse();
88
- case error instanceof ServerError:
89
- return error.toResponse();
90
- case error instanceof Unauthorized:
91
- return error.toResponse();
92
- case error instanceof UnprocessableEntity:
93
- return error.toResponse();
94
- }
95
-
96
- return new ServerError("Server error", error).toResponse();
97
- }
98
-
99
- export { errorHandler };
@@ -1,83 +0,0 @@
1
- import type { Schema } from "zod";
2
-
3
- type SuccessResponse<T extends FormParseProps> = {
4
- success: true;
5
- data: T[1] extends Schema<infer U> ? U : never;
6
- };
7
-
8
- type ErrorResponse = {
9
- success: false;
10
- fields: { [x: string]: string };
11
- fieldErrors: { [x: string]: string };
12
- };
13
-
14
- type FormParseProps = [formData: { [k: string]: any }, schema: Schema];
15
-
16
- type FormParseReturnType<T extends FormParseProps> =
17
- | SuccessResponse<T>
18
- | ErrorResponse;
19
-
20
- /**
21
- * Parses form data using a Zod schema and returns the result.
22
- *
23
- * @template T - A type that extends `FormParseProps`.
24
- *
25
- * @param {T} param0 - An array containing the form data and the Zod schema.
26
- * @param {T[0]} param0[0] - The form data to be validated.
27
- * @param {T[1]} param0[1] - The Zod schema used for validation.
28
- *
29
- * @returns {FormParseReturnType<T>} An object containing the validation result.
30
- * - If validation fails, it includes:
31
- * - `success`: A boolean indicating the validation status (false).
32
- * - `fieldErrors`: An object mapping field names to their respective error messages.
33
- * - `fields`: The original form data.
34
- * - If validation succeeds, it includes:
35
- * - `success`: A boolean indicating the validation status (true).
36
- * - `data`: The parsed and validated data.
37
- *
38
- * @example
39
- * ```typescript
40
- * import { z } from "zod";
41
- *
42
- * const schema = z.object({
43
- * name: z.string().min(1, "Name is required"),
44
- * age: z.number().min(18, "Must be at least 18"),
45
- * });
46
- *
47
- * const formData = { name: "", age: 17 };
48
- *
49
- * const result = formParse([formData, schema]);
50
- *
51
- * if (!result.success) {
52
- * console.log(result.fieldErrors); // { name: "Name is required", age: "Must be at least 18" }
53
- * } else {
54
- * console.log(result.data); // Parsed data
55
- * }
56
- * ```
57
- */
58
-
59
- function formParse<T extends FormParseProps>([
60
- formData,
61
- schema,
62
- ]: T): FormParseReturnType<T> {
63
- const zodResponse = schema.safeParse(formData);
64
-
65
- if (zodResponse.success === false) {
66
- const errorsObject = Object.fromEntries(
67
- zodResponse.error.errors.map((item) => [
68
- item.path.join("."),
69
- item.message,
70
- ])
71
- );
72
-
73
- return {
74
- success: zodResponse.success,
75
- fieldErrors: errorsObject,
76
- fields: formData,
77
- };
78
- } else {
79
- return { success: zodResponse.success, data: zodResponse.data };
80
- }
81
- }
82
-
83
- export { formParse };
@@ -1,82 +0,0 @@
1
- import path from "path";
2
-
3
- /**
4
- * Retrieves information about the caller of the current function.
5
- *
6
- * This function analyzes the stack trace to determine the file path and function name
7
- * of the caller. It excludes stack trace entries related to the `@arkyn/server` package
8
- * and attempts to resolve the file path relative to the project root directory.
9
- *
10
- * @returns An object containing:
11
- * - `functionName`: The name of the function that called the current function, or "Unknown function" if it cannot be determined.
12
- * - `callerInfo`: The file path of the caller relative to the project root, or "Unknown caller" if it cannot be determined.
13
- */
14
- function getCaller() {
15
- const projectRoot = process.cwd();
16
-
17
- const err = new Error();
18
- const stack = err.stack || "";
19
- const stackLines = stack.split("\n").map((line) => line.trim());
20
-
21
- // The first line is the error message
22
- // The second line is this function (getCaller)
23
- // The third line should be the direct caller
24
- // We start from 2 because indexes are zero-based
25
- let callerIndex = 2;
26
-
27
- // Ignore internal or infrastructure lines if necessary
28
- while (
29
- callerIndex < stackLines.length &&
30
- (stackLines[callerIndex].includes("node:internal") ||
31
- stackLines[callerIndex].includes("/node_modules/"))
32
- ) {
33
- callerIndex++;
34
- }
35
-
36
- const callerLine = stackLines[callerIndex] || "";
37
-
38
- let functionName = "Unknown function";
39
- let callerInfo = "Unknown caller";
40
-
41
- // Default for named functions: "at functionName (file:line:column)"
42
- const namedFunctionMatch = callerLine.match(/at\s+([^(\s]+)\s+\(([^)]+)\)/);
43
- if (namedFunctionMatch) {
44
- functionName = namedFunctionMatch[1];
45
- callerInfo = namedFunctionMatch[2];
46
- }
47
- // Default for anonymous functions or methods: "at file:line:column"
48
- else {
49
- const anonymousFunctionMatch = callerLine.match(/at\s+(.+)/);
50
- if (anonymousFunctionMatch) {
51
- callerInfo = anonymousFunctionMatch[1];
52
-
53
- // Tenta extrair nome da função de padrões como Object.method ou Class.method
54
- const objectMethodMatch = callerInfo.match(/at\s+([^(\s]+)\s+/);
55
- if (objectMethodMatch && objectMethodMatch[1] !== "new") {
56
- functionName = objectMethodMatch[1];
57
- }
58
- }
59
- }
60
-
61
- // Handles file paths
62
- if (callerInfo.includes("(")) {
63
- callerInfo = callerInfo.substring(
64
- callerInfo.indexOf("(") + 1,
65
- callerInfo.lastIndexOf(")")
66
- );
67
- }
68
-
69
- // Remove the line:column part of the file path
70
- callerInfo = callerInfo.split(":").slice(0, -2).join(":");
71
-
72
- // Make the path relative to the project
73
- try {
74
- callerInfo = path.relative(projectRoot, callerInfo);
75
- } catch (e) {
76
- // If it fails to relativize, use the original path
77
- }
78
-
79
- return { functionName, callerInfo };
80
- }
81
-
82
- export { getCaller };
@@ -1,43 +0,0 @@
1
- type GetScopedParamsFunction = (
2
- request: Request,
3
- scope?: string
4
- ) => URLSearchParams;
5
- /**
6
- * Extracts and returns scoped query parameters from a request URL.
7
- *
8
- * @param request - The incoming request object containing the URL.
9
- * @param scope - An optional string representing the scope prefix for filtering query parameters.
10
- * If no scope is provided, all query parameters are returned.
11
- *
12
- * @returns A `URLSearchParams` object containing the scoped query parameters.
13
- * If a scope is provided, only parameters with keys starting with the scope
14
- * (e.g., `scope:key`) are included, and the scope prefix is removed from the keys.
15
- * If no scope is provided, all query parameters are returned as-is.
16
- *
17
- * @example
18
- * // Example 1: No scope provided
19
- * const request = { url: "https://example.com?key1=value1&key2=value2" };
20
- * const params = getScopedParams(request);
21
- * console.log(params.toString()); // Output: "key1=value1&key2=value2"
22
- *
23
- * @example
24
- * // Example 2: Scope provided
25
- * const request = { url: "https://example.com?scope:key1=value1&scope:key2=value2&key3=value3" };
26
- * const params = getScopedParams(request, "scope");
27
- * console.log(params.toString()); // Output: "key1=value1&key2=value2"
28
- */
29
-
30
- const getScopedParams: GetScopedParamsFunction = (request, scope = "") => {
31
- const url = new URL(request.url);
32
- if (scope === "") return url.searchParams;
33
-
34
- const scopedSearchParams: [string, string][] = Array.from(
35
- url.searchParams.entries()
36
- )
37
- .filter(([key]) => key.startsWith(`${scope}:`))
38
- .map(([key, value]) => [key.replace(`${scope}:`, ""), value]);
39
-
40
- return new URLSearchParams(scopedSearchParams);
41
- };
42
-
43
- export { getScopedParams };
@@ -1,61 +0,0 @@
1
- import { getCaller } from "../services/getCaller";
2
-
3
- /**
4
- * Logs debug information to the console when in development mode or when the
5
- * `SHOW_ERRORS_IN_CONSOLE` environment variable is set to "true".
6
- *
7
- * This function provides detailed information about the caller function,
8
- * its location, and the provided body and cause, if any.
9
- *
10
- * @param name - A string representing the name or context of the debug log.
11
- * @param body - The main content or data to be logged.
12
- * @param cause - (Optional) Additional information or error cause to be logged.
13
- *
14
- * @remarks
15
- * The debug logs are only displayed when the application is running in
16
- * development mode (`NODE_ENV === "development"`) or when the
17
- * `SHOW_ERRORS_IN_CONSOLE` environment variable is explicitly set to "true".
18
- *
19
- * The logs include:
20
- * - The name of the debug context.
21
- * - The caller function name and its location.
22
- * - The provided body content.
23
- * - The optional cause, if provided.
24
- *
25
- * @example
26
- * ```typescript
27
- * httpDebug("FetchUserData", { userId: 123 });
28
- * ```
29
- *
30
- * @example
31
- * ```typescript
32
- * httpDebug("FetchUserDataError", { userId: 123 }, new Error("User not found"));
33
- * ```
34
- */
35
-
36
- function httpDebug(name: string, body: any, cause?: any) {
37
- const isDebugMode =
38
- process.env.NODE_ENV === "development" ||
39
- process.env?.SHOW_ERRORS_IN_CONSOLE === "true";
40
-
41
- if (isDebugMode) {
42
- const reset = "\x1b[0m";
43
- const cyan = "\x1b[36m";
44
-
45
- const debugName = `${cyan}[ARKYN-DEBUG]${reset}`;
46
- const { callerInfo, functionName } = getCaller();
47
-
48
- let consoleData = `${debugName} ${name} initialized\n`;
49
- consoleData += `${debugName} Caller Function: ${functionName}\n`;
50
- consoleData += `${debugName} Caller Location: ${callerInfo}\n`;
51
- consoleData += `${debugName} Body: ${JSON.stringify(body, null, 2)}\n`;
52
-
53
- if (cause) {
54
- consoleData += `${debugName} Cause: ${JSON.stringify(cause, null, 2)}\n`;
55
- }
56
-
57
- console.log(consoleData);
58
- }
59
- }
60
-
61
- export { httpDebug };
@@ -1,66 +0,0 @@
1
- import { Schema, z } from "zod";
2
-
3
- import { ServerError } from "../http/badResponses/serverError";
4
- import { UnprocessableEntity } from "../http/badResponses/unprocessableEntity";
5
- import { formParse } from "./formParse";
6
- import { getCaller } from "./getCaller";
7
- import { httpDebug } from "./httpDebug";
8
-
9
- function formatErrorMessage(error: z.ZodError) {
10
- const title = "Error validating:";
11
- const lines = error.issues.map(
12
- ({ path, message }) => `-> ${path.join(".")}: ${message}`
13
- );
14
-
15
- return [title, ...lines].join("\n");
16
- }
17
-
18
- class SchemaValidator<T extends Schema> {
19
- functionName: string;
20
- callerInfo: string;
21
-
22
- constructor(readonly schema: T) {
23
- const { callerInfo, functionName } = getCaller();
24
- this.callerInfo = callerInfo;
25
- this.functionName = functionName;
26
- }
27
-
28
- isValid(data: any): boolean {
29
- return this.schema.safeParse(data).success;
30
- }
31
-
32
- safeValidate(data: any): z.SafeParseReturnType<z.infer<T>, z.infer<T>> {
33
- return this.schema.safeParse(data);
34
- }
35
-
36
- validate(data: any): z.infer<T> {
37
- try {
38
- return this.schema.parse(data);
39
- } catch (error: any) {
40
- throw new ServerError(formatErrorMessage(error));
41
- }
42
- }
43
-
44
- formValidate(data: any, message?: string): z.infer<T> {
45
- const formParsed = formParse([data, this.schema]);
46
-
47
- if (!formParsed.success) {
48
- httpDebug("UnprocessableEntity", formParsed);
49
- const firstErrorKey = Object.keys(formParsed.fieldErrors)[0];
50
-
51
- throw new UnprocessableEntity(
52
- {
53
- fields: formParsed.fields,
54
- fieldErrors: formParsed.fieldErrors,
55
- data: { scrollTo: firstErrorKey },
56
- message,
57
- },
58
- false
59
- );
60
- }
61
-
62
- return formParsed.data;
63
- }
64
- }
65
-
66
- export { SchemaValidator };
@@ -1,19 +0,0 @@
1
- type ApiSuccessResponse<T = any> = {
2
- success: true;
3
- status: number;
4
- message: string;
5
- response: T;
6
- cause: null;
7
- };
8
-
9
- type ApiFailedResponse = {
10
- success: false;
11
- status: number;
12
- message: string;
13
- response: any;
14
- cause: string | Error | null;
15
- };
16
-
17
- type ApiResponseDTO<T = any> = ApiSuccessResponse<T> | ApiFailedResponse;
18
-
19
- export type { ApiResponseDTO };
package/tsconfig.json DELETED
@@ -1,21 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "allowSyntheticDefaultImports": true,
4
- "declaration": true,
5
- "declarationDir": "./dist",
6
- "declarationMap": true,
7
- "isolatedModules": true,
8
- "lib": ["DOM", "DOM.Iterable", "ES2022"],
9
- "module": "ESNext",
10
- "moduleResolution": "node",
11
- "outDir": "./dist",
12
- "preserveWatchOutput": true,
13
- "skipLibCheck": true,
14
- "strict": true,
15
- "target": "ESNext",
16
- "types": ["bun-types"],
17
- "verbatimModuleSyntax": true
18
- },
19
- "exclude": ["node_modules", "dist"],
20
- "include": ["src/**/*.ts"]
21
- }
package/vitest.config.ts DELETED
@@ -1,5 +0,0 @@
1
- import { defineConfig } from "vite";
2
-
3
- export default defineConfig({
4
- resolve: { mainFields: ["module"] },
5
- });