@astral/validations 2.26.0 → 3.0.0-beta.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 (316) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1243 -1
  3. package/any/any.d.ts +21 -0
  4. package/any/any.js +14 -0
  5. package/any/index.d.ts +1 -0
  6. package/any/index.js +1 -0
  7. package/array/array.d.ts +15 -0
  8. package/array/array.js +21 -0
  9. package/array/constants.d.ts +2 -0
  10. package/array/constants.js +5 -0
  11. package/array/index.d.ts +2 -0
  12. package/array/index.js +2 -0
  13. package/arrayItem/arrayItem.d.ts +35 -0
  14. package/arrayItem/arrayItem.js +33 -0
  15. package/arrayItem/index.d.ts +1 -0
  16. package/arrayItem/index.js +1 -0
  17. package/boolean/boolean.d.ts +13 -0
  18. package/boolean/boolean.js +19 -0
  19. package/boolean/constants.d.ts +2 -0
  20. package/boolean/constants.js +5 -0
  21. package/boolean/index.d.ts +2 -0
  22. package/boolean/index.js +2 -0
  23. package/core/compose/compose.d.ts +6 -0
  24. package/{compose → core/compose}/compose.js +2 -3
  25. package/core/context/createContext/createContext.d.ts +8 -0
  26. package/core/context/createContext/createContext.js +15 -0
  27. package/core/context/createContext/index.d.ts +1 -0
  28. package/core/context/createContext/index.js +1 -0
  29. package/core/context/index.d.ts +2 -0
  30. package/core/context/index.js +2 -0
  31. package/core/context/types.d.ts +28 -0
  32. package/core/errors/ArrayError/ArrayError.d.ts +18 -0
  33. package/core/errors/ArrayError/ArrayError.js +10 -0
  34. package/core/errors/ArrayError/createArrayError/createArrayError.d.ts +5 -0
  35. package/core/errors/ArrayError/createArrayError/createArrayError.js +11 -0
  36. package/core/errors/ArrayError/createArrayError/index.d.ts +1 -0
  37. package/core/errors/ArrayError/createArrayError/index.js +1 -0
  38. package/core/errors/ArrayError/index.d.ts +2 -0
  39. package/core/errors/ArrayError/index.js +2 -0
  40. package/core/errors/ErrorMap/ErrorMap.d.ts +21 -0
  41. package/core/errors/ErrorMap/ErrorMap.js +10 -0
  42. package/core/errors/ErrorMap/createErrorMap/createErrorMap.d.ts +5 -0
  43. package/core/errors/ErrorMap/createErrorMap/createErrorMap.js +10 -0
  44. package/core/errors/ErrorMap/createErrorMap/index.d.ts +1 -0
  45. package/core/errors/ErrorMap/createErrorMap/index.js +1 -0
  46. package/core/errors/ErrorMap/index.d.ts +2 -0
  47. package/core/errors/ErrorMap/index.js +2 -0
  48. package/core/errors/SimpleError/SimpleError.d.ts +16 -0
  49. package/core/errors/SimpleError/SimpleError.js +9 -0
  50. package/core/errors/SimpleError/createSimpleError/createSimpleError.d.ts +6 -0
  51. package/core/errors/SimpleError/createSimpleError/createSimpleError.js +5 -0
  52. package/core/errors/SimpleError/createSimpleError/index.d.ts +1 -0
  53. package/core/errors/SimpleError/createSimpleError/index.js +1 -0
  54. package/core/errors/SimpleError/index.d.ts +2 -0
  55. package/core/errors/SimpleError/index.js +2 -0
  56. package/core/errors/createErrorCode/createErrorCode.d.ts +5 -0
  57. package/core/errors/createErrorCode/createErrorCode.js +4 -0
  58. package/core/errors/createErrorCode/index.d.ts +1 -0
  59. package/core/errors/createErrorCode/index.js +1 -0
  60. package/core/errors/index.d.ts +5 -0
  61. package/core/errors/index.js +5 -0
  62. package/core/errors/types.d.ts +18 -0
  63. package/core/errors/types.js +1 -0
  64. package/core/guard/createGuard/createGuard.d.ts +54 -0
  65. package/core/guard/createGuard/createGuard.js +41 -0
  66. package/core/guard/createGuard/index.d.ts +1 -0
  67. package/core/guard/createGuard/index.js +1 -0
  68. package/core/guard/index.d.ts +1 -0
  69. package/core/guard/index.js +1 -0
  70. package/core/index.d.ts +8 -0
  71. package/core/index.js +8 -0
  72. package/core/rule/createRule/createRule.d.ts +42 -0
  73. package/core/rule/createRule/createRule.js +27 -0
  74. package/core/rule/index.d.ts +3 -0
  75. package/core/rule/index.js +3 -0
  76. package/core/rule/required/constants.d.ts +2 -0
  77. package/core/rule/required/constants.js +5 -0
  78. package/core/rule/required/index.d.ts +2 -0
  79. package/core/rule/required/index.js +2 -0
  80. package/core/rule/required/required.d.ts +19 -0
  81. package/core/rule/required/required.js +25 -0
  82. package/core/rule/types.d.ts +15 -0
  83. package/core/rule/types.js +1 -0
  84. package/core/types.d.ts +9 -0
  85. package/core/types.js +1 -0
  86. package/{utils → core/utils}/index.d.ts +1 -1
  87. package/{utils → core/utils}/index.js +1 -1
  88. package/core/utils/isStringOfZeros/index.d.ts +1 -0
  89. package/core/utils/isStringOfZeros/index.js +1 -0
  90. package/{utils → core/utils/isStringOfZeros}/isStringOfZeros.d.ts +1 -1
  91. package/{utils → core/utils/isStringOfZeros}/isStringOfZeros.js +1 -1
  92. package/core/utils/resetTime/index.d.ts +1 -0
  93. package/core/utils/resetTime/index.js +1 -0
  94. package/core/utils/resetTime/resetTime.d.ts +5 -0
  95. package/core/utils/resetTime/resetTime.js +12 -0
  96. package/date/constants.d.ts +3 -0
  97. package/date/constants.js +9 -0
  98. package/date/date.d.ts +19 -0
  99. package/date/date.js +24 -0
  100. package/date/index.d.ts +1 -0
  101. package/date/index.js +1 -0
  102. package/deepPartial/deepPartial.d.ts +29 -0
  103. package/deepPartial/deepPartial.js +21 -0
  104. package/deepPartial/index.d.ts +1 -0
  105. package/deepPartial/index.js +1 -0
  106. package/email/constants.d.ts +5 -0
  107. package/email/constants.js +11 -0
  108. package/email/email.d.ts +28 -0
  109. package/email/email.js +19 -0
  110. package/email/index.d.ts +2 -0
  111. package/email/index.js +2 -0
  112. package/index.d.ts +24 -20
  113. package/index.js +24 -20
  114. package/innIP/constants.d.ts +5 -0
  115. package/innIP/constants.js +8 -0
  116. package/innIP/index.d.ts +2 -0
  117. package/innIP/index.js +2 -0
  118. package/innIP/innIP.d.ts +25 -0
  119. package/innIP/innIP.js +40 -0
  120. package/innUL/constants.d.ts +4 -0
  121. package/innUL/constants.js +7 -0
  122. package/innUL/index.d.ts +2 -0
  123. package/innUL/index.js +2 -0
  124. package/innUL/innUL.d.ts +25 -0
  125. package/innUL/innUL.js +36 -0
  126. package/kpp/constants.d.ts +3 -0
  127. package/kpp/constants.js +6 -0
  128. package/kpp/index.d.ts +2 -0
  129. package/kpp/index.js +2 -0
  130. package/kpp/kpp.d.ts +25 -0
  131. package/kpp/kpp.js +16 -0
  132. package/max/constants.d.ts +5 -0
  133. package/max/constants.js +5 -0
  134. package/max/index.d.ts +2 -0
  135. package/max/index.js +2 -0
  136. package/max/max.d.ts +26 -0
  137. package/max/max.js +42 -0
  138. package/min/constants.d.ts +5 -0
  139. package/min/constants.js +5 -0
  140. package/min/index.d.ts +2 -0
  141. package/min/index.js +2 -0
  142. package/min/min.d.ts +26 -0
  143. package/min/min.js +42 -0
  144. package/mobilePhone/constants.d.ts +3 -0
  145. package/mobilePhone/constants.js +6 -0
  146. package/mobilePhone/index.d.ts +2 -0
  147. package/mobilePhone/index.js +2 -0
  148. package/mobilePhone/mobilePhone.d.ts +27 -0
  149. package/mobilePhone/mobilePhone.js +21 -0
  150. package/number/constants.d.ts +4 -0
  151. package/number/constants.js +13 -0
  152. package/number/index.d.ts +2 -0
  153. package/number/index.js +2 -0
  154. package/number/number.d.ts +19 -0
  155. package/number/number.js +26 -0
  156. package/object/constants.d.ts +2 -0
  157. package/object/constants.js +5 -0
  158. package/object/index.d.ts +2 -0
  159. package/object/index.js +2 -0
  160. package/object/isEmptyErrors/index.d.ts +1 -0
  161. package/object/isEmptyErrors/index.js +1 -0
  162. package/object/isEmptyErrors/isEmptyErrors.d.ts +5 -0
  163. package/object/isEmptyErrors/isEmptyErrors.js +4 -0
  164. package/object/object.d.ts +52 -0
  165. package/object/object.js +50 -0
  166. package/ogrnIP/constants.d.ts +3 -0
  167. package/ogrnIP/constants.js +6 -0
  168. package/ogrnIP/index.d.ts +2 -0
  169. package/ogrnIP/index.js +2 -0
  170. package/ogrnIP/ogrnIP.d.ts +25 -0
  171. package/ogrnIP/ogrnIP.js +27 -0
  172. package/ogrnUL/constants.d.ts +3 -0
  173. package/ogrnUL/constants.js +6 -0
  174. package/ogrnUL/index.d.ts +2 -0
  175. package/ogrnUL/index.js +2 -0
  176. package/ogrnUL/ogrnUL.d.ts +25 -0
  177. package/ogrnUL/ogrnUL.js +27 -0
  178. package/onlyNumber/constants.d.ts +2 -0
  179. package/onlyNumber/constants.js +2 -0
  180. package/onlyNumber/index.d.ts +2 -0
  181. package/onlyNumber/index.js +2 -0
  182. package/onlyNumber/onlyNumber.d.ts +24 -0
  183. package/onlyNumber/onlyNumber.js +20 -0
  184. package/optional/index.d.ts +1 -0
  185. package/optional/index.js +1 -0
  186. package/optional/optional.d.ts +7 -0
  187. package/optional/optional.js +15 -0
  188. package/or/index.d.ts +1 -0
  189. package/or/index.js +1 -0
  190. package/or/or.d.ts +22 -0
  191. package/or/or.js +21 -0
  192. package/package.json +2 -2
  193. package/partial/index.d.ts +1 -0
  194. package/partial/index.js +1 -0
  195. package/partial/partial.d.ts +10 -0
  196. package/partial/partial.js +6 -0
  197. package/pattern/constants.d.ts +2 -0
  198. package/pattern/constants.js +2 -0
  199. package/pattern/index.d.ts +2 -0
  200. package/pattern/index.js +2 -0
  201. package/pattern/pattern.d.ts +26 -0
  202. package/pattern/pattern.js +22 -0
  203. package/snils/constants.d.ts +4 -0
  204. package/snils/constants.js +7 -0
  205. package/snils/index.d.ts +2 -0
  206. package/snils/index.js +2 -0
  207. package/snils/snils.d.ts +25 -0
  208. package/{isSNILS/isSNILS.js → snils/snils.js} +20 -21
  209. package/string/constants.d.ts +2 -0
  210. package/string/constants.js +5 -0
  211. package/string/index.d.ts +2 -0
  212. package/string/index.js +2 -0
  213. package/string/string.d.ts +2 -0
  214. package/string/string.js +8 -0
  215. package/toPlainError/index.d.ts +1 -0
  216. package/toPlainError/index.js +1 -0
  217. package/toPlainError/toPlainError.d.ts +35 -0
  218. package/toPlainError/toPlainError.js +49 -0
  219. package/toPlainError/utils/generateArrayPath/generateArrayPath.d.ts +4 -0
  220. package/toPlainError/utils/generateArrayPath/generateArrayPath.js +9 -0
  221. package/toPlainError/utils/generateArrayPath/index.d.ts +1 -0
  222. package/toPlainError/utils/generateArrayPath/index.js +1 -0
  223. package/toPlainError/utils/generateObjectPath/generateObjectPath.d.ts +4 -0
  224. package/toPlainError/utils/generateObjectPath/generateObjectPath.js +9 -0
  225. package/toPlainError/utils/generateObjectPath/index.d.ts +1 -0
  226. package/toPlainError/utils/generateObjectPath/index.js +1 -0
  227. package/toPlainError/utils/index.d.ts +2 -0
  228. package/toPlainError/utils/index.js +2 -0
  229. package/transform/index.d.ts +1 -0
  230. package/transform/index.js +1 -0
  231. package/transform/transform.d.ts +26 -0
  232. package/transform/transform.js +16 -0
  233. package/when/index.d.ts +1 -0
  234. package/when/index.js +1 -0
  235. package/when/when.d.ts +47 -0
  236. package/when/when.js +29 -0
  237. package/compose/compose.d.ts +0 -7
  238. package/composeSome/composeSome.d.ts +0 -8
  239. package/composeSome/composeSome.js +0 -25
  240. package/composeSome/index.d.ts +0 -1
  241. package/composeSome/index.js +0 -1
  242. package/constants.d.ts +0 -2
  243. package/constants.js +0 -2
  244. package/createRule/createRule.d.ts +0 -14
  245. package/createRule/createRule.js +0 -12
  246. package/isDate/index.d.ts +0 -1
  247. package/isDate/index.js +0 -1
  248. package/isDate/isDate.d.ts +0 -10
  249. package/isDate/isDate.js +0 -23
  250. package/isEmail/index.d.ts +0 -1
  251. package/isEmail/index.js +0 -1
  252. package/isEmail/isEmail.d.ts +0 -13
  253. package/isEmail/isEmail.js +0 -25
  254. package/isINNIP/index.d.ts +0 -1
  255. package/isINNIP/index.js +0 -1
  256. package/isINNIP/isINNIP.d.ts +0 -10
  257. package/isINNIP/isINNIP.js +0 -42
  258. package/isINNUL/index.d.ts +0 -1
  259. package/isINNUL/index.js +0 -1
  260. package/isINNUL/isINNUL.d.ts +0 -10
  261. package/isINNUL/isINNUL.js +0 -37
  262. package/isKPP/index.d.ts +0 -1
  263. package/isKPP/index.js +0 -1
  264. package/isKPP/isKPP.d.ts +0 -7
  265. package/isKPP/isKPP.js +0 -19
  266. package/isMaxLength/index.d.ts +0 -1
  267. package/isMaxLength/index.js +0 -1
  268. package/isMaxLength/isMaxLength.d.ts +0 -18
  269. package/isMaxLength/isMaxLength.js +0 -34
  270. package/isMaxValue/index.d.ts +0 -1
  271. package/isMaxValue/index.js +0 -1
  272. package/isMaxValue/isMaxValue.d.ts +0 -17
  273. package/isMaxValue/isMaxValue.js +0 -35
  274. package/isMaybeNumber/index.d.ts +0 -1
  275. package/isMaybeNumber/index.js +0 -1
  276. package/isMaybeNumber/isMaybeNumber.d.ts +0 -10
  277. package/isMaybeNumber/isMaybeNumber.js +0 -23
  278. package/isMinLength/index.d.ts +0 -1
  279. package/isMinLength/index.js +0 -1
  280. package/isMinLength/isMinLength.d.ts +0 -18
  281. package/isMinLength/isMinLength.js +0 -34
  282. package/isMinValue/index.d.ts +0 -1
  283. package/isMinValue/index.js +0 -1
  284. package/isMinValue/isMinValue.d.ts +0 -17
  285. package/isMinValue/isMinValue.js +0 -35
  286. package/isMobilePhone/index.d.ts +0 -1
  287. package/isMobilePhone/index.js +0 -1
  288. package/isMobilePhone/isMobilePhone.d.ts +0 -10
  289. package/isMobilePhone/isMobilePhone.js +0 -20
  290. package/isOGRNIP/index.d.ts +0 -1
  291. package/isOGRNIP/index.js +0 -1
  292. package/isOGRNIP/isOGRNIP.d.ts +0 -10
  293. package/isOGRNIP/isOGRNIP.js +0 -29
  294. package/isOGRNUL/index.d.ts +0 -1
  295. package/isOGRNUL/index.js +0 -1
  296. package/isOGRNUL/isOGRNUL.d.ts +0 -10
  297. package/isOGRNUL/isOGRNUL.js +0 -29
  298. package/isRequired/index.d.ts +0 -1
  299. package/isRequired/index.js +0 -1
  300. package/isRequired/isRequired.d.ts +0 -11
  301. package/isRequired/isRequired.js +0 -23
  302. package/isSNILS/index.d.ts +0 -1
  303. package/isSNILS/index.js +0 -1
  304. package/isSNILS/isSNILS.d.ts +0 -10
  305. package/types.d.ts +0 -4
  306. package/utils/isEmptyString.d.ts +0 -4
  307. package/utils/isEmptyString.js +0 -6
  308. package/yupAdapter/index.d.ts +0 -1
  309. package/yupAdapter/index.js +0 -1
  310. package/yupAdapter/yupAdapter.d.ts +0 -8
  311. package/yupAdapter/yupAdapter.js +0 -11
  312. /package/{compose → core/compose}/index.d.ts +0 -0
  313. /package/{compose → core/compose}/index.js +0 -0
  314. /package/{types.js → core/context/types.js} +0 -0
  315. /package/{createRule → core/rule/createRule}/index.d.ts +0 -0
  316. /package/{createRule → core/rule/createRule}/index.js +0 -0
