@arkyn/shared 1.4.57 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/dist/formats/formatBrazilianDateHour.d.ts +3 -0
  2. package/dist/formats/formatBrazilianDateHour.d.ts.map +1 -0
  3. package/dist/formats/formatBrazilianDateHour.js +12 -0
  4. package/dist/formats/formatBrazilianDateToDate.d.ts +3 -0
  5. package/dist/formats/formatBrazilianDateToDate.d.ts.map +1 -0
  6. package/dist/formats/formatBrazilianDateToDate.js +9 -0
  7. package/dist/formats/formatDateHour.d.ts +3 -0
  8. package/dist/formats/formatDateHour.d.ts.map +1 -0
  9. package/dist/formats/formatDateHour.js +11 -0
  10. package/dist/formats/formatJsonObject.d.ts +1 -31
  11. package/dist/formats/formatJsonObject.d.ts.map +1 -1
  12. package/dist/formats/formatJsonObject.js +26 -67
  13. package/dist/formats/formatJsonString.d.ts +1 -37
  14. package/dist/formats/formatJsonString.d.ts.map +1 -1
  15. package/dist/formats/formatJsonString.js +4 -38
  16. package/dist/formats/formatToBRL.d.ts +3 -0
  17. package/dist/formats/formatToBRL.d.ts.map +1 -0
  18. package/dist/formats/formatToBRL.js +8 -0
  19. package/dist/formats/formatToCNPJ.d.ts +3 -0
  20. package/dist/formats/formatToCNPJ.d.ts.map +1 -0
  21. package/dist/formats/formatToCNPJ.js +9 -0
  22. package/dist/formats/formatToCPF.d.ts +3 -0
  23. package/dist/formats/formatToCPF.d.ts.map +1 -0
  24. package/dist/formats/formatToCPF.js +9 -0
  25. package/dist/formats/formatToCep.d.ts +1 -27
  26. package/dist/formats/formatToCep.d.ts.map +1 -1
  27. package/dist/formats/formatToCep.js +6 -31
  28. package/dist/formats/formatToCpfCnpj.d.ts +1 -22
  29. package/dist/formats/formatToCpfCnpj.d.ts.map +1 -1
  30. package/dist/formats/formatToCpfCnpj.js +7 -27
  31. package/dist/formats/formatToEllipsis.d.ts +1 -14
  32. package/dist/formats/formatToEllipsis.d.ts.map +1 -1
  33. package/dist/formats/formatToEllipsis.js +3 -20
  34. package/dist/formats/formatToHiddenDigits.d.ts +2 -30
  35. package/dist/formats/formatToHiddenDigits.d.ts.map +1 -1
  36. package/dist/formats/formatToHiddenDigits.js +3 -49
  37. package/dist/formats/formatToPhone.d.ts +1 -32
  38. package/dist/formats/formatToPhone.d.ts.map +1 -1
  39. package/dist/formats/formatToPhone.js +6 -128
  40. package/dist/generators/generateColorByString.d.ts +1 -13
  41. package/dist/generators/generateColorByString.d.ts.map +1 -1
  42. package/dist/generators/generateColorByString.js +4 -15
  43. package/dist/generators/generateId.d.ts +4 -26
  44. package/dist/generators/generateId.d.ts.map +1 -1
  45. package/dist/generators/generateId.js +5 -11
  46. package/dist/generators/generateSlug.d.ts +1 -15
  47. package/dist/generators/generateSlug.d.ts.map +1 -1
  48. package/dist/generators/generateSlug.js +2 -16
  49. package/dist/index.d.ts +10 -7
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +15 -7
  52. package/dist/parsers/parseToCharacters.d.ts +17 -0
  53. package/dist/parsers/parseToCharacters.d.ts.map +1 -0
  54. package/dist/parsers/parseToCharacters.js +13 -0
  55. package/dist/services/calculateCardInstallment.d.ts +5 -31
  56. package/dist/services/calculateCardInstallment.d.ts.map +1 -1
  57. package/dist/services/calculateCardInstallment.js +11 -52
  58. package/dist/services/maskSensitiveData.d.ts +1 -24
  59. package/dist/services/maskSensitiveData.d.ts.map +1 -1
  60. package/dist/services/maskSensitiveData.js +2 -24
  61. package/dist/services/range.d.ts +4 -0
  62. package/dist/services/range.d.ts.map +1 -0
  63. package/dist/services/range.js +9 -0
  64. package/dist/services/truncateLargeFields.d.ts +1 -30
  65. package/dist/services/truncateLargeFields.d.ts.map +1 -1
  66. package/dist/services/truncateLargeFields.js +6 -34
  67. package/dist/validations/regex.d.ts +15 -0
  68. package/dist/validations/regex.d.ts.map +1 -0
  69. package/dist/validations/regex.js +25 -0
  70. package/dist/validations/validateCPF.d.ts +3 -0
  71. package/dist/validations/validateCPF.d.ts.map +1 -0
  72. package/dist/validations/validateCPF.js +36 -0
  73. package/dist/validations/validateDate.d.ts +6 -27
  74. package/dist/validations/validateDate.d.ts.map +1 -1
  75. package/dist/validations/validateDate.js +6 -32
  76. package/dist/validations/validatePhone.d.ts +1 -27
  77. package/dist/validations/validatePhone.d.ts.map +1 -1
  78. package/dist/validations/validatePhone.js +2 -27
  79. package/package.json +2 -4
  80. package/src/formats/formatBrazilianDateHour.ts +17 -0
  81. package/src/formats/formatBrazilianDateToDate.ts +13 -0
  82. package/src/formats/formatDateHour.ts +15 -0
  83. package/src/formats/formatJsonObject.ts +26 -68
  84. package/src/formats/formatJsonString.ts +4 -40
  85. package/src/formats/formatToBRL.ts +10 -0
  86. package/src/formats/formatToCNPJ.ts +10 -0
  87. package/src/formats/formatToCPF.ts +10 -0
  88. package/src/formats/formatToCep.ts +7 -35
  89. package/src/formats/formatToCpfCnpj.ts +7 -31
  90. package/src/formats/formatToEllipsis.ts +3 -23
  91. package/src/formats/formatToHiddenDigits.ts +7 -75
  92. package/src/formats/formatToPhone.ts +6 -156
  93. package/src/generators/generateColorByString.ts +4 -18
  94. package/src/generators/generateId.ts +5 -36
  95. package/src/generators/generateSlug.ts +2 -17
  96. package/src/index.ts +15 -7
  97. package/src/parsers/parseToCharacters.ts +34 -0
  98. package/src/services/calculateCardInstallment.ts +12 -57
  99. package/src/services/maskSensitiveData.ts +4 -29
  100. package/src/services/range.ts +15 -0
  101. package/src/services/truncateLargeFields.ts +6 -40
  102. package/src/validations/regex.ts +41 -0
  103. package/src/validations/validateCPF.ts +38 -0
  104. package/src/validations/validateDate.ts +11 -33
  105. package/src/validations/validatePhone.ts +2 -29
  106. package/tsconfig.json +1 -1
  107. package/dist/formats/formatDate.d.ts +0 -43
  108. package/dist/formats/formatDate.d.ts.map +0 -1
  109. package/dist/formats/formatDate.js +0 -77
  110. package/dist/formats/formatToCnpj.d.ts +0 -30
  111. package/dist/formats/formatToCnpj.d.ts.map +0 -1
  112. package/dist/formats/formatToCnpj.js +0 -35
  113. package/dist/formats/formatToCpf.d.ts +0 -30
  114. package/dist/formats/formatToCpf.d.ts.map +0 -1
  115. package/dist/formats/formatToCpf.js +0 -35
  116. package/dist/formats/formatToCurrency.d.ts +0 -29
  117. package/dist/formats/formatToCurrency.d.ts.map +0 -1
  118. package/dist/formats/formatToCurrency.js +0 -41
  119. package/dist/regex/index.d.ts +0 -6
  120. package/dist/regex/index.d.ts.map +0 -1
  121. package/dist/regex/index.js +0 -4
  122. package/dist/services/removeCurrencySymbols.d.ts +0 -20
  123. package/dist/services/removeCurrencySymbols.d.ts.map +0 -1
  124. package/dist/services/removeCurrencySymbols.js +0 -23
  125. package/dist/services/removeNonNumeric.d.ts +0 -15
  126. package/dist/services/removeNonNumeric.d.ts.map +0 -1
  127. package/dist/services/removeNonNumeric.js +0 -16
  128. package/dist/validations/validateCpf.d.ts +0 -24
  129. package/dist/validations/validateCpf.d.ts.map +0 -1
  130. package/dist/validations/validateCpf.js +0 -56
  131. package/src/formats/formatDate.ts +0 -97
  132. package/src/formats/formatToCnpj.ts +0 -39
  133. package/src/formats/formatToCpf.ts +0 -39
  134. package/src/formats/formatToCurrency.ts +0 -53
  135. package/src/regex/index.ts +0 -8
  136. package/src/services/removeCurrencySymbols.ts +0 -25
  137. package/src/services/removeNonNumeric.ts +0 -18
  138. package/src/validations/validateCpf.ts +0 -64
  139. package/vitest.config.ts +0 -5
