@arkyn/server 3.0.1-beta.9 → 3.0.1-beta.91

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 (151) hide show
  1. package/README.md +368 -65
  2. package/dist/api/arkynLogRequest.d.ts +1 -1
  3. package/dist/api/arkynLogRequest.d.ts.map +1 -1
  4. package/dist/api/arkynLogRequest.js +24 -19
  5. package/dist/api/makeRequest.d.ts +1 -1
  6. package/dist/api/makeRequest.d.ts.map +1 -1
  7. package/dist/api/makeRequest.js +9 -7
  8. package/dist/bundle.js +1507 -0
  9. package/dist/bundle.umd.cjs +10 -0
  10. package/dist/http/badResponses/_badResponse.d.ts +11 -0
  11. package/dist/http/badResponses/_badResponse.d.ts.map +1 -0
  12. package/dist/http/badResponses/_badResponse.js +20 -0
  13. package/dist/http/badResponses/badGateway.d.ts +2 -1
  14. package/dist/http/badResponses/badGateway.d.ts.map +1 -1
  15. package/dist/http/badResponses/badGateway.js +9 -3
  16. package/dist/http/badResponses/badRequest.d.ts +2 -1
  17. package/dist/http/badResponses/badRequest.d.ts.map +1 -1
  18. package/dist/http/badResponses/badRequest.js +9 -3
  19. package/dist/http/badResponses/conflict.d.ts +2 -1
  20. package/dist/http/badResponses/conflict.d.ts.map +1 -1
  21. package/dist/http/badResponses/conflict.js +9 -3
  22. package/dist/http/badResponses/forbidden.d.ts +2 -1
  23. package/dist/http/badResponses/forbidden.d.ts.map +1 -1
  24. package/dist/http/badResponses/forbidden.js +9 -3
  25. package/dist/http/badResponses/notFound.d.ts +2 -1
  26. package/dist/http/badResponses/notFound.d.ts.map +1 -1
  27. package/dist/http/badResponses/notFound.js +9 -3
  28. package/dist/http/badResponses/notImplemented.d.ts +2 -1
  29. package/dist/http/badResponses/notImplemented.d.ts.map +1 -1
  30. package/dist/http/badResponses/notImplemented.js +9 -3
  31. package/dist/http/badResponses/serverError.d.ts +2 -1
  32. package/dist/http/badResponses/serverError.d.ts.map +1 -1
  33. package/dist/http/badResponses/serverError.js +9 -3
  34. package/dist/http/badResponses/unauthorized.d.ts +2 -1
  35. package/dist/http/badResponses/unauthorized.d.ts.map +1 -1
  36. package/dist/http/badResponses/unauthorized.js +9 -3
  37. package/dist/http/badResponses/unprocessableEntity.d.ts +3 -2
  38. package/dist/http/badResponses/unprocessableEntity.d.ts.map +1 -1
  39. package/dist/http/badResponses/unprocessableEntity.js +9 -4
  40. package/dist/http/successResponses/_successResponse.d.ts +22 -0
  41. package/dist/http/successResponses/_successResponse.d.ts.map +1 -0
  42. package/dist/http/successResponses/_successResponse.js +37 -0
  43. package/dist/http/successResponses/created.d.ts +2 -1
  44. package/dist/http/successResponses/created.d.ts.map +1 -1
  45. package/dist/http/successResponses/created.js +4 -1
  46. package/dist/http/successResponses/found.d.ts +2 -1
  47. package/dist/http/successResponses/found.d.ts.map +1 -1
  48. package/dist/http/successResponses/found.js +4 -1
  49. package/dist/http/successResponses/noContent.d.ts +2 -1
  50. package/dist/http/successResponses/noContent.d.ts.map +1 -1
  51. package/dist/http/successResponses/noContent.js +4 -1
  52. package/dist/http/successResponses/success.d.ts +2 -1
  53. package/dist/http/successResponses/success.d.ts.map +1 -1
  54. package/dist/http/successResponses/success.js +4 -1
  55. package/dist/http/successResponses/updated.d.ts +2 -1
  56. package/dist/http/successResponses/updated.d.ts.map +1 -1
  57. package/dist/http/successResponses/updated.js +4 -1
  58. package/dist/index.d.ts +13 -3
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +14 -4
  61. package/dist/{config/apiInstance.d.ts → services/apiService.d.ts} +25 -21
  62. package/dist/services/apiService.d.ts.map +1 -0
  63. package/dist/{config/apiInstance.js → services/apiService.js} +45 -23
  64. package/dist/{config/arkynLogInstance.d.ts → services/arkynLogService.d.ts} +11 -11
  65. package/dist/services/arkynLogService.d.ts.map +1 -0
  66. package/dist/{config/arkynLogInstance.js → services/arkynLogService.js} +8 -11
  67. package/dist/services/debugService.d.ts +54 -0
  68. package/dist/services/debugService.d.ts.map +1 -0
  69. package/dist/services/debugService.js +57 -0
  70. package/dist/services/flushDebugLogs.d.ts +8 -0
  71. package/dist/services/flushDebugLogs.d.ts.map +1 -0
  72. package/dist/services/flushDebugLogs.js +20 -0
  73. package/{src/services/formParse.ts → dist/services/formAsyncParse.d.ts} +20 -44
  74. package/dist/services/formAsyncParse.d.ts.map +1 -0
  75. package/dist/services/formAsyncParse.js +58 -0
  76. package/dist/services/formParse.d.ts +3 -3
  77. package/dist/services/formParse.d.ts.map +1 -1
  78. package/dist/services/formParse.js +7 -5
  79. package/dist/services/getCaller.d.ts.map +1 -1
  80. package/dist/services/getCaller.js +9 -14
  81. package/dist/services/measureRouteExecution.d.ts +3 -0
  82. package/dist/services/measureRouteExecution.d.ts.map +1 -0
  83. package/dist/services/measureRouteExecution.js +24 -0
  84. package/dist/services/schemaValidator.d.ts +148 -3
  85. package/dist/services/schemaValidator.d.ts.map +1 -1
  86. package/dist/services/schemaValidator.js +160 -4
  87. package/dist/validations/validateCep.d.ts +24 -0
  88. package/dist/validations/validateCep.d.ts.map +1 -0
  89. package/dist/validations/validateCep.js +33 -0
  90. package/dist/validations/validateCnpj.d.ts +22 -0
  91. package/dist/validations/validateCnpj.d.ts.map +1 -0
  92. package/dist/validations/validateCnpj.js +52 -0
  93. package/dist/validations/validateCpf.d.ts +24 -0
  94. package/dist/validations/validateCpf.d.ts.map +1 -0
  95. package/dist/validations/validateCpf.js +54 -0
  96. package/dist/validations/validateDate.d.ts +34 -0
  97. package/dist/validations/validateDate.d.ts.map +1 -0
  98. package/dist/validations/validateDate.js +73 -0
  99. package/dist/validations/validateEmail.d.ts +22 -0
  100. package/dist/validations/validateEmail.d.ts.map +1 -0
  101. package/dist/validations/validateEmail.js +123 -0
  102. package/dist/validations/validatePassword.d.ts +21 -0
  103. package/dist/validations/validatePassword.d.ts.map +1 -0
  104. package/dist/validations/validatePassword.js +34 -0
  105. package/dist/validations/validatePhone.d.ts +29 -0
  106. package/dist/validations/validatePhone.d.ts.map +1 -0
  107. package/dist/validations/validatePhone.js +44 -0
  108. package/dist/validations/validateRg.d.ts +22 -0
  109. package/dist/validations/validateRg.d.ts.map +1 -0
  110. package/dist/validations/validateRg.js +31 -0
  111. package/package.json +34 -18
  112. package/dist/config/apiInstance.d.ts.map +0 -1
  113. package/dist/config/arkynLogInstance.d.ts.map +0 -1
  114. package/dist/services/httpDebug.d.ts +0 -35
  115. package/dist/services/httpDebug.d.ts.map +0 -1
  116. package/dist/services/httpDebug.js +0 -52
  117. package/src/api/arkynLogRequest.ts +0 -125
  118. package/src/api/deleteRequest.ts +0 -22
  119. package/src/api/getRequest.ts +0 -20
  120. package/src/api/makeRequest.ts +0 -120
  121. package/src/api/patchRequest.ts +0 -22
  122. package/src/api/postRequest.ts +0 -22
  123. package/src/api/putRequest.ts +0 -22
  124. package/src/config/apiInstance.ts +0 -148
  125. package/src/config/arkynLogInstance.ts +0 -70
  126. package/src/http/badResponses/badGateway.ts +0 -63
  127. package/src/http/badResponses/badRequest.ts +0 -63
  128. package/src/http/badResponses/conflict.ts +0 -63
  129. package/src/http/badResponses/forbidden.ts +0 -63
  130. package/src/http/badResponses/notFound.ts +0 -63
  131. package/src/http/badResponses/notImplemented.ts +0 -63
  132. package/src/http/badResponses/serverError.ts +0 -63
  133. package/src/http/badResponses/unauthorized.ts +0 -63
  134. package/src/http/badResponses/unprocessableEntity.ts +0 -79
  135. package/src/http/successResponses/created.ts +0 -64
  136. package/src/http/successResponses/found.ts +0 -67
  137. package/src/http/successResponses/noContent.ts +0 -42
  138. package/src/http/successResponses/success.ts +0 -64
  139. package/src/http/successResponses/updated.ts +0 -64
  140. package/src/index.ts +0 -31
  141. package/src/mapper/arkynLogRequestMapper.ts +0 -73
  142. package/src/services/decodeErrorMessageFromRequest.ts +0 -36
  143. package/src/services/decodeRequestBody.ts +0 -43
  144. package/src/services/errorHandler.ts +0 -99
  145. package/src/services/getCaller.ts +0 -82
  146. package/src/services/getScopedParams.ts +0 -43
  147. package/src/services/httpDebug.ts +0 -61
  148. package/src/services/schemaValidator.ts +0 -66
  149. package/src/types/ApiResponseDTO.ts +0 -19
  150. package/tsconfig.json +0 -21
  151. package/vitest.config.ts +0 -5
