@arkyn/server 2.2.15 → 3.0.1-beta.10

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 (69) hide show
  1. package/README.md +1 -1
  2. package/dist/api/arkynLogRequest.d.ts +55 -0
  3. package/dist/api/arkynLogRequest.d.ts.map +1 -0
  4. package/dist/api/arkynLogRequest.js +82 -0
  5. package/dist/api/deleteRequest.d.ts +1 -1
  6. package/dist/api/deleteRequest.d.ts.map +1 -1
  7. package/dist/api/getRequest.d.ts +1 -1
  8. package/dist/api/getRequest.d.ts.map +1 -1
  9. package/dist/api/makeRequest.d.ts +2 -2
  10. package/dist/api/makeRequest.d.ts.map +1 -1
  11. package/dist/api/makeRequest.js +18 -18
  12. package/dist/api/patchRequest.d.ts +1 -1
  13. package/dist/api/patchRequest.d.ts.map +1 -1
  14. package/dist/api/postRequest.d.ts +1 -1
  15. package/dist/api/postRequest.d.ts.map +1 -1
  16. package/dist/api/putRequest.d.ts +1 -1
  17. package/dist/api/putRequest.d.ts.map +1 -1
  18. package/dist/config/apiInstance.d.ts +5 -5
  19. package/dist/config/arkynLogInstance.d.ts +44 -0
  20. package/dist/config/arkynLogInstance.d.ts.map +1 -0
  21. package/dist/config/arkynLogInstance.js +49 -0
  22. package/dist/index.d.ts +1 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -2
  25. package/dist/mapper/arkynLogRequestMapper.d.ts +30 -0
  26. package/dist/mapper/arkynLogRequestMapper.d.ts.map +1 -0
  27. package/dist/mapper/arkynLogRequestMapper.js +44 -0
  28. package/dist/services/decodeRequestBody.d.ts +1 -1
  29. package/dist/services/decodeRequestBody.d.ts.map +1 -1
  30. package/dist/services/formParse.d.ts +18 -1
  31. package/dist/services/formParse.d.ts.map +1 -1
  32. package/dist/services/getCaller.d.ts.map +1 -1
  33. package/dist/services/getCaller.js +41 -15
  34. package/dist/services/getScopedParams.d.ts +1 -1
  35. package/dist/services/getScopedParams.d.ts.map +1 -1
  36. package/dist/services/httpDebug.d.ts.map +1 -1
  37. package/dist/services/httpDebug.js +0 -1
  38. package/dist/types/ApiResponseDTO.d.ts +17 -0
  39. package/dist/types/ApiResponseDTO.d.ts.map +1 -0
  40. package/dist/types/ApiResponseDTO.js +1 -0
  41. package/package.json +2 -5
  42. package/src/api/arkynLogRequest.ts +118 -0
  43. package/src/api/deleteRequest.ts +1 -1
  44. package/src/api/getRequest.ts +1 -1
  45. package/src/api/makeRequest.ts +21 -20
  46. package/src/api/patchRequest.ts +1 -1
  47. package/src/api/postRequest.ts +1 -1
  48. package/src/api/putRequest.ts +1 -1
  49. package/src/config/arkynLogInstance.ts +70 -0
  50. package/src/index.ts +1 -2
  51. package/src/mapper/arkynLogRequestMapper.ts +73 -0
  52. package/src/services/decodeRequestBody.ts +2 -1
  53. package/src/services/formParse.ts +18 -1
  54. package/src/services/getCaller.ts +54 -20
  55. package/src/services/getScopedParams.ts +4 -2
  56. package/src/services/httpDebug.ts +0 -1
  57. package/src/types/ApiResponseDTO.ts +19 -0
  58. package/dist/api/inboxFlowRequest.d.ts +0 -40
  59. package/dist/api/inboxFlowRequest.d.ts.map +0 -1
  60. package/dist/api/inboxFlowRequest.js +0 -63
  61. package/dist/config/inboxFlowInstance.d.ts +0 -44
  62. package/dist/config/inboxFlowInstance.d.ts.map +0 -1
  63. package/dist/config/inboxFlowInstance.js +0 -46
  64. package/dist/services/sendFileToS3.d.ts +0 -4
  65. package/dist/services/sendFileToS3.d.ts.map +0 -1
  66. package/dist/services/sendFileToS3.js +0 -105
  67. package/src/api/inboxFlowRequest.ts +0 -76
  68. package/src/config/inboxFlowInstance.ts +0 -65
  69. package/src/services/sendFileToS3.ts +0 -131