@@ -1,66 +1,21 @@
1
- import type { CalculateCardInstallmentFunction } from "@arkyn/types";
1
+ import type { CalculateCardInstallmentProps } from "@arkyn/types";
2
2
 
3
- /**
4
- * Calculates the installment price and total price for a card payment plan.
5
- *
6
- * @remarks
7
- * **Important:** When the interest amount (`fees`) is equal to 0 or the number of installments (`numberInstallments`) is equal to 1, no interest will be charged.
8
- *
9
- * @throws Will throw an error if the number of installments is less than or equal to 0.
10
- * @throws Will throw an error if the fees are less than 0.
11
- *
12
- * @param props - The input parameters for the calculation.
13
- * @param props.cashPrice - The total cash price of the product or service.
14
- * @param props.numberInstallments - The number of installments for the payment plan.
15
- * @param props.fees - The interest rate per installment (default is 0.0349).
16
- *
17
- * @returns An object containing:
18
- * - `totalPrice`: The total price to be paid, rounded to two decimal places.
19
- * - `installmentPrice`: The price of each installment, rounded to two decimal places.
20
- *
21
- * @example
22
- * ```typescript
23
- * const result = calculateCardInstallment({
24
- * cashPrice: 1000,
25
- * numberInstallments: 12,
26
- * fees: 0.02,
27
- * });
28
- * console.log(result);
29
- * // Output: { totalPrice: 1124.62, installmentPrice: 93.72 }
30
- * ```
31
- */
3
+ function calculateCardInstallment(args: CalculateCardInstallmentProps) {
4
+ const { cash_price, number_installments, fees = 0.0349 } = args;
32
5
 
33
- const calculateCardInstallment: CalculateCardInstallmentFunction = (props) => {
34
- const { cashPrice, numberInstallments, fees = 0.0349 } = props;
6
+ let installment_price = 0;
7
+ let total_price = 0;
35
8
 
36
- if (fees === 0 || numberInstallments === 1) {
37
- return {
38
- totalPrice: cashPrice,
39
- installmentPrice: cashPrice / numberInstallments,
40
- };
41
- }
9
+ let numerator = Math.pow(1 + fees, number_installments) * fees;
10
+ let denominator = Math.pow(1 + fees, number_installments) - 1;
42
11
 
43
- if (numberInstallments <= 0) {
44
- throw new Error("Number of installments must be greater than 0");
45
- }
46
-
47
- if (fees < 0) {
48
- throw new Error("Fees must be greater than or equal to 0");
49
- }
50
-
51
- let installmentPrice = 0;
52
- let totalPrice = 0;
53
-
54
- let numerator = Math.pow(1 + fees, numberInstallments) * fees;
55
- let denominator = Math.pow(1 + fees, numberInstallments) - 1;
56
-
57
- installmentPrice = cashPrice * (numerator / denominator);
58
- totalPrice = numberInstallments * installmentPrice;
12
+ installment_price = cash_price * (numerator / denominator);
13
+ total_price = number_installments * installment_price;
59
14
 
60
15
  return {
61
- totalPrice: +totalPrice.toFixed(2),
62
- installmentPrice: +installmentPrice.toFixed(2),
16
+ total_price: +total_price.toFixed(2),
17
+ installment_price: +installment_price.toFixed(2),
63
18
  };
64
- };
19
+ }
65
20
 