@@ -1 +1 @@
1
- {"version":3,"file":"schemaValidator.d.ts","sourceRoot":"","sources":["../../src/services/schemaValidator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAiBhC,cAAM,eAAe,CAAC,CAAC,SAAS,MAAM;IAIxB,QAAQ,CAAC,MAAM,EAAE,CAAC;IAH9B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;gBAEE,MAAM,EAAE,CAAC;IAM9B,OAAO,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO;IAI3B,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAItE,QAAQ,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAQ/B,YAAY,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;CAoBtD;AAED,OAAO,EAAE,eAAe,EAAE,CAAC"}
1
+ {"version":3,"file":"schemaValidator.d.ts","sourceRoot":"","sources":["../../src/services/schemaValidator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAiBjC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,cAAM,eAAe,CAAC,CAAC,SAAS,OAAO;IASzB,QAAQ,CAAC,MAAM,EAAE,CAAC;IAR9B,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IAEnB;;;;OAIG;gBACkB,MAAM,EAAE,CAAC;IAM9B;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO;IAI3B;;;;;;;;;;;;;;;;;;OAkBG;IACH,YAAY,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAIzD;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,QAAQ,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAQ/B;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACH,YAAY,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;IAiBrD;;;;;;;;;;;;;;;;;;;;;;;;OAwBG;IACG,iBAAiB,CAAC,IAAI,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;CAgB1E;AAED,OAAO,EAAE,eAAe,EAAE,CAAC"}
@@ -1,30 +1,124 @@
1
- import { Schema, z } from "zod";
1
+ import { ZodType, z } from "zod";
2
2
  import { ServerError } from "../http/badResponses/serverError";
3
3
  import { UnprocessableEntity } from "../http/badResponses/unprocessableEntity";
4
+ import { formAsyncParse } from "./formAsyncParse";
4
5
  import { formParse } from "./formParse";
5
6
  import { getCaller } from "./getCaller";
6
- import { httpDebug } from "./httpDebug";
7
7
  function formatErrorMessage(error) {
8
8
  const title = "Error validating:";
9
9
  const lines = error.issues.map(({ path, message }) => `-> ${path.join(".")}: ${message}`);
10
10
  return [title, ...lines].join("\n");
11
11
  }
12
+ /**
13
+ * A schema validator class that provides multiple validation methods for Zod schemas.
14
+ *
15
+ * @template T - A type that extends ZodType.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * import { z } from "zod";
20
+ *
21
+ * const userSchema = z.object({
22
+ * name: z.string().min(1, "Name is required"),
23
+ * email: z.string().email("Invalid email"),
24
+ * age: z.number().min(18, "Must be at least 18")
25
+ * });
26
+ *
27
+ * const validator = new SchemaValidator(userSchema);
28
+ *
29
+ * // Check if data is valid without throwing
30
+ * const isValid = validator.isValid({ name: "John", email: "john@example.com", age: 25 });
31
+ *
32
+ * // Validate and throw ServerError on failure
33
+ * try {
34
+ * const validData = validator.validate({ name: "John", email: "john@example.com", age: 25 });
35
+ * } catch (error) {
36
+ * console.error(error.message);
37
+ * }
38
+ *
39
+ * // Form validation with UnprocessableEntity error
40
+ * try {
41
+ * const formData = validator.formValidate(requestBody);
42
+ * } catch (error) {
43
+ * // Returns structured error with fieldErrors for forms
44
+ * }
45
+ * ```
46
+ */
12
47
  class SchemaValidator {
13
48
  schema;
14
49
  functionName;
15
50
  callerInfo;
51
+ /**
52
+ * Creates a new SchemaValidator instance.
53
+ *
54
+ * @param {T} schema - The Zod schema to use for validation.
55
+ */
16
56
  constructor(schema) {
17
57
  this.schema = schema;
18
58
  const { callerInfo, functionName } = getCaller();
19
59
  this.callerInfo = callerInfo;
20
60
  this.functionName = functionName;
21
61
  }
62
+ /**
63
+ * Checks if the provided data is valid according to the schema without throwing errors.
64
+ *
65
+ * @param {any} data - The data to validate.
66
+ *
67
+ * @returns {boolean} True if the data is valid, false otherwise.
68
+ *
69
+ * @example
70
+ * ```typescript
71
+ * const validator = new SchemaValidator(userSchema);
72
+ * const isValid = validator.isValid({ name: "John", email: "invalid-email" });
73
+ * console.log(isValid); // false
74
+ * ```
75
+ */
22
76
  isValid(data) {
23
77
  return this.schema.safeParse(data).success;
24
78
  }
79
+ /**
80
+ * Safely validates data and returns the complete parse result without throwing errors.
81
+ *
82
+ * @param {any} data - The data to validate.
83
+ *
84
+ * @returns {z.ZodSafeParseResult<z.infer<T>>} The Zod safe parse result containing success status and data or error.
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * const validator = new SchemaValidator(userSchema);
89
+ * const result = validator.safeValidate({ name: "", email: "john@example.com" });
90
+ *
91
+ * if (result.success) {
92
+ * console.log(result.data); // Validated data
93
+ * } else {
94
+ * console.log(result.error.issues); // Validation errors
95
+ * }
96
+ * ```
97
+ */
25
98
  safeValidate(data) {
26
99
  return this.schema.safeParse(data);
27
100
  }
101
+ /**
102
+ * Validates data and returns the parsed result, throwing a ServerError on validation failure.
103
+ *
104
+ * @param {any} data - The data to validate.
105
+ *
106
+ * @returns {z.infer<T>} The validated and parsed data.
107
+ *
108
+ * @throws {ServerError} When validation fails, with a formatted error message.
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * const validator = new SchemaValidator(userSchema);
113
+ *
114
+ * try {
115
+ * const validUser = validator.validate({ name: "John", email: "john@example.com", age: 25 });
116
+ * console.log(validUser); // { name: "John", email: "john@example.com", age: 25 }
117
+ * } catch (error) {
118
+ * console.error(error.message); // "Error validating:\n-> name: String must contain at least 1 character(s)"
119
+ * }
120
+ * ```
121
+ */
28
122
  validate(data) {
29
123
  try {
30
124
  return this.schema.parse(data);
@@ -33,17 +127,79 @@ class SchemaValidator {
33
127
  throw new ServerError(formatErrorMessage(error));
34
128
  }
35
129
  }
130
+ /**
131
+ * Validates form data and returns the parsed result, throwing an UnprocessableEntity error on validation failure.
132
+ * This method is specifically designed for form validation in web applications.
133
+ *
134
+ * @param {any} data - The form data to validate.
135
+ * @param {string} [message] - Optional custom error message.
136
+ *
137
+ * @returns {z.infer<T>} The validated and parsed form data.
138
+ *
139
+ * @throws {UnprocessableEntity} When validation fails, with structured field errors for form handling.
140
+ *
141
+ * @example
142
+ * ```typescript
143
+ * const validator = new SchemaValidator(userSchema);
144
+ *
145
+ * try {
146
+ * const validFormData = validator.formValidate(requestBody, "User data is invalid");
147
+ * console.log(validFormData);
148
+ * } catch (error) {
149
+ * // UnprocessableEntity with fieldErrors, fields, and scrollTo data
150
+ * console.log(error.fieldErrors); // { name: "Name is required", email: "Invalid email" }
151
+ * console.log(error.data.scrollTo); // "name" (first error field)
152
+ * }
153
+ * ```
154
+ */
36
155
  formValidate(data, message) {
37
156
  const formParsed = formParse([data, this.schema]);
38
157
  if (!formParsed.success) {
39
- httpDebug("UnprocessableEntity", formParsed);
40
158
  const firstErrorKey = Object.keys(formParsed.fieldErrors)[0];
41
159
  throw new UnprocessableEntity({
42
160
  fields: formParsed.fields,
43
161
  fieldErrors: formParsed.fieldErrors,
44
162
  data: { scrollTo: firstErrorKey },
45
163
  message,
46
- }, false);
164
+ });
165
+ }
166
+ return formParsed.data;
167
+ }
168
+ /**
169
+ * Asynchronously validates form data and returns the parsed result, throwing an UnprocessableEntity error on validation failure.
170
+ * This method is the async version of formValidate, designed for form validation with async schemas.
171
+ *
172
+ * @param {any} data - The form data to validate.
173
+ * @param {string} [message] - Optional custom error message.
174
+ *
175
+ * @returns {Promise<z.infer<T>>} A promise that resolves to the validated and parsed form data.
176
+ *
177
+ * @throws {UnprocessableEntity} When validation fails, with structured field errors for form handling.
178
+ *
179
+ * @example
180
+ * ```typescript
181
+ * const validator = new SchemaValidator(userSchemaWithAsyncValidation);
182
+ *
183
+ * try {
184
+ * const validFormData = await validator.formAsyncValidate(requestBody, "User data is invalid");
185
+ * console.log(validFormData);
186
+ * } catch (error) {
187
+ * // UnprocessableEntity with fieldErrors, fields, and scrollTo data
188
+ * console.log(error.fieldErrors); // { name: "Name is required", email: "Invalid email" }
189
+ * console.log(error.data.scrollTo); // "name" (first error field)
190
+ * }
191
+ * ```
192
+ */
193
+ async formAsyncValidate(data, message) {
194
+ const formParsed = await formAsyncParse([data, this.schema]);
195
+ if (!formParsed.success) {
196
+ const firstErrorKey = Object.keys(formParsed.fieldErrors)[0];
197
+ throw new UnprocessableEntity({
198
+ fields: formParsed.fields,
199
+ fieldErrors: formParsed.fieldErrors,
200
+ data: { scrollTo: firstErrorKey },
201
+ message,
202
+ });
47
203
  }
48
204
  return formParsed.data;
49
205
  }
@@ -0,0 +1,24 @@
1
+ type ValidateCepFunction = (rawCep: string) => boolean;
2
+ /**
3
+ * Removes all non-digit characters from the CEP.
4
+ * @param cep - Raw CEP string.
5
+ * @returns Only numeric characters.
6
+ */
7
+ /**
8
+ * Validates a Brazilian CEP (Código de Endereçamento Postal).
9
+ *
10
+ * A valid CEP has 8 numeric digits.
11
+ *
12
+ * @param rawCep - CEP string, may include formatting (e.g., "12345-678").
13
+ * @returns `true` if the CEP is valid, otherwise `false`.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * validateCep("12345-678"); // true
18
+ * validateCep("12345678"); // true
19
+ * validateCep("ABCDE-123"); // false
20
+ * ```
21
+ */
22
+ declare const validateCep: ValidateCepFunction;
23
+ export { validateCep };
24
+ //# sourceMappingURL=validateCep.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateCep.d.ts","sourceRoot":"","sources":["../../src/validations/validateCep.ts"],"names":[],"mappings":"AAEA,KAAK,mBAAmB,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC;AAEvD;;;;GAIG;AAEH;;;;;;;;;;;;;;GAcG;AAEH,QAAA,MAAM,WAAW,EAAE,mBAYlB,CAAC;AAEF,OAAO,EAAE,WAAW,EAAE,CAAC"}
@@ -0,0 +1,33 @@
1
+ import { removeNonNumeric } from "@arkyn/shared";
2
+ /**
3
+ * Removes all non-digit characters from the CEP.
4
+ * @param cep - Raw CEP string.
5
+ * @returns Only numeric characters.
6
+ */
7
+ /**
8
+ * Validates a Brazilian CEP (Código de Endereçamento Postal).
9
+ *
10
+ * A valid CEP has 8 numeric digits.
11
+ *
12
+ * @param rawCep - CEP string, may include formatting (e.g., "12345-678").
13
+ * @returns `true` if the CEP is valid, otherwise `false`.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * validateCep("12345-678"); // true
18
+ * validateCep("12345678"); // true
19
+ * validateCep("ABCDE-123"); // false
20
+ * ```
21
+ */
22
+ const validateCep = (rawCep) => {
23
+ if (!rawCep)
24
+ return false;
25
+ const validFormat = /^[0-9-]+$/.test(rawCep);
26
+ if (!validFormat)
27
+ return false;
28
+ const cep = removeNonNumeric(rawCep);
29
+ const CEP_LENGTH = 8;
30
+ const isOnlyDigits = /^\d{8}$/.test(cep);
31
+ return cep.length === CEP_LENGTH && isOnlyDigits;
32
+ };
33
+ export { validateCep };
@@ -0,0 +1,22 @@
1
+ type ValidateCnpjFunction = (rawCnpj: string) => boolean;
2
+ /**
3
+ * Validates a Brazilian CNPJ (Cadastro Nacional da Pessoa Jurídica) number.
4
+ *
5
+ * This function performs:
6
+ * - Sanitization (removes non-digit characters).
7
+ * - Length check (must be 14 digits).
8
+ * - Repeating digits check (invalid if all digits are the same).
9
+ * - Verifies the two check digits with the proper weights.
10
+ *
11
+ * @param rawCnpj - CNPJ string, possibly formatted.
12
+ * @returns `true` if valid, otherwise `false`.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * validateCnpj("12.345.678/0001-95"); // false
17
+ * validateCnpj("11.444.777/0001-61"); // true
18
+ * ```
19
+ */
20
+ declare const validateCnpj: ValidateCnpjFunction;
21
+ export { validateCnpj };
22
+ //# sourceMappingURL=validateCnpj.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateCnpj.d.ts","sourceRoot":"","sources":["../../src/validations/validateCnpj.ts"],"names":[],"mappings":"AAEA,KAAK,oBAAoB,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC;AAyBzD;;;;;;;;;;;;;;;;;GAiBG;AAEH,QAAA,MAAM,YAAY,EAAE,oBAgBnB,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1,52 @@
1
+ import { removeNonNumeric } from "@arkyn/shared";
2
+ function isInvalidLength(cnpj) {
3
+ const CNPJ_LENGTH = 14;
4
+ return cnpj.length !== CNPJ_LENGTH;
5
+ }
6
+ function hasAllDigitsEqual(cnpj) {
7
+ const [firstDigit] = cnpj;
8
+ return [...cnpj].every((digit) => digit === firstDigit);
9
+ }
10
+ function calculateDigit(cnpj, multipliers) {
11
+ let total = 0;
12
+ for (let i = 0; i < multipliers.length; i++) {
13
+ total += parseInt(cnpj[i]) * multipliers[i];
14
+ }
15
+ const rest = total % 11;
16
+ return rest < 2 ? 0 : 11 - rest;
17
+ }
18
+ function extractDigit(cnpj) {
19
+ return cnpj.slice(12);
20
+ }
21
+ /**
22
+ * Validates a Brazilian CNPJ (Cadastro Nacional da Pessoa Jurídica) number.
23
+ *
24
+ * This function performs:
25
+ * - Sanitization (removes non-digit characters).
26
+ * - Length check (must be 14 digits).
27
+ * - Repeating digits check (invalid if all digits are the same).
28
+ * - Verifies the two check digits with the proper weights.
29
+ *
30
+ * @param rawCnpj - CNPJ string, possibly formatted.
31
+ * @returns `true` if valid, otherwise `false`.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * validateCnpj("12.345.678/0001-95"); // false
36
+ * validateCnpj("11.444.777/0001-61"); // true
37
+ * ```
38
+ */
39
+ const validateCnpj = (rawCnpj) => {
40
+ if (!rawCnpj)
41
+ return false;
42
+ const cnpj = removeNonNumeric(rawCnpj);
43
+ if (isInvalidLength(cnpj))
44
+ return false;
45
+ if (hasAllDigitsEqual(cnpj))
46
+ return false;
47
+ const base = cnpj.slice(0, 12);
48
+ const digit1 = calculateDigit(base, [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]);
49
+ const digit2 = calculateDigit(base + digit1, [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]);
50
+ return extractDigit(cnpj) === `${digit1}${digit2}`;
51
+ };
52
+ export { validateCnpj };
@@ -0,0 +1,24 @@
1
+ type ValidateCpfFunction = (rawCpf: string) => boolean;
2
+ /**
3
+ * Validates a Brazilian CPF (Cadastro de Pessoas Físicas) number.
4
+ *
5
+ * The CPF is a unique identifier assigned to Brazilian citizens and residents.
6
+ * This function checks if the provided CPF is valid by performing the following steps:
7
+ * - Removes any non-digit characters from the input.
8
+ * - Verifies if the CPF has the correct length (11 digits).
9
+ * - Ensures that all digits are not the same (e.g., "111.111.111-11" is invalid).
10
+ * - Calculates the first and second verification digits using the CPF algorithm.
11
+ * - Compares the calculated verification digits with the ones provided in the CPF.
12
+ *
13
+ * @param rawCpf - The raw CPF string, which may include formatting characters (e.g., dots or dashes).
14
+ * @returns `true` if the CPF is valid, otherwise `false`.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * validateCpf("123.456.789-09"); // false
19
+ * validateCpf("111.444.777-35"); // true
20
+ * ```
21
+ */
22
+ declare const validateCpf: ValidateCpfFunction;
23
+ export { validateCpf };
24
+ //# sourceMappingURL=validateCpf.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateCpf.d.ts","sourceRoot":"","sources":["../../src/validations/validateCpf.ts"],"names":[],"mappings":"AAEA,KAAK,mBAAmB,GAAG,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC;AAyBvD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,QAAA,MAAM,WAAW,EAAE,mBAWlB,CAAC;AAEF,OAAO,EAAE,WAAW,EAAE,CAAC"}
@@ -0,0 +1,54 @@
1
+ import { removeNonNumeric } from "@arkyn/shared";
2
+ function isInvalidLength(cpf) {
3
+ const CPF_LENGTH = 11;
4
+ return cpf.length !== CPF_LENGTH;
5
+ }
6
+ function hasAllDigitsEqual(cpf) {
7
+ const [firstCpfDigit] = cpf;
8
+ return [...cpf].every((digit) => digit === firstCpfDigit);
9
+ }
10
+ function calculateDigit(cpf, factor) {
11
+ let total = 0;
12
+ for (const digit of cpf) {
13
+ if (factor > 1)
14
+ total += parseInt(digit) * factor--;
15
+ }
16
+ const rest = total % 11;
17
+ return rest < 2 ? 0 : 11 - rest;
18
+ }
19
+ function extractDigit(cpf) {
20
+ return cpf.slice(9);
21
+ }
22
+ /**
23
+ * Validates a Brazilian CPF (Cadastro de Pessoas Físicas) number.
24
+ *
25
+ * The CPF is a unique identifier assigned to Brazilian citizens and residents.
26
+ * This function checks if the provided CPF is valid by performing the following steps:
27
+ * - Removes any non-digit characters from the input.
28
+ * - Verifies if the CPF has the correct length (11 digits).
29
+ * - Ensures that all digits are not the same (e.g., "111.111.111-11" is invalid).
30
+ * - Calculates the first and second verification digits using the CPF algorithm.
31
+ * - Compares the calculated verification digits with the ones provided in the CPF.
32
+ *
33
+ * @param rawCpf - The raw CPF string, which may include formatting characters (e.g., dots or dashes).
34
+ * @returns `true` if the CPF is valid, otherwise `false`.
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * validateCpf("123.456.789-09"); // false
39
+ * validateCpf("111.444.777-35"); // true
40
+ * ```
41
+ */
42
+ const validateCpf = (rawCpf) => {
43
+ if (!rawCpf)
44
+ return false;
45
+ const cpf = removeNonNumeric(rawCpf);
46
+ if (isInvalidLength(cpf))
47
+ return false;
48
+ if (hasAllDigitsEqual(cpf))
49
+ return false;
50
+ const digit1 = calculateDigit(cpf, 10);
51
+ const digit2 = calculateDigit(cpf, 11);
52
+ return extractDigit(cpf) === `${digit1}${digit2}`;
53
+ };
54
+ export { validateCpf };
@@ -0,0 +1,34 @@
1
+ type ValidateDateConfig = {
2
+ inputFormat?: "DD/MM/YYYY" | "MM-DD-YYYY" | "YYYY-MM-DD";
3
+ minYear?: number;
4
+ maxYear?: number;
5
+ };
6
+ type ValidateDateFunction = (rawDate: string, config?: ValidateDateConfig) => boolean;
7
+ /**
8
+ * Validates a date string based on the provided format and configuration.
9
+ *
10
+ * @param rawDate - The date string to validate.
11
+ * @param config - Optional configuration object to customize validation.
12
+ * @param config.inputFormat - The expected format of the input date.
13
+ * Supported formats are "DD/MM/YYYY", "MM-DD-YYYY", and "YYYY-MM-DD".
14
+ * Defaults to "DD/MM/YYYY".
15
+ * @param config.minYear - The minimum allowed year for the date. Defaults to 1900.
16
+ * @param config.maxYear - The maximum allowed year for the date. Defaults to 3000.
17
+ *
18
+ * @returns `true` if the date is valid according to the specified format and configuration, otherwise `false`.
19
+ *
20
+ * @throws {Error} If an invalid date format is provided in the configuration.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * validateDate("31/12/2023"); // true
25
+ * validateDate("12-31-2023", { inputFormat: "MM-DD-YYYY" }); // true
26
+ * validateDate("2023-12-31", { inputFormat: "YYYY-MM-DD", minYear: 2000, maxYear: 2100 }); // true
27
+ * validateDate("29/02/2024", { inputFormat: "DD/MM/YYYY" }); // true (leap year)
28
+ * validateDate("29/02/2023", { inputFormat: "DD/MM/YYYY" }); // false (not a leap year)
29
+ * validateDate("31/04/2023", { inputFormat: "DD/MM/YYYY" }); // false (April has 30 days)
30
+ * ```
31
+ */
32
+ declare const validateDate: ValidateDateFunction;
33
+ export { validateDate };
34
+ //# sourceMappingURL=validateDate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateDate.d.ts","sourceRoot":"","sources":["../../src/validations/validateDate.ts"],"names":[],"mappings":"AAAA,KAAK,kBAAkB,GAAG;IACxB,WAAW,CAAC,EAAE,YAAY,GAAG,YAAY,GAAG,YAAY,CAAC;IACzD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,KAAK,oBAAoB,GAAG,CAC1B,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,kBAAkB,KACxB,OAAO,CAAC;AAEb;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,QAAA,MAAM,YAAY,EAAE,oBA8CnB,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC"}
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Validates a date string based on the provided format and configuration.
3
+ *
4
+ * @param rawDate - The date string to validate.
5
+ * @param config - Optional configuration object to customize validation.
6
+ * @param config.inputFormat - The expected format of the input date.
7
+ * Supported formats are "DD/MM/YYYY", "MM-DD-YYYY", and "YYYY-MM-DD".
8
+ * Defaults to "DD/MM/YYYY".
9
+ * @param config.minYear - The minimum allowed year for the date. Defaults to 1900.
10
+ * @param config.maxYear - The maximum allowed year for the date. Defaults to 3000.
11
+ *
12
+ * @returns `true` if the date is valid according to the specified format and configuration, otherwise `false`.
13
+ *
14
+ * @throws {Error} If an invalid date format is provided in the configuration.
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * validateDate("31/12/2023"); // true
19
+ * validateDate("12-31-2023", { inputFormat: "MM-DD-YYYY" }); // true
20
+ * validateDate("2023-12-31", { inputFormat: "YYYY-MM-DD", minYear: 2000, maxYear: 2100 }); // true
21
+ * validateDate("29/02/2024", { inputFormat: "DD/MM/YYYY" }); // true (leap year)
22
+ * validateDate("29/02/2023", { inputFormat: "DD/MM/YYYY" }); // false (not a leap year)
23
+ * validateDate("31/04/2023", { inputFormat: "DD/MM/YYYY" }); // false (April has 30 days)
24
+ * ```
25
+ */
26
+ const validateDate = (rawDate, config) => {
27
+ let day, month, year;
28
+ const inputFormat = config?.inputFormat || "DD/MM/YYYY";
29
+ const minYear = config?.minYear || 1900;
30
+ const maxYear = config?.maxYear || 3000;
31
+ if (inputFormat === "DD/MM/YYYY") {
32
+ const dateRegex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
33
+ if (!dateRegex.test(rawDate))
34
+ return false;
35
+ [, day, month, year] = rawDate.match(dateRegex) || [];
36
+ }
37
+ else if (inputFormat === "MM-DD-YYYY") {
38
+ const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
39
+ if (!dateRegex.test(rawDate))
40
+ return false;
41
+ [, month, day, year] = rawDate.match(dateRegex) || [];
42
+ }
43
+ else if (inputFormat === "YYYY-MM-DD") {
44
+ const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
45
+ if (!dateRegex.test(rawDate))
46
+ return false;
47
+ [, year, month, day] = rawDate.match(dateRegex) || [];
48
+ }
49
+ else {
50
+ throw new Error("Invalid date format");
51
+ }
52
+ const dayNum = parseInt(day, 10);
53
+ const monthNum = parseInt(month, 10);
54
+ const yearNum = parseInt(year, 10);
55
+ if (dayNum < 1 || dayNum > 31)
56
+ return false;
57
+ if (monthNum < 1 || monthNum > 12)
58
+ return false;
59
+ const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
60
+ if (monthNum === 2) {
61
+ const isLeapYear = (yearNum % 4 === 0 && yearNum % 100 !== 0) || yearNum % 400 === 0;
62
+ if (dayNum > (isLeapYear ? 29 : 28))
63
+ return false;
64
+ }
65
+ else if (dayNum > daysInMonth[monthNum - 1]) {
66
+ return false;
67
+ }
68
+ if (yearNum < minYear || yearNum > maxYear)
69
+ return false;
70
+ const isValidDate = new Date(yearNum, monthNum - 1, dayNum).getDate() === dayNum;
71
+ return isValidDate;
72
+ };
73
+ export { validateDate };
@@ -0,0 +1,22 @@
1
+ type ValidateEmailFunction = (rawEmail: string) => Promise<boolean>;
2
+ /**
3
+ * Validates if an email address is valid in all possible ways, including DNS validation.
4
+ *
5
+ * This function performs comprehensive email validation by:
6
+ * - Checking basic email format and syntax
7
+ * - Validating advanced RFC 5322 compliance rules
8
+ * - Verifying that the domain has valid MX or A records in DNS
9
+ *
10
+ * @param rawEmail - The email address string to validate
11
+ * @returns A promise that resolves to `true` if the email is valid (including DNS), otherwise `false`
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * await validateEmail("user@gmail.com"); // true
16
+ * await validateEmail("user@gmil.com"); // false (invalid domain)
17
+ * await validateEmail("invalid-email"); // false (invalid format)
18
+ * ```
19
+ */
20
+ declare const validateEmail: ValidateEmailFunction;
21
+ export { validateEmail };
22
+ //# sourceMappingURL=validateEmail.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validateEmail.d.ts","sourceRoot":"","sources":["../../src/validations/validateEmail.ts"],"names":[],"mappings":"AAEA,KAAK,qBAAqB,GAAG,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAmGpE;;;;;;;;;;;;;;;;;GAiBG;AAEH,QAAA,MAAM,aAAa,EAAE,qBAYpB,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,CAAC"}