@@ -15,25 +15,51 @@ function getCaller() {
15
15
  const err = new Error();
16
16
  const stack = err.stack || "";
17
17
  const stackLines = stack.split("\n").map((line) => line.trim());
18
- const callerLine = stackLines[4] || "";
19
- let functionName = "unknown";
20
- let callerInfo = "unknown location";
21
- const functionMatch = callerLine.match(/at\s+([^\s]+)\s+\((.*)\)/);
22
- if (functionMatch) {
23
- functionName = functionMatch[1];
24
- callerInfo = functionMatch[2];
18
+ // The first line is the error message
19
+ // The second line is this function (getCaller)
20
+ // The third line should be the direct caller
21
+ // We start from 2 because indexes are zero-based
22
+ let callerIndex = 2;
23
+ // Ignore internal or infrastructure lines if necessary
24
+ while (callerIndex < stackLines.length &&
25
+ (stackLines[callerIndex].includes("node:internal") ||
26
+ stackLines[callerIndex].includes("/node_modules/"))) {
27
+ callerIndex++;
25
28
  }
29
+ const callerLine = stackLines[callerIndex] || "";
30
+ let functionName = "Unknown function";
31
+ let callerInfo = "Unknown caller";
32
+ // Default for named functions: "at functionName (file:line:column)"
33
+ const namedFunctionMatch = callerLine.match(/at\s+([^(\s]+)\s+\(([^)]+)\)/);
34
+ if (namedFunctionMatch) {
35
+ functionName = namedFunctionMatch[1];
36
+ callerInfo = namedFunctionMatch[2];
37
+ }
38
+ // Default for anonymous functions or methods: "at file:line:column"
26
39
  else {
27
- const locationMatch = callerLine.match(/at\s+(.*)/);
28
- if (locationMatch) {
29
- callerInfo = locationMatch[1];
30
- const pathParts = callerInfo.split("/");
31
- const lastPart = pathParts[pathParts.length - 1] || "";
32
- const fileParts = lastPart.split(":");
33
- functionName = fileParts[0] || "unknown";
40
+ const anonymousFunctionMatch = callerLine.match(/at\s+(.+)/);
41
+ if (anonymousFunctionMatch) {
42
+ callerInfo = anonymousFunctionMatch[1];
43
+ // Tenta extrair nome da função de padrões como Object.method ou Class.method
44
+ const objectMethodMatch = callerInfo.match(/at\s+([^(\s]+)\s+/);
45
+ if (objectMethodMatch && objectMethodMatch[1] !== "new") {
46
+ functionName = objectMethodMatch[1];
47
+ }
34
48
  }
35
49
  }
36
- callerInfo = path.relative(projectRoot, callerInfo);
50
+ // Handles file paths
51
+ if (callerInfo.includes("(")) {
52
+ callerInfo = callerInfo.substring(callerInfo.indexOf("(") + 1, callerInfo.lastIndexOf(")"));
53
+ }
54
+ // Remove the line:column part of the file path
55
+ callerInfo = callerInfo.split(":").slice(0, -2).join(":");
56
+ // Make the path relative to the project
57
+ try {
58
+ callerInfo = path.relative(projectRoot, callerInfo);
59
+ }
60
+ catch (e) {
61
+ // If it fails to relativize, use the original path
62
+ }
37
63
  return { functionName, callerInfo };
38
64
  }
39
65
  export { getCaller };
@@ -1,4 +1,4 @@
1
- import type { GetScopedParamsFunction } from "@arkyn/types";
1
+ type GetScopedParamsFunction = (request: Request, scope?: string) => URLSearchParams;
2
2
  /**
3
3
  * Extracts and returns scoped query parameters from a request URL.
4
4
  *
@@ -1 +1 @@
1
- {"version":3,"file":"getScopedParams.d.ts","sourceRoot":"","sources":["../../src/services/getScopedParams.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAE5D;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,QAAA,MAAM,eAAe,EAAE,uBAWtB,CAAC;AAEF,OAAO,EAAE,eAAe,EAAE,CAAC"}
1
+ {"version":3,"file":"getScopedParams.d.ts","sourceRoot":"","sources":["../../src/services/getScopedParams.ts"],"names":[],"mappings":"AAAA,KAAK,uBAAuB,GAAG,CAC7B,OAAO,EAAE,OAAO,EAChB,KAAK,CAAC,EAAE,MAAM,KACX,eAAe,CAAC;AACrB;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,QAAA,MAAM,eAAe,EAAE,uBAWtB,CAAC;AAEF,OAAO,EAAE,eAAe,EAAE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"httpDebug.d.ts","sourceRoot":"","sources":["../../src/services/httpDebug.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,iBAAS,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,GAAG,QAuBtD;AAED,OAAO,EAAE,SAAS,EAAE,CAAC"}
1
+ {"version":3,"file":"httpDebug.d.ts","sourceRoot":"","sources":["../../src/services/httpDebug.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,iBAAS,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,CAAC,EAAE,GAAG,QAuBtD;AAED,OAAO,EAAE,SAAS,EAAE,CAAC"}
@@ -1,4 +1,3 @@
1
- import { InboxFlowInstance } from "../config/inboxFlowInstance";
2
1
  import { getCaller } from "../services/getCaller";
3
2
  /**
4
3
  * Logs debug information to the console when in development mode or when the
@@ -0,0 +1,17 @@
1
+ type ApiSuccessResponse<T = any> = {
2
+ success: true;
3
+ status: number;
4
+ message: string;
5
+ response: T;
6
+ cause: null;
7
+ };
8
+ type ApiFailedResponse = {
9
+ success: false;
10
+ status: number;
11
+ message: string;
12
+ response: any;
13
+ cause: string | Error | null;
14
+ };
15
+ type ApiResponseDTO<T = any> = ApiSuccessResponse<T> | ApiFailedResponse;
16
+ export type { ApiResponseDTO };
17
+ //# sourceMappingURL=ApiResponseDTO.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ApiResponseDTO.d.ts","sourceRoot":"","sources":["../../src/types/ApiResponseDTO.ts"],"names":[],"mappings":"AAAA,KAAK,kBAAkB,CAAC,CAAC,GAAG,GAAG,IAAI;IACjC,OAAO,EAAE,IAAI,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,CAAC,CAAC;IACZ,KAAK,EAAE,IAAI,CAAC;CACb,CAAC;AAEF,KAAK,iBAAiB,GAAG;IACvB,OAAO,EAAE,KAAK,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,GAAG,CAAC;IACd,KAAK,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;CAC9B,CAAC;AAEF,KAAK,cAAc,CAAC,CAAC,GAAG,GAAG,IAAI,kBAAkB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC;AAEzE,YAAY,EAAE,cAAc,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,15 +1,12 @@
1
1
  {
2
2
  "name": "@arkyn/server",
3
- "version": "2.2.15",
3
+ "version": "3.0.1-beta.10",
4
4
  "author": "Arkyn | Lucas Gonçalves",
5
5
  "main": "./dist/bundle.js",
6
6
  "module": "./src/index.ts",
7
7
  "dependencies": {
8
8
  "@arkyn/shared": "*",
9
- "@aws-sdk/client-s3": "^3.782.0",
10
- "@mjackson/multipart-parser": "^0.8.2",
11
- "sharp": "^0.33.5",
12
- "zod": "^3.24.2"
9
+ "zod": ">=3.24.2"
13
10
  },
14
11
  "devDependencies": {
15
12
  "bun-types": "latest",
@@ -0,0 +1,118 @@
1
+ import { ArkynLogInstance } from "../config/arkynLogInstance";
2
+ import { httpDebug } from "../services/httpDebug";
3
+
4
+ type ConfigProps = {
5
+ rawUrl: string;
6
+ status: number;
7
+ method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
8
+ token: string | null;
9
+ elapsedTime: number;
10
+ requestHeaders: Record<string, string>;
11
+ requestBody: Record<string, string>;
12
+ queryParams: Record<string, string>;
13
+ responseHeaders: Record<string, string>;
14
+ responseBody: Record<string, string>;
15
+ };
16
+
17
+ /**
18
+ * Sends a request to the inbox flow API with the provided configuration.
19
+ *
20
+ * @param config - The configuration object for the request.
21
+ * @param config.rawUrl - The raw URL of the request.
22
+ * @param config.status - The HTTP status code associated with the request.
23
+ * @param config.method - The HTTP method used for the request. Can be "POST", "GET", "PUT", "DELETE", or "PATCH".
24
+ * @param config.token - The authentication token for the request.
25
+ * @param config.elapsedTime - The elapsed time for the request in milliseconds.
26
+ * @param config.requestHeaders - The headers sent with the request.
27
+ * @param config.requestBody - The body of the request, if applicable.
28
+ * @param config.queryParams - The query parameters for the request.
29
+ * @param config.responseHeaders - The headers received in the response.
30
+ * @param config.responseBody - The body of the response received.
31
+ *
32
+ * @remarks
33
+ * - This function retrieves the inbox flow configuration using `InboxFlowInstance.getInboxConfig()`.
34
+ * - If the configuration is not available, the function will return early without performing any action.
35
+ * - In a development environment (`NODE_ENV === "development"`), the function will also return early.
36
+ * - The request is sent as a POST request to the inbox API URL with the provided configuration details.
37
+ * - If an error occurs during the request, it will be logged using the `httpDebug` service.
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const config = {
42
+ * rawUrl: "https://example.com/api/data",
43
+ * status: 200,
44
+ * method: "GET",
45
+ * token: "auth-token-123",
46
+ * elapsedTime: "150ms",
47
+ * requestHeaders: { "Accept": "application/json", "Authorization": "Bearer token123" },
48
+ * requestBody: {},
49
+ * queryParams: { "page": "1", "limit": "10" },
50
+ * responseHeaders: { "Content-Type": "application/json" },
51
+ * responseBody: { "data": "example response" }
52
+ * };
53
+ *
54
+ * await arkynLogRequest(config);
55
+ * ```
56
+ */
57
+
58
+ async function arkynLogRequest(config: ConfigProps) {
59
+ const arkynInstance = ArkynLogInstance.getArkynConfig();
60
+ if (!arkynInstance) return;
61
+
62
+ const { arkynUserToken, arkynApiUrl } = arkynInstance;
63
+
64
+ const {
65
+ elapsedTime,
66
+ method,
67
+ queryParams,
68
+ requestBody,
69
+ requestHeaders,
70
+ responseBody,
71
+ responseHeaders,
72
+ status,
73
+ token,
74
+ rawUrl,
75
+ } = config;
76
+
77
+ // if (process.env.NODE_ENV === "development") return;
78
+
79
+ try {
80
+ const url = new URL(rawUrl);
81
+ let protocol: "HTTPS" | "HTTP" = "HTTPS";
82
+ if (url.protocol === "http:") protocol = "HTTP";
83
+
84
+ const body = JSON.stringify({
85
+ domainUrl: url.protocol + "//" + url.host,
86
+ pathnameUrl: url.pathname,
87
+ status,
88
+ protocol,
89
+ method,
90
+ trafficUserId: null,
91
+ elapsedTime,
92
+ requestHeaders,
93
+ requestBody,
94
+ queryParams,
95
+ responseHeaders,
96
+ responseBody,
97
+ });
98
+
99
+ await fetch(
100
+ arkynApiUrl.replace(
101
+ ":trafficSourceId",
102
+ arkynInstance.arkynTrafficSourceId
103
+ ),
104
+ {
105
+ method: "POST",
106
+ body,
107
+ headers: {
108
+ "Content-Type": "application/json",
109
+ Authorization: `Bearer ${arkynUserToken}`,
110
+ },
111
+ }
112
+ );
113
+ } catch (err) {
114
+ httpDebug("arkyn log error", "Error sending request", err);
115
+ }
116
+ }
117
+
118
+ export { arkynLogRequest };
@@ -1,4 +1,4 @@
1
- import type { ApiResponseDTO } from "@arkyn/types";
1
+ import type { ApiResponseDTO } from "../types/ApiResponseDTO";
2
2
  import { makeRequest } from "./makeRequest";
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import type { ApiResponseDTO } from "@arkyn/types";
1
+ import type { ApiResponseDTO } from "../types/ApiResponseDTO";
2
2
  import { makeRequest } from "./makeRequest";
3
3
 
4
4
  /**
@@ -1,6 +1,7 @@
1
- import type { ApiResponseDTO } from "@arkyn/types";
2
- import { InboxFlowInstance } from "../config/inboxFlowInstance";
3
- import { inboxFlowRequest } from "./inboxFlowRequest";
1
+ import { ArkynLogRequestMapper } from "../mapper/arkynLogRequestMapper";
2
+ import { httpDebug } from "../services/httpDebug";
3
+ import type { ApiResponseDTO } from "../types/ApiResponseDTO";
4
+ import { arkynLogRequest } from "./arkynLogRequest";
4
5
 
5
6
  /**
6
7
  * Makes an HTTP request using the Fetch API and returns a standardized response.
@@ -40,7 +41,7 @@ import { inboxFlowRequest } from "./inboxFlowRequest";
40
41
  async function makeRequest<T = any>(
41
42
  method: "POST" | "PUT" | "DELETE" | "PATCH" | "GET",
42
43
  url: string,
43
- headers: HeadersInit = {},
44
+ rawHeaders: HeadersInit = {},
44
45
  body?: any
45
46
  ): Promise<ApiResponseDTO<T>> {
46
47
  const successMessage = {
@@ -52,15 +53,16 @@ async function makeRequest<T = any>(
52
53
  };
53
54
 
54
55
  try {
56
+ const startTime = performance.now();
57
+
58
+ const headers = { ...rawHeaders, "Content-Type": "application/json" };
55
59
  const response = await fetch(url, {
56
60
  method,
57
- headers: {
58
- ...headers,
59
- "Content-Type": "application/json",
60
- },
61
+ headers,
61
62
  body: body ? JSON.stringify(body) : undefined,
62
63
  });
63
64
 
65
+ const elapsedTime = performance.now() - startTime;
64
66
  const status = response.status;
65
67
 
66
68
  let data: any = null;
@@ -70,14 +72,20 @@ async function makeRequest<T = any>(
70
72
  data = null;
71
73
  }
72
74
 
73
- inboxFlowRequest({
75
+ const logData = ArkynLogRequestMapper.handle({
76
+ elapsedTime,
74
77
  method,
78
+ queryParams: new URL(url).searchParams,
79
+ requestHeaders: headers,
80
+ requestBody: body,
81
+ responseBody: data,
82
+ responseHeaders: response.headers,
75
83
  status,
76
- request: JSON.stringify(response.headers),
77
- response: JSON.stringify(data),
78
- token: (headers as any)?.Authorization || "TOKEN_NOT_FOUND",
84
+ url,
79
85
  });
80
86
 
87
+ arkynLogRequest(logData);
88
+
81
89
  if (!response.ok) {
82
90
  return {
83
91
  success: false,
@@ -96,14 +104,7 @@ async function makeRequest<T = any>(
96
104
  cause: null,
97
105
  };
98
106
  } catch (err) {
99
- inboxFlowRequest({
100
- method,
101
- request: JSON.stringify(headers),
102
- response: String(err),
103
- status: 500,
104
- token: "TOKEN_NOT_FOUND",
105
- });
106
-
107
+ httpDebug("Network error or request failed", null, err);
107
108
  return {
108
109
  success: false,
109
110
  status: 0,
@@ -1,4 +1,4 @@
1
- import type { ApiResponseDTO } from "@arkyn/types";
1
+ import type { ApiResponseDTO } from "../types/ApiResponseDTO";
2
2
  import { makeRequest } from "./makeRequest";
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import type { ApiResponseDTO } from "@arkyn/types";
1
+ import type { ApiResponseDTO } from "../types/ApiResponseDTO";
2
2
  import { makeRequest } from "./makeRequest";
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import type { ApiResponseDTO } from "@arkyn/types";
1
+ import type { ApiResponseDTO } from "../types/ApiResponseDTO";
2
2
  import { makeRequest } from "./makeRequest";
3
3
 
4
4
  /**
@@ -0,0 +1,70 @@
1
+ type ArkynConfigProps = {
2
+ arkynTrafficSourceId: string;
3
+ arkynUserToken: string;
4
+ arkynApiUrl: string;
5
+ };
6
+
7
+ type SetArkynConfigProps = {
8
+ arkynTrafficSourceId: string;
9
+ arkynUserToken: string;
10
+ arkynLogBaseApiUrl?: string;
11
+ };
12
+
13
+ /**
14
+ * The `ArkynLogInstance` class manages the configuration for the arkyn flow.
15
+ * It allows you to set and retrieve the arkyn configuration, including the traffic source ID,
16
+ * user token, and API URL.
17
+ */
18
+
19
+ class ArkynLogInstance {
20
+ private static arkynConfig?: ArkynConfigProps;
21
+
22
+ /**
23
+ * Sets the configuration for the arkyn. This method initializes the arkyn configuration
24
+ * with the provided `arkynConfig` values. If the configuration has already been set,
25
+ * the method will return early without making any changes.
26
+ *
27
+ * @param arkynConfig - An object containing the arkyn configuration properties.
28
+ * @param arkynConfig.arkynTrafficSourceId - The key used to identify the arkyn.
29
+ * @param arkynConfig.arkynUserToken - The user token for authenticating with the arkyn.
30
+ * @param arkynConfig.arkynLogBaseApiUrl - (Optional) The API URL for the arkyn. If not provided,
31
+ * a default URL will be used.
32
+ */
33
+
34
+ static setArkynConfig(arkynConfig: SetArkynConfigProps) {
35
+ if (!!this.arkynConfig) return;
36
+
37
+ let defaultArkynURL = `https://logs-arkyn-flow-logs.vw6wo7.easypanel.host`;
38
+ let arkynLogBaseApiUrl = arkynConfig.arkynLogBaseApiUrl || defaultArkynURL;
39
+
40
+ arkynLogBaseApiUrl =
41
+ arkynLogBaseApiUrl + "/http-traffic-records/:trafficSourceId";
42
+
43
+ this.arkynConfig = {
44
+ arkynTrafficSourceId: arkynConfig.arkynTrafficSourceId,
45
+ arkynUserToken: arkynConfig.arkynUserToken,
46
+ arkynApiUrl: arkynLogBaseApiUrl,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Retrieves the current arkyn configuration for the ArkynLogInstance.
52
+ *
53
+ * @returns {ArkynConfigProps | undefined} The current arkyn configuration if set,
54
+ * or `undefined` if no configuration has been initialized.
55
+ */
56
+ static getArkynConfig(): ArkynConfigProps | undefined {
57
+ return this.arkynConfig;
58
+ }
59
+
60
+ /**
61
+ * Resets the arkyn configuration to `undefined`.
62
+ * This method can be used to clear the current configuration.
63
+ */
64
+
65
+ static resetArkynConfig() {
66
+ this.arkynConfig = undefined;
67
+ }
68
+ }
69
+
70
+ export { ArkynLogInstance };
package/src/index.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // config
2
2
  export { ApiInstance } from "./config/apiInstance";
3
- export { InboxFlowInstance } from "./config/inboxFlowInstance";
3
+ export { ArkynLogInstance } from "./config/arkynLogInstance";
4
4
 
5
5
  // http bad responses
6
6
  export { BadGateway } from "./http/badResponses/badGateway";
@@ -29,4 +29,3 @@ export { getCaller } from "./services/getCaller";
29
29
  export { getScopedParams } from "./services/getScopedParams";
30
30
  export { httpDebug } from "./services/httpDebug";
31
31
  export { SchemaValidator } from "./services/schemaValidator";
32
- export { sendFileToS3 } from "./services/sendFileToS3";
@@ -0,0 +1,73 @@
1
+ type InputProps = {
2
+ status: number;
3
+ url: string;
4
+ method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
5
+ requestHeaders: HeadersInit;
6
+ responseHeaders: HeadersInit;
7
+ requestBody: any;
8
+ elapsedTime: number;
9
+ responseBody: any;
10
+ queryParams: URLSearchParams;
11
+ };
12
+
13
+ type OutputProps = {
14
+ rawUrl: string;
15
+ status: number;
16
+ method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
17
+ token: string | null;
18
+ elapsedTime: number;
19
+ requestHeaders: Record<string, string>;
20
+ requestBody: Record<string, string>;
21
+ queryParams: Record<string, string>;
22
+ responseHeaders: Record<string, string>;
23
+ responseBody: any;
24
+ };
25
+
26
+ class ArkynLogRequestMapper {
27
+ private static mapHeaders(headers: HeadersInit): Record<string, string> {
28
+ if (headers instanceof Headers) {
29
+ return Object.fromEntries(headers.entries());
30
+ } else if (typeof headers === "object") {
31
+ return Object.entries(headers).reduce((acc, [key, value]) => {
32
+ if (typeof value === "string") {
33
+ acc[key] = value;
34
+ } else if (Array.isArray(value)) {
35
+ acc[key] = value.join(", ");
36
+ } else {
37
+ acc[key] = JSON.stringify(value);
38
+ }
39
+ return acc;
40
+ }, {} as Record<string, string>);
41
+ }
42
+ return {};
43
+ }
44
+
45
+ private static mapQueryParams(
46
+ queryParams: URLSearchParams
47
+ ): Record<string, string> {
48
+ const params: Record<string, string> = {};
49
+
50
+ queryParams.forEach((value, key) => {
51
+ params[key] = value;
52
+ });
53
+
54
+ return params;
55
+ }
56
+
57
+ static handle(props: InputProps): OutputProps {
58
+ return {
59
+ rawUrl: props.url,
60
+ status: props.status,
61
+ method: props.method,
62
+ token: null,
63
+ elapsedTime: props.elapsedTime,
64
+ requestHeaders: this.mapHeaders(props.requestHeaders),
65
+ requestBody: props.requestBody || null,
66
+ queryParams: this.mapQueryParams(props.queryParams),
67
+ responseHeaders: this.mapHeaders(props.responseHeaders),
68
+ responseBody: props.responseBody || null,
69
+ };
70
+ }
71
+ }
72
+
73
+ export { ArkynLogRequestMapper };
@@ -1,6 +1,7 @@
1
- import type { DecodeRequestBodyFunction } from "@arkyn/types";
2
1
  import { BadRequest } from "../http/badResponses/badRequest";
3
2
 
3
+ type DecodeRequestBodyFunction = (request: Request) => Promise<any>;
4
+
4
5
  /**
5
6
  * Decodes the body of an incoming request into a JavaScript object.
6
7
  *
@@ -1,4 +1,21 @@
1
- import type { FormParseProps, FormParseReturnType } from "@arkyn/types";
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;
2
19
 
3
20
  /**
4
21
  * Parses form data using a Zod schema and returns the result.
@@ -11,36 +11,70 @@ import path from "path";
11
11
  * - `functionName`: The name of the function that called the current function, or "Unknown function" if it cannot be determined.
12
12
  * - `callerInfo`: The file path of the caller relative to the project root, or "Unknown caller" if it cannot be determined.
13
13
  */
14
-
15
14
  function getCaller() {
16
15
  const projectRoot = process.cwd();
17
16
 
18
17
  const err = new Error();
19
18
  const stack = err.stack || "";
20
-
21
19
  const stackLines = stack.split("\n").map((line) => line.trim());
22
20
 
23
- const callerLine = stackLines[4] || "";
24
-
25
- let functionName = "unknown";
26
- let callerInfo = "unknown location";
27
-
28
- const functionMatch = callerLine.match(/at\s+([^\s]+)\s+\((.*)\)/);
29
- if (functionMatch) {
30
- functionName = functionMatch[1];
31
- callerInfo = functionMatch[2];
32
- } else {
33
- const locationMatch = callerLine.match(/at\s+(.*)/);
34
- if (locationMatch) {
35
- callerInfo = locationMatch[1];
36
- const pathParts = callerInfo.split("/");
37
- const lastPart = pathParts[pathParts.length - 1] || "";
38
- const fileParts = lastPart.split(":");
39
- functionName = fileParts[0] || "unknown";
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
+ }
40
58
  }
41
59
  }
42
60
 
43
- callerInfo = path.relative(projectRoot, callerInfo);
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
+ }
44
78
 
45
79
  return { functionName, callerInfo };
46
80
  }
@@ -1,5 +1,7 @@
1
- import type { GetScopedParamsFunction } from "@arkyn/types";
2
-
1
+ type GetScopedParamsFunction = (
2
+ request: Request,
3
+ scope?: string
4
+ ) => URLSearchParams;
3
5
  /**
4
6
  * Extracts and returns scoped query parameters from a request URL.
5
7
  *