@@ -0,0 +1,2 @@
1
+ export * from './string';
2
+ export * from './constants';
@@ -0,0 +1,2 @@
1
+ export * from './string';
2
+ export * from './constants';
@@ -0,0 +1,2 @@
1
+ import { ValidationRule } from '../core';
2
+ export declare const string: <TValues>(...rules: ValidationRule<string, TValues>[]) => import("../core").Guard<string, TValues, {}>;
@@ -0,0 +1,8 @@
1
+ import { compose, createGuard } from '../core';
2
+ import { STRING_TYPE_ERROR_INFO } from './constants';
3
+ export const string = (...rules) => createGuard((value, ctx, { typeErrorMessage }) => {
4
+ if (typeof value !== 'string') {
5
+ return ctx.createError(Object.assign(Object.assign({}, STRING_TYPE_ERROR_INFO), { message: typeErrorMessage || STRING_TYPE_ERROR_INFO.message }));
6
+ }
7
+ return compose(...rules)(value, ctx);
8
+ });
@@ -0,0 +1 @@
1
+ export * from './toPlainError';
@@ -0,0 +1 @@
1
+ export * from './toPlainError';
@@ -0,0 +1,35 @@
1
+ import { ValidationResult, ValidationSimpleError } from '../core';
2
+ type PlainArrayResult<TPlainSimpleError> = Array<TPlainSimpleError | TPlainSimpleError[] | PlainErrorMap<TPlainSimpleError> | PlainArrayResult<TPlainSimpleError> | undefined>;
3
+ type PlainErrorMap<TPlainSimpleError> = {
4
+ [key: string]: TPlainSimpleError | PlainArrayResult<TPlainSimpleError> | PlainErrorMap<TPlainSimpleError>;
5
+ };
6
+ type FormatSimpleErrorFunc<TPlainSimpleError> = (error: ValidationSimpleError, params: {
7
+ path: string;
8
+ }) => TPlainSimpleError;
9
+ /**
10
+ * @description Результат валидации, преобразованный в простые структуры данных (исходные - это инстансы error)
11
+ */
12
+ export type PlainValidationResult<TPlainSimpleError> = undefined | TPlainSimpleError | PlainArrayResult<TPlainSimpleError> | PlainErrorMap<TPlainSimpleError>;
13
+ /**
14
+ * @description Форматирует все ошибки валидации в простые объекты. Необходим для интеграции с другими библиотеками
15
+ * @param validationResult
16
+ * @param formatErrorInfo - позволяет отформатировать объект ошибки при его формировании
17
+ * @param path - путь до ошибки в схеме
18
+ * @example
19
+ * ```ts
20
+ * const validate = object<{ info: Array<{ name: string }> }>({
21
+ * info: array(
22
+ * arrayItem(
23
+ * object<{ name: string }>(
24
+ * { name: string() }
25
+ * )
26
+ * )
27
+ ),
28
+ * }),
29
+ *
30
+ * // { info: [{ name: { code: Symbol(string), message: 'Не является строкой' } }] }
31
+ * console.log(toPlainError(validate({ info: [{ name: 22 }] })));
32
+ * ```
33
+ */
34
+ export declare const toPlainError: <TPlainSimpleError>(validationResult: ValidationResult, formatErrorInfo: FormatSimpleErrorFunc<TPlainSimpleError>, path?: string) => PlainValidationResult<TPlainSimpleError>;
35
+ export {};
@@ -0,0 +1,49 @@
1
+ import { ValidationArrayError, ValidationErrorMap, } from '../core';
2
+ import { generateArrayPath, generateObjectPath } from './utils';
3
+ const toPlainArrayResult = (error, formatErrorInfo, path) => error.cause.errorArray.map((errorItem, index) =>
4
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
5
+ toPlainError(errorItem, formatErrorInfo, generateArrayPath(index, path)));
6
+ function toPlainErrorMap(error, formatErrorInfo, path) {
7
+ return Object.entries(error.cause.errorMap).reduce((plainErrorMap, [key, currentError]) => {
8
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
9
+ const plainError = toPlainError(currentError, formatErrorInfo, generateObjectPath(key, path));
10
+ if (plainError === undefined) {
11
+ return plainErrorMap;
12
+ }
13
+ plainErrorMap[key] = plainError;
14
+ return plainErrorMap;
15
+ }, {});
16
+ }
17
+ /**
18
+ * @description Форматирует все ошибки валидации в простые объекты. Необходим для интеграции с другими библиотеками
19
+ * @param validationResult
20
+ * @param formatErrorInfo - позволяет отформатировать объект ошибки при его формировании
21
+ * @param path - путь до ошибки в схеме
22
+ * @example
23
+ * ```ts
24
+ * const validate = object<{ info: Array<{ name: string }> }>({
25
+ * info: array(
26
+ * arrayItem(
27
+ * object<{ name: string }>(
28
+ * { name: string() }
29
+ * )
30
+ * )
31
+ ),
32
+ * }),
33
+ *
34
+ * // { info: [{ name: { code: Symbol(string), message: 'Не является строкой' } }] }
35
+ * console.log(toPlainError(validate({ info: [{ name: 22 }] })));
36
+ * ```
37
+ */
38
+ export const toPlainError = (validationResult, formatErrorInfo, path = '') => {
39
+ if (!validationResult) {
40
+ return undefined;
41
+ }
42
+ if (validationResult instanceof ValidationErrorMap) {
43
+ return toPlainErrorMap(validationResult, formatErrorInfo, path);
44
+ }
45
+ if (validationResult instanceof ValidationArrayError) {
46
+ return toPlainArrayResult(validationResult, formatErrorInfo, path);
47
+ }
48
+ return formatErrorInfo(validationResult, { path });
49
+ };
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @description Гененирует path для массива
3
+ */
4
+ export declare const generateArrayPath: (index: number, prevPath?: string) => string;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @description Гененирует path для массива
3
+ */
4
+ export const generateArrayPath = (index, prevPath) => {
5
+ if (prevPath) {
6
+ return `${prevPath}.${index}`;
7
+ }
8
+ return String(index);
9
+ };
@@ -0,0 +1 @@
1
+ export * from './generateArrayPath';
@@ -0,0 +1 @@
1
+ export * from './generateArrayPath';
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @description Гененирует path для объекта
3
+ */
4
+ export declare const generateObjectPath: (key: string, prevPath?: string) => string;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @description Гененирует path для объекта
3
+ */
4
+ export const generateObjectPath = (key, prevPath) => {
5
+ if (prevPath) {
6
+ return `${prevPath}.${key}`;
7
+ }
8
+ return key;
9
+ };
@@ -0,0 +1 @@
1
+ export * from './generateObjectPath';
@@ -0,0 +1 @@
1
+ export * from './generateObjectPath';
@@ -0,0 +1,2 @@
1
+ export * from './generateObjectPath';
2
+ export * from './generateArrayPath';
@@ -0,0 +1,2 @@
1
+ export * from './generateObjectPath';
2
+ export * from './generateArrayPath';
@@ -0,0 +1 @@
1
+ export * from './transform';
@@ -0,0 +1 @@
1
+ export * from './transform';
@@ -0,0 +1,26 @@
1
+ import { ValidationRule } from '../core';
2
+ type Transformer<TValue, TResult> = (value: TValue) => TResult;
3
+ /**
4
+ * @description Трансформирует value в новый тип для валидации
5
+ * @param transformer - функция трансформации value в новый тип
6
+ * @param rules - правила, которые будут вызваны после трансформации value
7
+ * @example
8
+ * ```ts
9
+ * string(
10
+ * transform(
11
+ * (value) => new Date(value),
12
+ * date(min(new Date()))
13
+ * )
14
+ * );
15
+ * ```
16
+ */
17
+ export declare const transform: <TValue extends unknown, TResult extends unknown, TValues>(transformer: Transformer<TValue, TResult>, ...rules: ValidationRule<TResult, TValues>[]) => (value: TValue, prevCtx?: Readonly<{
18
+ global: Readonly<{
19
+ values: TValues;
20
+ overrides: Readonly<{
21
+ objectIsPartial: boolean;
22
+ }>;
23
+ }>;
24
+ createError: ({ message, code }: import("../core").ErrorInfo) => import("../core").ValidationSimpleError<{}>;
25
+ }> | undefined) => import("../core").ValidationResult;
26
+ export {};
@@ -0,0 +1,16 @@
1
+ import { compose, createRule } from '../core';
2
+ /**
3
+ * @description Трансформирует value в новый тип для валидации
4
+ * @param transformer - функция трансформации value в новый тип
5
+ * @param rules - правила, которые будут вызваны после трансформации value
6
+ * @example
7
+ * ```ts
8
+ * string(
9
+ * transform(
10
+ * (value) => new Date(value),
11
+ * date(min(new Date()))
12
+ * )
13
+ * );
14
+ * ```
15
+ */
16
+ export const transform = (transformer, ...rules) => createRule((value, ctx) => compose(...rules)(transformer(value), ctx));
@@ -0,0 +1 @@
1
+ export * from './when';
package/when/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './when';
package/when/when.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import { ValidationContext, ValidationRule } from '../core';
2
+ type Params<TValues> = {
3
+ /**
4
+ * @description Условие для выбора ветки
5
+ */
6
+ is: (value: unknown, ctx: ValidationContext<TValues>) => boolean;
7
+ /**
8
+ * Правила валидации, применяемые если is === true
9
+ */
10
+ then: ValidationRule<unknown, TValues>;
11
+ /**
12
+ * Правила валидации, применяемые если is === false
13
+ */
14
+ otherwise: ValidationRule<unknown, TValues>;
15
+ };
16
+ /**
17
+ * @description Позволяет указывать условные валидации
18
+ * @example
19
+ * ```ts
20
+ * type Values = { name: string; isAgree: boolean };
21
+ *
22
+ * const validate = object<Values, Values>({
23
+ * name: when({
24
+ * is: (_, ctx) => ctx.global.values.isAgree,
25
+ * then: string(),
26
+ * otherwise: any(),
27
+ * }),
28
+ * isAgree: optional(boolean()),
29
+ * });
30
+ *
31
+ * // undefined
32
+ * const result1 = validate({ isAgree: false, name: '' });
33
+ *
34
+ * // Required error для name
35
+ * const result2 = validate({ isAgree: true, name: '' });
36
+ * ```
37
+ */
38
+ export declare const when: <TValues>({ is, then, otherwise }: Params<TValues>) => (value: unknown, prevCtx?: Readonly<{
39
+ global: Readonly<{
40
+ values: TValues;
41
+ overrides: Readonly<{
42
+ objectIsPartial: boolean;
43
+ }>;
44
+ }>;
45
+ createError: ({ message, code }: import("../core").ErrorInfo) => import("../core").ValidationSimpleError<{}>;
46
+ }> | undefined) => import("../core").ValidationResult;
47
+ export {};
package/when/when.js ADDED
@@ -0,0 +1,29 @@
1
+ import { createRule } from '../core';
2
+ /**
3
+ * @description Позволяет указывать условные валидации
4
+ * @example
5
+ * ```ts
6
+ * type Values = { name: string; isAgree: boolean };
7
+ *
8
+ * const validate = object<Values, Values>({
9
+ * name: when({
10
+ * is: (_, ctx) => ctx.global.values.isAgree,
11
+ * then: string(),
12
+ * otherwise: any(),
13
+ * }),
14
+ * isAgree: optional(boolean()),
15
+ * });
16
+ *
17
+ * // undefined
18
+ * const result1 = validate({ isAgree: false, name: '' });
19
+ *
20
+ * // Required error для name
21
+ * const result2 = validate({ isAgree: true, name: '' });
22
+ * ```
23
+ */
24
+ export const when = ({ is, then, otherwise }) => createRule((value, ctx) => {
25
+ if (is(value, ctx)) {
26
+ return then(value, ctx);
27
+ }
28
+ return otherwise(value, ctx);
29
+ });
@@ -1,7 +0,0 @@
1
- import { InitializedRule, ValidationResult } from '../types';
2
- /**
3
- * @description Объединяет переданные правила в цепочку правил, останавливает выполнение цепочки, если появилась ошибка. Выполняет правила слева направо
4
- * @example compose(isRequired(), isEmail());
5
- * @example compose(isRequired(), compose(isIncludeDot(), isIncludeComma()));
6
- */
7
- export declare const compose: (...rules: InitializedRule[]) => (value: unknown) => ValidationResult;
@@ -1,8 +0,0 @@
1
- import { InitializedRule, ValidationResult } from '../types';
2
- /**
3
- * @description Объединяет переданные правила в цепочку правил, выполняя все переданные правила, независимо от результата выполнения правил.
4
- * Выполняет правила слева направо. Возвращает текст первой ошибки, если все правила выполнены с ошибкой
5
- * @example composeSome(isIncludeDot(), isIncludeComma());
6
- * @example compose(isRequired(), composeSome(isIncludeDot(), isIncludeComma()));
7
- */
8
- export declare const composeSome: (...rules: InitializedRule[]) => (value: unknown) => ValidationResult;
@@ -1,25 +0,0 @@
1
- /**
2
- * @description Объединяет переданные правила в цепочку правил, выполняя все переданные правила, независимо от результата выполнения правил.
3
- * Выполняет правила слева направо. Возвращает текст первой ошибки, если все правила выполнены с ошибкой
4
- * @example composeSome(isIncludeDot(), isIncludeComma());
5
- * @example compose(isRequired(), composeSome(isIncludeDot(), isIncludeComma()));
6
- */
7
- export const composeSome = (...rules) => (value) => {
8
- const errors = rules.reduce((errorsAcc, rule) => {
9
- const error = rule(value);
10
- if (Array.isArray(error) && error.length > 0) {
11
- errorsAcc.push(...error);
12
- }
13
- if (typeof error === 'string') {
14
- errorsAcc.push(error);
15
- }
16
- return errorsAcc;
17
- }, []);
18
- if (!errors.length) {
19
- return undefined;
20
- }
21
- if (errors.length < rules.length) {
22
- return undefined;
23
- }
24
- return errors[0];
25
- };
@@ -1 +0,0 @@
1
- export * from './composeSome';
@@ -1 +0,0 @@
1
- export * from './composeSome';
package/constants.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export declare const INCORRECT_MESSAGE = "\u041D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435";
2
- export declare const CONTAINS_SPACES_REGEX: RegExp;
package/constants.js DELETED
@@ -1,2 +0,0 @@
1
- export const INCORRECT_MESSAGE = 'Некорректное значение';
2
- export const CONTAINS_SPACES_REGEX = /\s/g;
@@ -1,14 +0,0 @@
1
- import { Rule } from '../types';
2
- /**
3
- * @description Фабрика по созданию правил валидации.
4
- */
5
- export declare function createRule<Params extends object, RequiredParams extends true>(creator: Rule<Params & {
6
- exclude?: (value: unknown) => boolean;
7
- }, RequiredParams>): Rule<Params & {
8
- exclude?: (value: unknown) => boolean;
9
- }, RequiredParams>;
10
- export declare function createRule<Params extends object, RequiredParams extends false>(creator: Rule<Params & {
11
- exclude?: (value: unknown) => boolean;
12
- }, RequiredParams>): Rule<Params & {
13
- exclude?: (value: unknown) => boolean;
14
- }, RequiredParams>;
@@ -1,12 +0,0 @@
1
- // Реализована перегрузка, поэтому используется any
2
- // eslint-disable-next-line
3
- export function createRule(creator) {
4
- // eslint-disable-next-line
5
- return (params) => (value) => {
6
- var _a;
7
- if ((_a = params === null || params === void 0 ? void 0 : params.exclude) === null || _a === void 0 ? void 0 : _a.call(params, value)) {
8
- return undefined;
9
- }
10
- return creator(params)(value);
11
- };
12
- }
package/isDate/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from './isDate';
package/isDate/index.js DELETED
@@ -1 +0,0 @@
1
- export * from './isDate';
@@ -1,10 +0,0 @@
1
- export declare const IS_DATE_RULE_DEFAULT_MESSAGE = "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0444\u043E\u0440\u043C\u0430\u0442 \u0434\u0430\u0442\u044B";
2
- /**
3
- * @description Проверяет валидна ли дата
4
- * @example isDate()('2011-11-12');
5
- */
6
- export declare const isDate: (params?: ({
7
- message?: string | undefined;
8
- } & {
9
- exclude?: ((value: unknown) => boolean) | undefined;
10
- }) | undefined) => import("..").InitializedRule;
package/isDate/isDate.js DELETED
@@ -1,23 +0,0 @@
1
- import { createRule } from '../createRule';
2
- import { isEmptyString } from '../utils';
3
- export const IS_DATE_RULE_DEFAULT_MESSAGE = 'Неверный формат даты';
4
- /**
5
- * @description Проверяет валидна ли дата
6
- * @example isDate()('2011-11-12');
7
- */
8
- export const isDate = createRule(({ message = IS_DATE_RULE_DEFAULT_MESSAGE } = {}) => (value) => {
9
- if (isEmptyString(value)) {
10
- return undefined;
11
- }
12
- if (typeof value === 'string') {
13
- const date = new Date(value);
14
- if (!isNaN(date.getTime())) {
15
- return undefined;
16
- }
17
- return message;
18
- }
19
- if (value instanceof Date && !isNaN(value.getTime())) {
20
- return undefined;
21
- }
22
- return message;
23
- });
@@ -1 +0,0 @@
1
- export * from './isEmail';
package/isEmail/index.js DELETED
@@ -1 +0,0 @@
1
- export * from './isEmail';
@@ -1,13 +0,0 @@
1
- export declare const EMAIL_MAX_LENGTH = 256;
2
- export declare const DEFAULT_ERROR_MESSAGE = "\u041D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u044B\u0439 E-mail";
3
- export declare const INVALID_LENGTH_ERROR_MESSAGE = "E-mail \u0441\u043B\u0438\u0448\u043A\u043E\u043C \u0434\u043B\u0438\u043D\u043D\u044B\u0439";
4
- /**
5
- * @description Проверяет валиден ли email
6
- * @example isEmail()('test@example.com');
7
- */
8
- export declare const isEmail: (params?: ({
9
- message?: string | undefined;
10
- invalidLengthMessage?: string | undefined;
11
- } & {
12
- exclude?: ((value: unknown) => boolean) | undefined;
13
- }) | undefined) => import("..").InitializedRule;
@@ -1,25 +0,0 @@
1
- import { createRule } from '../createRule';
2
- import { isEmptyString } from '../utils';
3
- const EMAIL_REGEXP = /^[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,}$/;
4
- export const EMAIL_MAX_LENGTH = 256;
5
- export const DEFAULT_ERROR_MESSAGE = 'Некорректный E-mail';
6
- export const INVALID_LENGTH_ERROR_MESSAGE = 'E-mail слишком длинный';
7
- /**
8
- * @description Проверяет валиден ли email
9
- * @example isEmail()('test@example.com');
10
- */
11
- export const isEmail = createRule(({ message = DEFAULT_ERROR_MESSAGE, invalidLengthMessage = INVALID_LENGTH_ERROR_MESSAGE, } = {}) => (value) => {
12
- if (typeof value !== 'string') {
13
- return message;
14
- }
15
- if (isEmptyString(value)) {
16
- return undefined;
17
- }
18
- if (!EMAIL_REGEXP.test(value)) {
19
- return message;
20
- }
21
- if (value.length > EMAIL_MAX_LENGTH) {
22
- return invalidLengthMessage;
23
- }
24
- return undefined;
25
- });
@@ -1 +0,0 @@
1
- export * from './isINNIP';
package/isINNIP/index.js DELETED
@@ -1 +0,0 @@
1
- export * from './isINNIP';
@@ -1,10 +0,0 @@
1
- export declare const IS_INNIP_DEFAULT_MESSAGE = "\u041D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u044B\u0439 \u0418\u041D\u041D \u0418\u041F";
2
- /**
3
- * @description Проверяет валиден ли ИНН ИП
4
- * @example isINNIP()('384212952720');
5
- */
6
- export declare const isINNIP: (params?: ({
7
- message?: string | undefined;
8
- } & {
9
- exclude?: ((value: unknown) => boolean) | undefined;
10
- }) | undefined) => import("..").InitializedRule;
@@ -1,42 +0,0 @@
1
- import { createRule } from '../createRule';
2
- import { isEmptyString, isStringOfZeros } from '../utils';
3
- export const IS_INNIP_DEFAULT_MESSAGE = 'Некорректный ИНН ИП';
4
- const INNIP_LENGTH = 12;
5
- const FIRST_INN_UL_DECODING = [7, 2, 4, 10, 3, 5, 9, 4, 6, 8];
6
- const SECOND_INN_UL_DECODING = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8];
7
- const calcFirstCheckSumForInnUl = (arrSymbols) => (arrSymbols
8
- .slice(0, -2)
9
- .reduce((sum, symbol, index) => FIRST_INN_UL_DECODING[index] * Number(symbol) + sum, 0) %
10
- 11) %
11
- 10;
12
- const calcSecondCheckSumForInnUl = (arrSymbols) => (arrSymbols
13
- .slice(0, -1)
14
- .reduce((sum, symbol, index) => SECOND_INN_UL_DECODING[index] * Number(symbol) + sum, 0) %
15
- 11) %
16
- 10;
17
- /**
18
- * @description Проверяет валиден ли ИНН ИП
19
- * @example isINNIP()('384212952720');
20
- */
21
- export const isINNIP = createRule(({ message = IS_INNIP_DEFAULT_MESSAGE } = {}) => (value) => {
22
- if (isEmptyString(value)) {
23
- return undefined;
24
- }
25
- if (isStringOfZeros(value)) {
26
- return message;
27
- }
28
- if (typeof value === 'string') {
29
- if (value.length !== INNIP_LENGTH) {
30
- return message;
31
- }
32
- const arrSymbols = value.split('');
33
- const firstChecksum = calcFirstCheckSumForInnUl(arrSymbols);
34
- const secondChecksum = calcSecondCheckSumForInnUl(arrSymbols);
35
- if (Number(value[10]) !== firstChecksum &&
36
- Number(value[11]) !== secondChecksum) {
37
- return message;
38
- }
39
- return undefined;
40
- }
41
- return message;
42
- });
@@ -1 +0,0 @@
1
- export * from './isINNUL';
package/isINNUL/index.js DELETED
@@ -1 +0,0 @@
1
- export * from './isINNUL';
@@ -1,10 +0,0 @@
1
- export declare const IS_INNUL_DEFAULT_MESSAGE = "\u041D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u044B\u0439 \u0418\u041D\u041D \u042E\u041B";
2
- /**
3
- * @description Проверяет валиден ли ИНН ЮЛ
4
- * @example isINNUL()('7728168971');
5
- */
6
- export declare const isINNUL: (params?: ({
7
- message?: string | undefined;
8
- } & {
9
- exclude?: ((value: unknown) => boolean) | undefined;
10
- }) | undefined) => import("..").InitializedRule;
@@ -1,37 +0,0 @@
1
- import { createRule } from '../createRule';
2
- import { isEmptyString, isStringOfZeros } from '../utils';
3
- export const IS_INNUL_DEFAULT_MESSAGE = 'Некорректный ИНН ЮЛ';
4
- const INNUL_LENGTH = 10;
5
- const INN_UL_DECODING = [2, 4, 10, 3, 5, 9, 4, 6, 8];
6
- const calcCheckSumForInnUl = (arrSymbols) => (arrSymbols
7
- .slice(0, -1)
8
- .reduce((sum, symbol, index) => INN_UL_DECODING[index] * Number(symbol) + sum, 0) %
9
- 11) %
10
- 10;
11
- /**
12
- * @description Проверяет валиден ли ИНН ЮЛ
13
- * @example isINNUL()('7728168971');
14
- */
15
- export const isINNUL = createRule(({ message = IS_INNUL_DEFAULT_MESSAGE } = {}) => (value) => {
16
- if (isEmptyString(value)) {
17
- return undefined;
18
- }
19
- if (isStringOfZeros(value)) {
20
- return message;
21
- }
22
- if (typeof value === 'string') {
23
- if (value.length !== INNUL_LENGTH) {
24
- return message;
25
- }
26
- const arrSymbols = value.split('');
27
- if (arrSymbols.some((symbol) => isNaN(Number(symbol)))) {
28
- return message;
29
- }
30
- const checksum = calcCheckSumForInnUl(arrSymbols);
31
- if (Number(value[9]) !== checksum) {
32
- return message;
33
- }
34
- return undefined;
35
- }
36
- return message;
37
- });
package/isKPP/index.d.ts DELETED
@@ -1 +0,0 @@
1
- export * from './isKPP';
package/isKPP/index.js DELETED
@@ -1 +0,0 @@
1
- export * from './isKPP';
package/isKPP/isKPP.d.ts DELETED
@@ -1,7 +0,0 @@
1
- export declare const IS_KPP_DEFAULT_MESSAGE = "\u041D\u0435\u043A\u043E\u0440\u0440\u0435\u043A\u0442\u043D\u044B\u0439 \u041A\u041F\u041F";
2
- export declare const KPP_REGEX: RegExp;
3
- export declare const isKPP: (params?: ({
4
- message?: string | undefined;
5
- } & {
6
- exclude?: ((value: unknown) => boolean) | undefined;
7
- }) | undefined) => import("..").InitializedRule;
package/isKPP/isKPP.js DELETED
@@ -1,19 +0,0 @@
1
- import { createRule } from '../createRule';
2
- import { isEmptyString, isStringOfZeros } from '../utils';
3
- export const IS_KPP_DEFAULT_MESSAGE = 'Некорректный КПП';
4
- export const KPP_REGEX = /^(\d{4}([A-Z]|\d){2}\d{3})$/;
5
- export const isKPP = createRule(({ message = IS_KPP_DEFAULT_MESSAGE } = {}) => (value) => {
6
- if (isEmptyString(value)) {
7
- return undefined;
8
- }
9
- if (isStringOfZeros(value)) {
10
- return message;
11
- }
12
- if (typeof value !== 'string') {
13
- return message;
14
- }
15
- if (!KPP_REGEX.test(value)) {
16
- return message;
17
- }
18
- return undefined;
19
- });