66
21
  export { calculateCardInstallment };
@@ -1,32 +1,7 @@
1
- import type { MaskSensitiveDataFunction } from "@arkyn/types";
2
-
3
- /**
4
- * Masks sensitive data in a JSON string by replacing the values of specified keys with "****".
5
- *
6
- * @param jsonString - The JSON string to be processed.
7
- * @param sensitiveKeys - An array of keys whose values should be masked. Defaults to `["password", "confirmPassword", "creditCard"]`.
8
- * @returns A JSON string with sensitive data masked. If the input is not a valid JSON string, it returns the original string.
9
- *
10
- * @example
11
- * ```typescript
12
- * const jsonString = JSON.stringify({
13
- * username: "user123",
14
- * password: "secret",
15
- * profile: {
16
- * creditCard: "1234-5678-9012-3456",
17
- * },
18
- * });
19
- *
20
- * const result = maskSensitiveData(jsonString, ["password", "creditCard"]);
21
- * console.log(result);
22
- * // Output: '{"username":"user123","password":"****","profile":{"creditCard":"****"}}'
23
- * ```
24
- */
25
-
26
- const maskSensitiveData: MaskSensitiveDataFunction = (
27
- jsonString,
1
+ function maskSensitiveData(
2
+ jsonString: string,
28
3
  sensitiveKeys = ["password", "confirmPassword", "creditCard"]
29
- ) => {
4
+ ): string {
30
5
  function maskValue(key: string, value: any): any {
31
6
  if (sensitiveKeys.includes(key)) return "****";
32
7
  return value;
@@ -60,6 +35,6 @@ const maskSensitiveData: MaskSensitiveDataFunction = (
60
35
  } catch (error) {
61
36
  return jsonString;
62
37
  }
63
- };
38
+ }
64
39
 
65
40
  export { maskSensitiveData };
@@ -0,0 +1,15 @@
1
+ const normalizeRange = (
2
+ range: number | [number, number],
3
+ limit: number
4
+ ): [number, number] => {
5
+ if (Array.isArray(range)) return range;
6
+
7
+ if (range >= 0) return [0, range];
8
+
9
+ return [limit + 1 - Math.abs(range), limit];
10
+ };
11
+
12
+ const within = (range: [number, number], value: number): boolean =>
13
+ value >= range[0] && value <= range[1];
14
+
15
+ export { normalizeRange, within };
@@ -1,39 +1,5 @@
1
- import type { TruncateLargeFieldsFunction } from "@arkyn/types";
2
-
3
- /**
4
- * Truncates large string fields in a JSON string to a specified maximum length.
5
- *
6
- * This function parses a JSON string, traverses its structure recursively, and truncates
7
- * any string fields that exceed the specified maximum length. If a string field is truncated,
8
- * it is replaced with a message indicating the original length of the field.
9
- *
10
- * @param jsonString - The JSON string to process.
11
- * @param maxLength - The maximum allowed length for string fields. Defaults to 1000.
12
- * @returns A JSON string with large string fields truncated.
13
- *
14
- * @throws {Error} Throws an error if the input is not a valid JSON string.
15
- *
16
- * @example
17
- * ```typescript
18
- * const json = JSON.stringify({
19
- * name: "John",
20
- * description: "A very long description that exceeds the maximum length...",
21
- * nested: {
22
- * details: "Another long string that needs truncation."
23
- * }
24
- * });
25
- *
26
- * const result = truncateLargeFields(json, 50);
27
- * console.log(result);
28
- * // Output: '{"name":"John","description":"To large information: field as 57 characters","nested":{"details":"To large information: field as 43 characters"}}'
29
- * ```
30
- */
31
-
32
- const truncateLargeFields: TruncateLargeFieldsFunction = (
33
- jsonString,
34
- maxLength = 1000
35
- ) => {
36
- function truncateValue(value: any): any {
1
+ function truncateLargeFields(jsonString: string, maxLength = 1000): string {
2
+ function truncateValue(key: string, value: any): any {
37
3
  if (typeof value === "string" && value.length > maxLength) {
38
4
  return `To large information: field as ${value.length} characters`;
39
5
  }
@@ -42,16 +8,16 @@ const truncateLargeFields: TruncateLargeFieldsFunction = (
42
8
 
43
9
  function recursiveTruncate(obj: any): any {
44
10
  if (Array.isArray(obj)) {
45
- return obj.map((item) => recursiveTruncate(item)); // Corrigido para processar elementos do array
11
+ return obj.map(recursiveTruncate);
46
12
  } else if (obj !== null && typeof obj === "object") {
47
13
  return Object.fromEntries(
48
14
  Object.entries(obj).map(([key, value]) => [
49
15
  key,
50
- recursiveTruncate(value), // Corrigido para aplicar recursão corretamente
16
+ truncateValue(key, recursiveTruncate(value)),
51
17
  ])
52
18
  );
53
19
  }
54
- return truncateValue(obj); // Corrigido para truncar valores diretamente
20
+ return obj;
55
21
  }
56
22
 
57
23
  try {
@@ -61,6 +27,6 @@ const truncateLargeFields: TruncateLargeFieldsFunction = (
61
27
  } catch (error) {
62
28
  throw new Error("Invalid JSON string");
63
29
  }
64
- };
30
+ }
65
31
 
66
32
  export { truncateLargeFields };
@@ -0,0 +1,41 @@
1
+ const CEP = /^(\d{8}|\d{2}\.?\d{3}\-\d{3})$/;
2
+
3
+ const CNPJ = /(^\d{2}\.\d{3}\.\d{3}\/\d{4}\-\d{2}$)/;
4
+
5
+ const CPF = /(^\d{3}\.\d{3}\.\d{3}\-\d{2}$)/;
6
+
7
+ const DATE = /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/\d{4}$/;
8
+
9
+ const DATEHOUR =
10
+ /^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/\d{4}\s(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/;
11
+
12
+ const HOUR = /^(0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])$/;
13
+
14
+ const PASSWORD =
15
+ /(?=^.{8,}$)((?=.*\w)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[|!"$%&\/\(\)\?\^\'\\\+\-\*]))^.*/;
16
+
17
+ const PHONE = /([0-9]{2})?(\s|-)?(9?[0-9]{4})-?([0-9]{4}$)/;
18
+
19
+ const RG = /(^\d{1,2}).?(\d{3}).?(\d{3})-?(\d{1}|X|x$)/;
20
+
21
+ const URL =
22
+ /^(((https?|ftp):\/\/)?([\w\-\.])+(\.)([\w]){2,4}([\w\/+=%&_\.~?\-]*))*$/;
23
+
24
+ const CPFCNPJ =
25
+ /^(?:(\d{3}\.\d{3}\.\d{3}-\d{2})|(\d{11})|(\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2})|(\d{14}))$/;
26
+
27
+ const regex = {
28
+ URL,
29
+ HOUR,
30
+ RG,
31
+ PHONE,
32
+ PASSWORD,
33
+ DATEHOUR,
34
+ CPF,
35
+ CNPJ,
36
+ CEP,
37
+ CPFCNPJ,
38
+ DATE,
39
+ };
40
+
41
+ export { regex };
@@ -0,0 +1,38 @@
1
+ function removeNonDigits(cpf: string) {
2
+ return cpf.replace(/\D/g, "");
3
+ }
4
+
5
+ function isInvalidLength(cpf: string) {
6
+ const CPF_LENGTH = 11;
7
+ return cpf.length !== CPF_LENGTH;
8
+ }
9
+
10
+ function hasAllDigitsEqual(cpf: string) {
11
+ const [firstCpfDigit] = cpf;
12
+ return [...cpf].every((digit) => digit === firstCpfDigit);
13
+ }
14
+
15
+ function calculateDigit(cpf: string, factor: number) {
16
+ let total = 0;
17
+ for (const digit of cpf) {
18
+ if (factor > 1) total += parseInt(digit) * factor--;
19
+ }
20
+ const rest = total % 11;
21
+ return rest < 2 ? 0 : 11 - rest;
22
+ }
23
+
24
+ function extractDigit(cpf: string) {
25
+ return cpf.slice(9);
26
+ }
27
+
28
+ function validateCPF(rawCpf: string) {
29
+ if (!rawCpf) return false;
30
+ const cpf = removeNonDigits(rawCpf);
31
+ if (isInvalidLength(cpf)) return false;
32
+ if (hasAllDigitsEqual(cpf)) return false;
33
+ const digit1 = calculateDigit(cpf, 10);
34
+ const digit2 = calculateDigit(cpf, 11);
35
+ return extractDigit(cpf) === `${digit1}${digit2}`;
36
+ }
37
+
38
+ export { validateCPF };
@@ -1,47 +1,25 @@
1
- import type { ValidateDateFunction } from "@arkyn/types";
1
+ type Format = "DD/MM/YYYY" | "MM-DD-YYYY" | "YYYY-MM-DD";
2
2
 
3
- /**
4
- * Validates a date string based on the provided format and configuration.
5
- *
6
- * @param date - The date string to validate.
7
- * @param config - Optional configuration object to customize validation.
8
- * @param config.inputFormat - The expected format of the input date.
9
- * Supported formats are "DD/MM/YYYY", "MM-DD-YYYY", and "YYYY-MM-DD".
10
- * Defaults to "DD/MM/YYYY".
11
- * @param config.minYear - The minimum allowed year for the date. Defaults to 1900.
12
- * @param config.maxYear - The maximum allowed year for the date. Defaults to 3000.
13
- *
14
- * @returns `true` if the date is valid according to the specified format and configuration, otherwise `false`.
15
- *
16
- * @throws {Error} If an invalid date format is provided in the configuration.
17
- *
18
- * @example
19
- * ```typescript
20
- * validateDate("31/12/2023"); // true
21
- * validateDate("12-31-2023", { inputFormat: "MM-DD-YYYY" }); // true
22
- * validateDate("2023-12-31", { inputFormat: "YYYY-MM-DD", minYear: 2000, maxYear: 2100 }); // true
23
- * validateDate("29/02/2024", { inputFormat: "DD/MM/YYYY" }); // true (leap year)
24
- * validateDate("29/02/2023", { inputFormat: "DD/MM/YYYY" }); // false (not a leap year)
25
- * validateDate("31/04/2023", { inputFormat: "DD/MM/YYYY" }); // false (April has 30 days)
26
- * ```
27
- */
3
+ type Config = {
4
+ minYear?: number;
5
+ maxYear?: number;
6
+ };
28
7
 
29
- const validateDate: ValidateDateFunction = (date, config) => {
8
+ function validateDate(date: string, format: Format, config?: Config): boolean {
30
9
  let day: string, month: string, year: string;
31
10
 
32
- const inputFormat = config?.inputFormat || "DD/MM/YYYY";
33
- const minYear = config?.minYear || 1900;
11
+ const minYear = config?.minYear || 0;
34
12
  const maxYear = config?.maxYear || 3000;
35
13
 
36
- if (inputFormat === "DD/MM/YYYY") {
14
+ if (format === "DD/MM/YYYY") {
37
15
  const dateRegex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
38
16
  if (!dateRegex.test(date)) return false;
39
17
  [, day, month, year] = date.match(dateRegex) || [];
40
- } else if (inputFormat === "MM-DD-YYYY") {
18
+ } else if (format === "MM-DD-YYYY") {
41
19
  const dateRegex = /^(\d{2})-(\d{2})-(\d{4})$/;
42
20
  if (!dateRegex.test(date)) return false;
43
21
  [, month, day, year] = date.match(dateRegex) || [];
44
- } else if (inputFormat === "YYYY-MM-DD") {
22
+ } else if (format === "YYYY-MM-DD") {
45
23
  const dateRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
46
24
  if (!dateRegex.test(date)) return false;
47
25
  [, year, month, day] = date.match(dateRegex) || [];
@@ -72,6 +50,6 @@ const validateDate: ValidateDateFunction = (date, config) => {
72
50
  new Date(yearNum, monthNum - 1, dayNum).getDate() === dayNum;
73
51
 
74
52
  return isValidDate;
75
- };
53
+ }
76
54
 
77
55
  export { validateDate };
@@ -1,33 +1,6 @@
1
1
  import { countries } from "@arkyn/templates";
2
- import type { ValidatePhoneFunction } from "@arkyn/types";
3
2
 
4
- /**
5
- * Validates a phone number against a list of country-specific formats.
6
- *
7
- * The function iterates through a predefined list of countries and checks if the
8
- * provided phone number matches the format for any of the countries. It uses
9
- * regular expressions to validate the phone number based on the country's code,
10
- * prefix, and mask.
11
- *
12
- * Special handling is applied for Brazilian phone numbers (ISO code "BR"), which
13
- * allows for an optional ninth digit.
14
- *
15
- * @param phone - The phone number to validate as a string.
16
- * @returns `true` if the phone number matches any country's format, otherwise `false`.
17
- *
18
- * @example
19
- * ```typescript
20
- * import { validatePhone } from "./validatePhone";
21
- *
22
- * validatePhone("+55 32912345678"); // true for a valid Brazilian phone number
23
- * validatePhone("+55 3212345678"); // true for a valid Brazilian phone number
24
- * validatePhone("+1-684 1234567"); // true for a valid American Samoa phone number
25
- * validatePhone("+5532912345678"); // false for an invalid Brazilian phone number
26
- * validatePhone("+55 1234567890"); // false for an invalid Brazilian phone number
27
- * ```
28
- */
29
-
30
- const validatePhone: ValidatePhoneFunction = (phone) => {
3
+ function validatePhone(phone: string): boolean {
31
4
  for (const country of countries) {
32
5
  const countryCode = country.code;
33
6
  const prefix = country.prefix ? `-${country.prefix}` : "";
@@ -44,6 +17,6 @@ const validatePhone: ValidatePhoneFunction = (phone) => {
44
17
  }
45
18
 
46
19
  return false;
47
- };
20
+ }
48
21
 
49
22
  export { validatePhone };
package/tsconfig.json CHANGED
@@ -15,6 +15,6 @@
15
15
  "types": ["bun-types"],
16
16
  "verbatimModuleSyntax": true
17
17
  },
18
- "exclude": ["dist", "node_modules", "**/__test__"],
18
+ "exclude": ["dist", "node_modules"],
19
19
  "include": ["src/**/*.ts"]
20
20
  }
@@ -1,43 +0,0 @@
1
- import type { FormatDateFunction } from "@arkyn/types";
2
- /**
3
- * Formats a date string from a given input format to a specified output format,
4
- * with optional timezone adjustment.
5
- *
6
- * @param date - The date string to be formatted. It should match the specified `inputFormat`.
7
- * @param time - The time string in the format `hh:mm:ss` (e.g., `14:30:00`).
8
- * @param inputFormat - The format of the input date string. Supported formats:
9
- * - `"brazilianDate"`: Expects the date in `DD/MM/YYYY` format.
10
- * - `"isoDate"`: Expects the date in `YYYY-MM-DD` format.
11
- * - `"timestamp"`: Expects the date as a numeric timestamp (e.g., `YYYY-MM-DD`).
12
- *
13
- * @param outputFormat - The desired format for the output date string. Supported tokens:
14
- * - `YYYY`: Full year (e.g., 2023)
15
- * - `YY`: Last two digits of the year (e.g., 23)
16
- * - `MM`: Month (zero-padded, e.g., 01)
17
- * - `DD`: Day of the month (zero-padded, e.g., 09)
18
- * - `hh`: Hours (zero-padded, 24-hour format, e.g., 08)
19
- * - `mm`: Minutes (zero-padded, e.g., 05)
20
- * - `ss`: Seconds (zero-padded, e.g., 07)
21
- * @param timezone - (Optional) The timezone offset in hours to adjust the date. Defaults to `0`.
22
- *
23
- * @returns The formatted date string in the specified `outputFormat`.
24
- *
25
- * @throws Will throw an error if:
26
- * - The `inputFormat` is invalid.
27
- * - The `date` string does not match the expected `inputFormat`.
28
- * - The `time` string is not in the format `hh:mm:ss`.
29
- * - The resulting date is invalid.
30
- *
31
- * @example
32
- * ```typescript
33
- * import { formatDate } from "./formatDate";
34
- *
35
- * const date = "25/12/2023";
36
- * const time = "14:30:00";
37
- * const formatted = formatDate(date, time, "brazilianDate", "YYYY-MM-DD hh:mm:ss", -3);
38
- * console.log(formatted); // Outputs: "2023-12-25 14:30:00"
39
- * ```
40
- */
41
- declare const formatDate: FormatDateFunction;
42
- export { formatDate };
43
- //# sourceMappingURL=formatDate.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"formatDate.d.ts","sourceRoot":"","sources":["../../src/formats/formatDate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAqBvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAEH,QAAA,MAAM,UAAU,EAAE,kBAiCjB,CAAC;AAEF,OAAO,EAAE,UAAU,EAAE,CAAC"}
@@ -1,77 +0,0 @@
1
- function formatDateString(date, format) {
2
- const pad = (num) => num.toString().padStart(2, "0");
3
- const replacements = {
4
- YYYY: date.getFullYear().toString(),
5
- YY: date.getFullYear().toString().slice(-2),
6
- MM: pad(date.getMonth() + 1),
7
- DD: pad(date.getDate()),
8
- hh: pad(date.getHours()),
9
- mm: pad(date.getMinutes()),
10
- ss: pad(date.getSeconds()),
11
- };
12
- return format.replace(/YYYY|YY|MM|DD|hh|mm|ss/g, (match) => replacements[match]);
13
- }
14
- /**
15
- * Formats a date string from a given input format to a specified output format,
16
- * with optional timezone adjustment.
17
- *
18
- * @param date - The date string to be formatted. It should match the specified `inputFormat`.
19
- * @param time - The time string in the format `hh:mm:ss` (e.g., `14:30:00`).
20
- * @param inputFormat - The format of the input date string. Supported formats:
21
- * - `"brazilianDate"`: Expects the date in `DD/MM/YYYY` format.
22
- * - `"isoDate"`: Expects the date in `YYYY-MM-DD` format.
23
- * - `"timestamp"`: Expects the date as a numeric timestamp (e.g., `YYYY-MM-DD`).
24
- *
25
- * @param outputFormat - The desired format for the output date string. Supported tokens:
26
- * - `YYYY`: Full year (e.g., 2023)
27
- * - `YY`: Last two digits of the year (e.g., 23)
28
- * - `MM`: Month (zero-padded, e.g., 01)
29
- * - `DD`: Day of the month (zero-padded, e.g., 09)
30
- * - `hh`: Hours (zero-padded, 24-hour format, e.g., 08)
31
- * - `mm`: Minutes (zero-padded, e.g., 05)
32
- * - `ss`: Seconds (zero-padded, e.g., 07)
33
- * @param timezone - (Optional) The timezone offset in hours to adjust the date. Defaults to `0`.
34
- *
35
- * @returns The formatted date string in the specified `outputFormat`.
36
- *
37
- * @throws Will throw an error if:
38
- * - The `inputFormat` is invalid.
39
- * - The `date` string does not match the expected `inputFormat`.
40
- * - The `time` string is not in the format `hh:mm:ss`.
41
- * - The resulting date is invalid.
42
- *
43
- * @example
44
- * ```typescript
45
- * import { formatDate } from "./formatDate";
46
- *
47
- * const date = "25/12/2023";
48
- * const time = "14:30:00";
49
- * const formatted = formatDate(date, time, "brazilianDate", "YYYY-MM-DD hh:mm:ss", -3);
50
- * console.log(formatted); // Outputs: "2023-12-25 14:30:00"
51
- * ```
52
- */
53
- const formatDate = (date, time, inputFormat, outputFormat, timezone = 0) => {
54
- const dateParts = date.split(/[-/]/).map(Number);
55
- const timeParts = time.split(":").map(Number);
56
- let day, month, year;
57
- const [hours = 0, minutes = 0, seconds = 0] = timeParts;
58
- switch (inputFormat) {
59
- case "brazilianDate":
60
- [day, month, year] = dateParts;
61
- break;
62
- case "isoDate":
63
- [year, month, day] = dateParts;
64
- break;
65
- case "timestamp":
66
- [year, month, day] = dateParts.map(Number);
67
- break;
68
- default:
69
- throw new Error("Invalid input format");
70
- }
71
- const formattedDate = new Date(year, month - 1, day, hours, minutes, seconds);
72
- if (isNaN(formattedDate.getTime()))
73
- throw new Error("Invalid date");
74
- formattedDate.setUTCHours(formattedDate.getUTCHours() + timezone);
75
- return formatDateString(formattedDate, outputFormat);
76
- };
77
- export { formatDate };
@@ -1,30 +0,0 @@
1
- import type { FormatToCnpjFunction } from "@arkyn/types";
2
- /**
3
- * Formats a given string or number into a CNPJ (Cadastro Nacional da Pessoa Jurídica) format.
4
- *
5
- * The CNPJ format is: `XX.XXX.XXX/XXXX-XX`, where `X` represents a digit.
6
- *
7
- * @param value - The input value to be formatted. It can be a string or number containing the CNPJ digits.
8
- * Non-numeric characters will be removed before formatting.
9
- *
10
- * @returns A string formatted as a CNPJ.
11
- *
12
- * @throws {Error} Throws an error if the input does not contain exactly 14 numeric digits.
13
- *
14
- * @example
15
- * ```typescript
16
- * import { formatToCnpj } from "./formatToCNPJ";
17
- *
18
- * const formattedCnpj = formatToCnpj("12345678000195");
19
- * console.log(formattedCnpj); // Output: "12.345.678/0001-95"
20
- *
21
- * try {
22
- * formatToCnpj("12345");
23
- * } catch (error) {
24
- * console.error(error.message); // Output: "Invalid CNPJ length"
25
- * }
26
- * ```
27
- */
28
- declare const formatToCnpj: FormatToCnpjFunction;
29
- export { formatToCnpj };
30
- //# sourceMappingURL=formatToCnpj.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"formatToCnpj.d.ts","sourceRoot":"","sources":["../../src/formats/formatToCnpj.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AAGzD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,QAAA,MAAM,YAAY,EAAE,oBAMnB,CAAC;AAEF,OAAO,EAAE,YAAY,EAAE,CAAC"}
@@ -1,35 +0,0 @@
1
- import { removeNonNumeric } from "../services/removeNonNumeric";
2
- /**
3
- * Formats a given string or number into a CNPJ (Cadastro Nacional da Pessoa Jurídica) format.
4
- *
5
- * The CNPJ format is: `XX.XXX.XXX/XXXX-XX`, where `X` represents a digit.
6
- *
7
- * @param value - The input value to be formatted. It can be a string or number containing the CNPJ digits.
8
- * Non-numeric characters will be removed before formatting.
9
- *
10
- * @returns A string formatted as a CNPJ.
11
- *
12
- * @throws {Error} Throws an error if the input does not contain exactly 14 numeric digits.
13
- *
14
- * @example
15
- * ```typescript
16
- * import { formatToCnpj } from "./formatToCNPJ";
17
- *
18
- * const formattedCnpj = formatToCnpj("12345678000195");
19
- * console.log(formattedCnpj); // Output: "12.345.678/0001-95"
20
- *
21
- * try {
22
- * formatToCnpj("12345");
23
- * } catch (error) {
24
- * console.error(error.message); // Output: "Invalid CNPJ length"
25
- * }
26
- * ```
27
- */
28
- const formatToCnpj = (value) => {
29
- const cleaned = removeNonNumeric(value);
30
- const match = cleaned.match(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/);
31
- if (match)
32
- return `${match[1]}.${match[2]}.${match[3]}/${match[4]}-${match[5]}`;
33
- throw new Error("Invalid CNPJ length");
34
- };
35
- export { formatToCnpj };
@@ -1,30 +0,0 @@
1
- import type { FormatToCpfFunction } from "@arkyn/types";
2
- /**
3
- * Formats a given string into a CPF (Cadastro de Pessoas Físicas) format.
4
- *
5
- * A CPF is a Brazilian individual taxpayer registry identification format.
6
- * This function ensures the input is cleaned of non-numeric characters and
7
- * then formats it into the standard CPF format: `XXX.XXX.XXX-XX`.
8
- *
9
- * @param value - The input string to be formatted as a CPF.
10
- * @returns The formatted CPF string.
11
- * @throws {Error} If the input string does not match the expected CPF format.
12
- *
13
- * @example
14
- * ```typescript
15
- * import { formatToCpf } from "./formatToCPF";
16
- *
17
- * const formattedCpf = formatToCpf("12345678909");
18
- * console.log(formattedCpf); // Output: "123.456.789-09"
19
-
20
- * try {
21
- * const formattedCpf = formatToCpf("12345");
22
- * } catch (error) {
23
- * console.error(error.message); // Output: "Invalid CPF format"
24
- * }
25
- *
26
- * ```
27
- */
28
- declare const formatToCpf: FormatToCpfFunction;
29
- export { formatToCpf };
30
- //# sourceMappingURL=formatToCpf.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"formatToCpf.d.ts","sourceRoot":"","sources":["../../src/formats/formatToCpf.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAGxD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,QAAA,MAAM,WAAW,EAAE,mBAMlB,CAAC;AAEF,OAAO,EAAE,WAAW,EAAE,CAAC"}