@astral/validations 3.3.0 → 4.0.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 (41) hide show
  1. package/README.md +60 -18
  2. package/any/any.d.ts +1 -1
  3. package/array/array.d.ts +2 -2
  4. package/arrayItem/arrayItem.d.ts +1 -1
  5. package/boolean/boolean.d.ts +2 -2
  6. package/core/compose/compose.d.ts +1 -1
  7. package/core/context/createContext/createContext.d.ts +2 -2
  8. package/core/context/createContext/createContext.js +7 -2
  9. package/core/context/types.d.ts +6 -2
  10. package/core/guard/createGuard/createGuard.d.ts +7 -7
  11. package/core/guard/createGuard/createGuard.js +1 -1
  12. package/core/rule/createRule/createRule.d.ts +3 -3
  13. package/core/rule/required/required.d.ts +1 -1
  14. package/core/rule/types.d.ts +3 -3
  15. package/date/date.d.ts +2 -2
  16. package/deepPartial/deepPartial.d.ts +1 -1
  17. package/email/email.d.ts +1 -1
  18. package/innIP/innIP.d.ts +1 -1
  19. package/innUL/innUL.d.ts +1 -1
  20. package/integer/integer.d.ts +1 -1
  21. package/kpp/kpp.d.ts +1 -1
  22. package/max/max.d.ts +3 -3
  23. package/min/min.d.ts +3 -3
  24. package/mobilePhone/mobilePhone.d.ts +1 -1
  25. package/number/number.d.ts +2 -2
  26. package/object/object.d.ts +8 -8
  27. package/object/object.js +5 -4
  28. package/ogrnIP/ogrnIP.d.ts +1 -1
  29. package/ogrnUL/ogrnUL.d.ts +1 -1
  30. package/onlyNumber/onlyNumber.d.ts +1 -1
  31. package/optional/optional.d.ts +1 -1
  32. package/or/or.d.ts +1 -1
  33. package/package.json +1 -1
  34. package/partial/partial.d.ts +1 -1
  35. package/pattern/pattern.d.ts +1 -1
  36. package/positiveNumber/positiveNumber.d.ts +1 -1
  37. package/snils/snils.d.ts +1 -1
  38. package/string/string.d.ts +2 -2
  39. package/transform/transform.d.ts +1 -1
  40. package/when/when.d.ts +6 -6
  41. package/when/when.js +2 -2
package/README.md CHANGED
@@ -50,6 +50,7 @@
50
50
  - [Custom rules](#custom-rules)
51
51
  - [Базовый пример](#базовый-пример)
52
52
  - [Связанные поля](#связанные-поля)
53
+ - [Доступ к ctx.global.values](#доступ-к-высокоуровневым-values-ctxglobalvalues)
53
54
  - [Переиспользуемое правило](#переиспользуемое-правило)
54
55
  - [Common](#common)
55
56
  - [optional](#optional)
@@ -63,6 +64,7 @@
63
64
  - [Переиспользование объектов схемы, с условной валидацией и зависимыми полями](#переиспользование-объектов-схемы-с-условной-валидацией-и-зависимыми-полями)
64
65
  - [Error message customization](#error-message-customization)
65
66
  - [Exclusion managing](#exclusion-managing)
67
+ - [Migration Guide](#migration-guide)
66
68
 
67
69
  ---
68
70
 
@@ -952,9 +954,9 @@ validate([1, 2]);
952
954
  ```ts
953
955
  type Values = { name: string; isAgree: boolean };
954
956
 
955
- const validate = object<Values, Values>({
957
+ const validate = object<Values>({
956
958
  name: when({
957
- is: (_, ctx) => Boolean(ctx.global.values.isAgree),
959
+ is: (_, ctx) => Boolean(ctx.values?.isAgree),
958
960
  then: string(),
959
961
  otherwise: any(),
960
962
  }),
@@ -976,7 +978,7 @@ toPrettyError(
976
978
 
977
979
  Каждый guard позволяет переопределить дефолтные параметры:
978
980
  - Сообщение об ошибке типа
979
- - Сообщение о ошибке required
981
+ - Сообщение об ошибке required
980
982
  - Уникальные для каждого guard параметры
981
983
 
982
984
  ```ts
@@ -1010,7 +1012,7 @@ type Values = {
1010
1012
  nickname: string;
1011
1013
  };
1012
1014
 
1013
- const validate = object<Values, Values>({
1015
+ const validate = object<Values>({
1014
1016
  name: string(),
1015
1017
  nickname: string((value, ctx) => {
1016
1018
  if (value.includes('_')) {
@@ -1032,7 +1034,7 @@ toPrettyError(
1032
1034
 
1033
1035
  ## Связанные поля
1034
1036
 
1035
- В ```ctx.global.values``` находится value, принятое самым верхнеуровневым guard'ом.
1037
+ В ```ctx.values``` находится value, принятое последним object.
1036
1038
 
1037
1039
  ```ts
1038
1040
  import { object, string, toPrettyError } from '@astral/validations';
@@ -1042,10 +1044,10 @@ type Values = {
1042
1044
  repeatPassword: string;
1043
1045
  };
1044
1046
 
1045
- const validate = object<Values, Values>({
1047
+ const validate = object<Values>({
1046
1048
  password: string(min(9)),
1047
1049
  repeatPassword: string(min(9), (value, ctx) => {
1048
- if (value !== ctx.global.values.password) {
1050
+ if (value !== ctx.values?.password) {
1049
1051
  return ctx.createError({
1050
1052
  message: 'Пароли не совпадают',
1051
1053
  code: 'repeat-password',
@@ -1062,6 +1064,33 @@ toPrettyError(
1062
1064
  );
1063
1065
  ```
1064
1066
 
1067
+
1068
+ ## Доступ к высокоуровневым values (```ctx.global.values```)
1069
+
1070
+ В ```ctx.global.values``` находится values, полученное самым первым guard.
1071
+
1072
+ ```ts
1073
+ import { object, string, boolean, optional } from '@astral/validations';
1074
+
1075
+ type Values = {
1076
+ isAgree: boolean;
1077
+ info: {
1078
+ name: string
1079
+ }
1080
+ };
1081
+
1082
+ const validate = object<Values>({
1083
+ isAgree: optional(boolean()),
1084
+ info: object<Values['info']>({
1085
+ name: when({
1086
+ is: (_, ctx) => Boolean(ctx.global.values?.isAgree),
1087
+ then: string(),
1088
+ otherwise: any(),
1089
+ }),
1090
+ })
1091
+ });
1092
+ ```
1093
+
1065
1094
  ## Переиспользуемое правило
1066
1095
 
1067
1096
  ```ts
@@ -1137,9 +1166,9 @@ validate({
1137
1166
  ```ts
1138
1167
  type Values = { name: string; isAgree: boolean };
1139
1168
 
1140
- const validate = object<Values, Values>({
1169
+ const validate = object<Values>({
1141
1170
  name: when({
1142
- is: (_, ctx) => Boolean(ctx.global.values.isAgree),
1171
+ is: (_, ctx) => Boolean(ctx.values?.isAgree),
1143
1172
  then: string(),
1144
1173
  otherwise: any(),
1145
1174
  }),
@@ -1164,10 +1193,10 @@ type Values = {
1164
1193
  info?: ValuesInfo;
1165
1194
  };
1166
1195
 
1167
- const validate = object<Values, Values>({
1196
+ const validate = object<Values>({
1168
1197
  name: string(),
1169
1198
  info: when({
1170
- is: (_, ctx) => ctx.global.values.name === 'Vasya',
1199
+ is: (_, ctx) => ctx.values?.name === 'Vasya',
1171
1200
  then: object<ValuesInfo>({ surname: string() }),
1172
1201
  otherwise: any(),
1173
1202
  }),
@@ -1386,12 +1415,10 @@ type Values = {
1386
1415
  org: { data: RusOrganization | EngOrganization };
1387
1416
  };
1388
1417
 
1389
- // второй параметр generic - это глобально валидируемое значение. Для формы это весь values
1390
- const rusOrganization = object<RusOrganization, Values>({
1418
+ const rusOrganization = object<RusOrganization>({
1391
1419
  inn: string(
1392
- // автоматический вывод типа для ctx.global.values
1393
1420
  when({
1394
- is: (_, ctx) => Boolean(ctx.global.values.isRus),
1421
+ is: (_, ctx) => Boolean((ctx.global.values as Values)?.isRus),
1395
1422
  then: rusOrganization,
1396
1423
  otherwise: engOrganization,
1397
1424
  }),
@@ -1401,14 +1428,13 @@ const rusOrganization = object<RusOrganization, Values>({
1401
1428
 
1402
1429
  const engOrganization = object<EngOrganization, Values>({ name: string() });
1403
1430
 
1404
- // необходимо явно указать Values для типизации ctx.global.values
1405
1431
  const organization = when<Values>({
1406
- is: (_, ctx) => Boolean(ctx.global.values.isRus),
1432
+ is: (_, ctx) => Boolean((ctx.global.values as Values)?.isRus),
1407
1433
  then: rusOrganization,
1408
1434
  otherwise: engOrganization,
1409
1435
  });
1410
1436
 
1411
- const validate = object<Values, Values>({
1437
+ const validate = object<Values>({
1412
1438
  isRus: optional(boolean()),
1413
1439
  org: organization,
1414
1440
  });
@@ -1461,3 +1487,19 @@ const validate = string(kpp({ exclude: isExclude }));
1461
1487
  // undefined (значение не будет провалидировано)
1462
1488
  validate(excludeValue);
1463
1489
  ```
1490
+
1491
+ # Migration guide
1492
+
1493
+ ## v3 -> v4
1494
+
1495
+ ### object
1496
+
1497
+ Generic object guard стал принимать один параметр - валидируемое значение.
1498
+
1499
+ ### Типизация guard и rules
1500
+
1501
+ Generics правил и guards стали принимать тип для ```ctx.values``` вместо ```ctx.global.values```.
1502
+
1503
+ ### ctx.global.values
1504
+
1505
+ ```ctx.global.values``` стал ```unknown```. Для использования необходимо вручную уточнять тип. [Пример](#доступ-к-высокоуровневым-values-ctxglobalvalues).
package/any/any.d.ts CHANGED
@@ -10,4 +10,4 @@
10
10
  * validate({});
11
11
  * ```
12
12
  */
13
- export declare const any: <TValues>() => (value: unknown, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
13
+ export declare const any: <TLastSchemaValues extends Record<string, unknown>>() => (value: unknown, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
package/array/array.d.ts CHANGED
@@ -12,8 +12,8 @@ import { ValidationRule } from '../core';
12
12
  * validateArray(value);
13
13
  * ```
14
14
  */
15
- export declare const array: <TItem extends unknown, TValues = unknown>(...rules: ValidationRule<TItem[], TValues>[]) => {
16
- (value: unknown, prevCtx?: import("../core").ValidationContext<TValues> | undefined): import("../core").ValidationResult;
15
+ export declare const array: <TItem extends unknown, TLastSchemaValues extends Record<string, unknown> = {}>(...rules: ValidationRule<TItem[], TLastSchemaValues>[]) => {
16
+ (value: unknown, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined): import("../core").ValidationResult;
17
17
  define(overridesDefOptions: Partial<{}> & {
18
18
  requiredErrorMessage?: string | undefined;
19
19
  typeErrorMessage?: string | undefined;
@@ -24,4 +24,4 @@ import { ValidationRule } from '../core';
24
24
  * validateArray(values);
25
25
  * ```
26
26
  */
27
- export declare const arrayItem: <TItem extends unknown, TValues = unknown>(...rules: ValidationRule<TItem, TValues>[]) => (value: TItem[], prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
27
+ export declare const arrayItem: <TItem extends unknown, TLastSchemaValues extends Record<string, unknown> = {}>(...rules: ValidationRule<TItem, TLastSchemaValues>[]) => (value: TItem[], prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
@@ -10,8 +10,8 @@ import { ValidationRule } from '../core';
10
10
  * validate(true);
11
11
  * ```
12
12
  */
13
- export declare const boolean: <TValues>(...rules: ValidationRule<boolean, TValues>[]) => {
14
- (value: unknown, prevCtx?: import("../core").ValidationContext<TValues> | undefined): import("../core").ValidationResult;
13
+ export declare const boolean: <TLastSchemaValues extends Record<string, unknown>>(...rules: ValidationRule<boolean, TLastSchemaValues>[]) => {
14
+ (value: unknown, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined): import("../core").ValidationResult;
15
15
  define(overridesDefOptions: Partial<{}> & {
16
16
  requiredErrorMessage?: string | undefined;
17
17
  typeErrorMessage?: string | undefined;
@@ -3,4 +3,4 @@ import { IndependentValidationRule, ValidationRule } from '../rule';
3
3
  * @description Объединяет переданные правила в цепочку правил, останавливает выполнение цепочки, если появилась ошибка. Выполняет правила слева направо
4
4
  * @example compose(min(), max());
5
5
  */
6
- export declare const compose: <ValidationType, TValues>(...rules: (IndependentValidationRule<ValidationType, TValues> | ValidationRule<ValidationType, TValues>)[]) => IndependentValidationRule<ValidationType, TValues>;
6
+ export declare const compose: <ValidationType, TLastSchemaValues extends Record<string, unknown>>(...rules: (IndependentValidationRule<ValidationType, TLastSchemaValues> | ValidationRule<ValidationType, TLastSchemaValues>)[]) => IndependentValidationRule<ValidationType, Record<string, unknown>>;
@@ -4,5 +4,5 @@ import { ValidationTypes } from '../../types';
4
4
  * @description Создает context валидации. Используется внутри фабрик guard и rule
5
5
  * @default по-дефолту сбрасывает все флаги в false
6
6
  */
7
- export declare function createContext<Value extends ValidationTypes>(prevCtx: ValidationContext<Value> | undefined, value: Value): ValidationContext<Value>;
8
- export declare function createContext<Value extends ValidationTypes, Values>(prevCtx: ValidationContext<Values> | undefined, value: Value): ValidationContext<Values>;
7
+ export declare function createContext<TValue extends ValidationTypes>(prevCtx: ValidationContext<{}, TValue> | undefined, value: TValue): ValidationContext<{}, TValue>;
8
+ export declare function createContext<TValue extends ValidationTypes, TLastSchemaValues extends Record<string, unknown>>(prevCtx: ValidationContext<{}> | undefined, value: TValue, lastSchemaValue: TLastSchemaValues): ValidationContext<TLastSchemaValues, TValue>;
@@ -1,9 +1,14 @@
1
1
  import { createSimpleError } from '../../errors';
2
- export function createContext(prevCtx, value) {
3
- if (prevCtx) {
2
+ export function createContext(prevCtx, value, lastSchemaValue) {
3
+ if (prevCtx && !lastSchemaValue) {
4
4
  return prevCtx;
5
5
  }
6
+ const currentLastSchemaValue = lastSchemaValue ? lastSchemaValue : undefined;
7
+ if (prevCtx) {
8
+ return Object.assign(Object.assign({}, prevCtx), { values: currentLastSchemaValue });
9
+ }
6
10
  return {
11
+ values: currentLastSchemaValue,
7
12
  global: {
8
13
  values: value,
9
14
  overrides: {
@@ -3,7 +3,11 @@ import { createSimpleError } from '../errors';
3
3
  /**
4
4
  * @description Контекст, который доступен в каждом правиле
5
5
  */
6
- export type ValidationContext<TValues> = DeepReadonly<{
6
+ export type ValidationContext<TLastSchemaValues extends Record<string, unknown> = {}, TGlobalSchemaValues = unknown> = DeepReadonly<{
7
+ /**
8
+ * @description Values последнего валидируемого object
9
+ */
10
+ values?: DeepPartial<TLastSchemaValues>;
7
11
  /**
8
12
  * @description Глобальные значения, идущие от самого верхнего правила к самому нижнему
9
13
  */
@@ -11,7 +15,7 @@ export type ValidationContext<TValues> = DeepReadonly<{
11
15
  /**
12
16
  * @description Значения, которые валидируется guard самого высоко порядка
13
17
  */
14
- values: DeepPartial<TValues>;
18
+ values: TGlobalSchemaValues;
15
19
  /**
16
20
  * @description Глобальные переопределения (сквозные для всех правил)
17
21
  */
@@ -21,26 +21,26 @@ type GuardValue = unknown;
21
21
  /**
22
22
  * @description Интерфейс функции guard, которая в прототипе содержит метод define
23
23
  */
24
- export interface Guard<TValues = unknown, AddDefOptions extends Record<string, unknown> = {}> {
25
- (value: GuardValue, ctx?: ValidationContext<TValues>): ValidationResult;
24
+ export interface Guard<TLastSchemaValues extends Record<string, unknown> = {}, AddDefOptions extends Record<string, unknown> = {}> {
25
+ (value: GuardValue, ctx?: ValidationContext<TLastSchemaValues>): ValidationResult;
26
26
  /**
27
27
  * @description Функция для создания нового guard с переопределенными дефолтными параметрами. Возвращает новый guard
28
28
  * @param options - параметры, позволяющие переопределить дефолтные настройки guard
29
29
  * @example string.define({ requiredMessage: 'ИНН не может быть пустым' })(inn())
30
30
  */
31
- define(options: DefOptions<AddDefOptions>): Guard<TValues, AddDefOptions>;
31
+ define(options: DefOptions<AddDefOptions>): Guard<TLastSchemaValues, AddDefOptions>;
32
32
  }
33
33
  /**
34
34
  * @description Функция, которая позволяет определять частную логику для guard
35
35
  */
36
- type GuardExecutor<TValues, AddDefOptions extends Record<string, unknown>> = (value: unknown, ctx: ValidationContext<TValues>, defOptions: DefOptions<AddDefOptions>) => ValidationResult;
36
+ type GuardExecutor<AddDefOptions extends Record<string, unknown>> = (value: unknown, ctx: ValidationContext<Record<string, unknown>>, defOptions: DefOptions<AddDefOptions>) => ValidationResult;
37
37
  /**
38
38
  * @description Создает guard. Guard - функция, проверяющая тип значения
39
39
  * По-дефолту проверяет value на required. Для выключения required необходимо использовать optional().
40
40
  * После первого вызова guard в прототипу функции становится доступен метод define, который позволяет переопределить дефолтное поведение guard (например, изменить текст для required правила)
41
41
  * @example
42
42
  * ```ts
43
- * const string = <TValues>(...rules: ValidationRule<string, TValues>[]) =>
43
+ * const string = <TLastSchemaValues extends Record<string, unknown>>(...rules: ValidationRule<string, TValues>[]) =>
44
44
  * createGuard<string, TValues>((value, ctx) => {
45
45
  * if (typeof value !== 'string') {
46
46
  * return ctx.createError({ code: 'custom error', message: 'Не строка' });
@@ -50,8 +50,8 @@ type GuardExecutor<TValues, AddDefOptions extends Record<string, unknown>> = (va
50
50
  * });
51
51
  * ```
52
52
  */
53
- export declare const createGuard: <TValues, AddDefOptions extends Record<string, unknown> = {}>(executeGuard: GuardExecutor<TValues, AddDefOptions>) => {
54
- (value: unknown, prevCtx?: ValidationContext<TValues> | undefined): ValidationResult;
53
+ export declare const createGuard: <TLastSchemaValues extends Record<string, unknown>, AddDefOptions extends Record<string, unknown> = {}>(executeGuard: GuardExecutor<AddDefOptions>) => {
54
+ (value: unknown, prevCtx?: ValidationContext<TLastSchemaValues> | undefined): ValidationResult;
55
55
  define(overridesDefOptions: DefOptions<AddDefOptions>): any;
56
56
  };
57
57
  export {};
@@ -7,7 +7,7 @@ import { compose } from '../../compose';
7
7
  * После первого вызова guard в прототипу функции становится доступен метод define, который позволяет переопределить дефолтное поведение guard (например, изменить текст для required правила)
8
8
  * @example
9
9
  * ```ts
10
- * const string = <TValues>(...rules: ValidationRule<string, TValues>[]) =>
10
+ * const string = <TLastSchemaValues extends Record<string, unknown>>(...rules: ValidationRule<string, TValues>[]) =>
11
11
  * createGuard<string, TValues>((value, ctx) => {
12
12
  * if (typeof value !== 'string') {
13
13
  * return ctx.createError({ code: 'custom error', message: 'Не строка' });
@@ -8,12 +8,12 @@ export type CommonRuleParams<ValidationType extends ValidationTypes> = {
8
8
  /**
9
9
  * @description Функция, позволяющая для каждого правила указать исключение
10
10
  */
11
- exclude?: (value: ValidationType, ctx: ValidationContext<unknown>) => boolean;
11
+ exclude?: (value: ValidationType, ctx: ValidationContext) => boolean;
12
12
  };
13
13
  /**
14
14
  * @description Функция, которая позволяет определять частную логику для guard
15
15
  */
16
- type RuleExecutor<ValidationType extends ValidationTypes, TValues> = (value: ValidationType, ctx: ValidationContext<TValues>) => ValidationResult;
16
+ type RuleExecutor<ValidationType extends ValidationTypes, TLastSchemaValues extends Record<string, unknown>> = (value: ValidationType, ctx: ValidationContext<TLastSchemaValues>) => ValidationResult;
17
17
  /**
18
18
  * @description Создает правила валидации, которые можно использовать внутри guard или по отдельности
19
19
  * @param executor - функция, которая позволяет определять частную логику для guard
@@ -30,5 +30,5 @@ type RuleExecutor<ValidationType extends ValidationTypes, TValues> = (value: Val
30
30
  * }, params);
31
31
  * ```
32
32
  */
33
- export declare const createRule: <ValidationType extends unknown, TValues = unknown>(executor: RuleExecutor<ValidationType, TValues>, commonParams?: CommonRuleParams<ValidationType> | undefined) => (value: ValidationType, prevCtx?: ValidationContext<TValues> | undefined) => ValidationResult;
33
+ export declare const createRule: <ValidationType extends unknown, TLastSchemaValues extends Record<string, unknown> = {}>(executor: RuleExecutor<ValidationType, TLastSchemaValues>, commonParams?: CommonRuleParams<ValidationType> | undefined) => (value: ValidationType, prevCtx?: ValidationContext<TLastSchemaValues> | undefined) => ValidationResult;
34
34
  export {};
@@ -8,4 +8,4 @@ export declare const required: ({ message, }?: {
8
8
  * @default Обязательно
9
9
  */
10
10
  message?: string | undefined;
11
- }) => (value: unknown, prevCtx?: import("../..").ValidationContext<unknown> | undefined) => import("../..").ValidationResult;
11
+ }) => (value: unknown, prevCtx?: import("../..").ValidationContext<{}> | undefined) => import("../..").ValidationResult;
@@ -3,13 +3,13 @@ import { ValidationResult } from '../types';
3
3
  /**
4
4
  * @description Самостоятельное правило для валидации. Может использоваться вне guard'ов
5
5
  */
6
- export type IndependentValidationRule<TValue, TValues> = (value: TValue, ctx?: ValidationContext<TValues>) => ValidationResult;
6
+ export type IndependentValidationRule<TValue, TLastSchemaValues extends Record<string, unknown>> = (value: TValue, ctx?: ValidationContext<TLastSchemaValues>) => ValidationResult;
7
7
  /**
8
8
  * @description Правило для валидации, работающее исключительно с guard'ами
9
9
  */
10
- export type ValidationRule<TValue, TValues> = (value: TValue, ctx: ValidationContext<TValues>) => ValidationResult;
10
+ export type ValidationRule<TValue, TLastSchemaValues extends Record<string, unknown> = {}> = (value: TValue, ctx: ValidationContext<TLastSchemaValues>) => ValidationResult;
11
11
  /**
12
12
  * @description Композиционное правило валидации, умеющее работать с любыми значениями.
13
13
  * В основном используется для композиционных правил, которые принимают rule, умеющие валидировать разные значения (optional, transform...)
14
14
  */
15
- export type UniversalCompositionalValidationRule<TValues = unknown> = ValidationRule<any, TValues>;
15
+ export type UniversalCompositionalValidationRule<TLastSchemaValues extends Record<string, unknown>> = ValidationRule<any, TLastSchemaValues>;
package/date/date.d.ts CHANGED
@@ -15,8 +15,8 @@ type AdditionalDefOptions = {
15
15
  * validate(new Date('22.22.2022'));
16
16
  * ```
17
17
  */
18
- export declare const date: <TValues>(...rules: ValidationRule<Date, TValues>[]) => {
19
- (value: unknown, prevCtx?: import("../core").ValidationContext<TValues> | undefined): import("../core").ValidationResult;
18
+ export declare const date: <TLastSchemaValues extends Record<string, unknown>>(...rules: ValidationRule<Date, TLastSchemaValues>[]) => {
19
+ (value: unknown, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined): import("../core").ValidationResult;
20
20
  define(overridesDefOptions: Partial<AdditionalDefOptions> & {
21
21
  requiredErrorMessage?: string | undefined;
22
22
  typeErrorMessage?: string | undefined;
@@ -18,4 +18,4 @@ import { Guard } from '../core';
18
18
  * const result = validate({ info: { info: {} } });
19
19
  * ```
20
20
  */
21
- export declare const deepPartial: <TValues>(guard: Guard<TValues, {}>) => (value: unknown, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
21
+ export declare const deepPartial: <TLastSchemaValues extends Record<string, unknown>>(guard: Guard<TLastSchemaValues, {}>) => (value: unknown, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
package/email/email.d.ts CHANGED
@@ -16,5 +16,5 @@ type EmailParams = {
16
16
  * validate('example@mail.ru');
17
17
  * ```
18
18
  */
19
- export declare const email: <TValues>(params?: EmailParams) => (value: string, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
19
+ export declare const email: <TLastSchemaValues extends Record<string, unknown>>(params?: EmailParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
20
20
  export {};
package/innIP/innIP.d.ts CHANGED
@@ -13,5 +13,5 @@ type InnIPParams = CommonRuleParams<string> & {
13
13
  * validate('384212952720');
14
14
  * ```
15
15
  */
16
- export declare const innIP: <TValues>(params?: InnIPParams) => (value: string, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
16
+ export declare const innIP: <TLastSchemaValues extends Record<string, unknown>>(params?: InnIPParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
17
17
  export {};
package/innUL/innUL.d.ts CHANGED
@@ -13,5 +13,5 @@ type InnULParams = CommonRuleParams<string> & {
13
13
  * validate('7728168971');
14
14
  * ```
15
15
  */
16
- export declare const innUL: <TValues>(params?: InnULParams) => (value: string, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
16
+ export declare const innUL: <TLastSchemaValues extends Record<string, unknown>>(params?: InnULParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
17
17
  export {};
@@ -21,5 +21,5 @@ type IntegerParams = {
21
21
  * validate(3.14)
22
22
  * ```
23
23
  */
24
- export declare const integer: <TValues>(params?: IntegerParams) => (value: number, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
24
+ export declare const integer: <TLastSchemaValues extends Record<string, unknown>>(params?: IntegerParams) => (value: number, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
25
25
  export {};
package/kpp/kpp.d.ts CHANGED
@@ -13,5 +13,5 @@ type KPPParams = CommonRuleParams<string> & {
13
13
  * validate('770201001');
14
14
  * ```
15
15
  */
16
- export declare const kpp: <TValues>(params?: KPPParams) => (value: string, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
16
+ export declare const kpp: <TLastSchemaValues extends Record<string, unknown>>(params?: KPPParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
17
17
  export {};
package/max/max.d.ts CHANGED
@@ -5,7 +5,7 @@ type MaxParams<ValidationType> = {
5
5
  /**
6
6
  * @description Сообщение ошибки
7
7
  */
8
- getMessage?: (threshold: CommonThreshold, value: ValidationType, ctx: ValidationContext<unknown>) => string;
8
+ getMessage?: (threshold: CommonThreshold, value: ValidationType, ctx: ValidationContext) => string;
9
9
  };
10
10
  /**
11
11
  * @description Проверяет значение на соответствие максимуму. Работает с: string, array, Date, number
@@ -21,6 +21,6 @@ type MaxParams<ValidationType> = {
21
21
  * date(max(new Date())));
22
22
  * ```
23
23
  */
24
- export declare function max<ValidationType extends Date>(threshold: Date, params?: MaxParams<ValidationType>): ReturnType<typeof createRule<Date, unknown>>;
25
- export declare function max<ValidationType extends BaseMaxValidationTypes>(threshold: number, params?: MaxParams<ValidationType>): ReturnType<typeof createRule<BaseMaxValidationTypes, unknown>>;
24
+ export declare function max<ValidationType extends Date>(threshold: Date, params?: MaxParams<ValidationType>): ReturnType<typeof createRule<Date>>;
25
+ export declare function max<ValidationType extends BaseMaxValidationTypes>(threshold: number, params?: MaxParams<ValidationType>): ReturnType<typeof createRule<BaseMaxValidationTypes>>;
26
26
  export {};
package/min/min.d.ts CHANGED
@@ -5,7 +5,7 @@ type MinParams<ValidationType> = {
5
5
  /**
6
6
  * @description Сообщение ошибки
7
7
  */
8
- getMessage?: (threshold: CommonThreshold, value: ValidationType, ctx: ValidationContext<unknown>) => string;
8
+ getMessage?: (threshold: CommonThreshold, value: ValidationType, ctx: ValidationContext) => string;
9
9
  };
10
10
  /**
11
11
  * @description Проверяет значение на соответствие минимуму. Работает с: string, array, Date, number
@@ -21,6 +21,6 @@ type MinParams<ValidationType> = {
21
21
  * date(min(new Date())));
22
22
  * ```
23
23
  */
24
- export declare function min<ValidationType extends Date>(threshold: Date, params?: MinParams<ValidationType>): ReturnType<typeof createRule<Date, unknown>>;
25
- export declare function min<ValidationType extends BaseMinValidationTypes>(threshold: number, params?: MinParams<ValidationType>): ReturnType<typeof createRule<BaseMinValidationTypes, unknown>>;
24
+ export declare function min<ValidationType extends Date>(threshold: Date, params?: MinParams<ValidationType>): ReturnType<typeof createRule<Date>>;
25
+ export declare function min<ValidationType extends BaseMinValidationTypes>(threshold: number, params?: MinParams<ValidationType>): ReturnType<typeof createRule<BaseMinValidationTypes>>;
26
26
  export {};
@@ -15,5 +15,5 @@ type MobilePhoneParams = CommonRuleParams<string> & {
15
15
  * validate('79999999999');
16
16
  * ```
17
17
  */
18
- export declare const mobilePhone: <TValues>(params?: MobilePhoneParams) => (value: string, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
18
+ export declare const mobilePhone: <TLastSchemaValues extends Record<string, unknown>>(params?: MobilePhoneParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
19
19
  export {};
@@ -15,8 +15,8 @@ type AdditionalDefOptions = {
15
15
  * validate(24);
16
16
  * ```
17
17
  */
18
- export declare const number: <TValues>(...rules: ValidationRule<number, TValues>[]) => {
19
- (value: unknown, prevCtx?: import("../core").ValidationContext<TValues> | undefined): import("../core").ValidationResult;
18
+ export declare const number: <TLastSchemaValues extends Record<string, unknown>>(...rules: ValidationRule<number, TLastSchemaValues>[]) => {
19
+ (value: unknown, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined): import("../core").ValidationResult;
20
20
  define(overridesDefOptions: Partial<AdditionalDefOptions> & {
21
21
  requiredErrorMessage?: string | undefined;
22
22
  typeErrorMessage?: string | undefined;
@@ -3,9 +3,9 @@ import { Guard, ValidationContext, ValidationRule } from '../core';
3
3
  * @description Специальный итерфейс Guard для object. В данном интерфейсе ctx required
4
4
  * Переопределение необходимо для того, чтобы ts показывал, что ctx required в кастомных правилах
5
5
  */
6
- interface ObjectPropGuard<TValues> {
7
- (value: Parameters<Guard<TValues>>[0], ctx: ValidationContext<TValues>): ReturnType<Guard<TValues>>;
8
- define: Guard<TValues>['define'];
6
+ interface ObjectPropGuard<TLastSchemaValues extends Record<string, unknown>> {
7
+ (value: Parameters<Guard<TLastSchemaValues>>[0], ctx: ValidationContext<TLastSchemaValues>): ReturnType<Guard<TLastSchemaValues>>;
8
+ define: Guard<TLastSchemaValues>['define'];
9
9
  }
10
10
  type AdditionalDefOptions = {
11
11
  /**
@@ -16,11 +16,11 @@ type AdditionalDefOptions = {
16
16
  /**
17
17
  * @description Возможные значения, принимаемые схемой
18
18
  */
19
- export type SchemaValue<TValues> = ObjectPropGuard<TValues> | ValidationRule<unknown, TValues>;
19
+ export type SchemaValue<TValue extends Record<string, unknown>> = ObjectPropGuard<TValue> | ValidationRule<unknown, TValue>;
20
20
  /**
21
21
  * @description Схема правил валдиации для объекта
22
22
  */
23
- export type Schema<TValue extends Record<string, unknown>, TValues = unknown> = Record<keyof TValue, SchemaValue<TValues>>;
23
+ export type Schema<TValue extends Record<string, unknown>> = Record<keyof TValue, SchemaValue<TValue>>;
24
24
  /**
25
25
  * @description Guard для объекта
26
26
  * @param schema - схема валидации объекта
@@ -44,13 +44,13 @@ export type Schema<TValue extends Record<string, unknown>, TValues = unknown> =
44
44
  * });
45
45
  * ```
46
46
  */
47
- export declare const object: <TValue extends Record<string, unknown>, TValues = unknown>(schema: Schema<TValue, TValues>) => {
48
- (value: unknown, prevCtx?: ValidationContext<TValues> | undefined): import("../core").ValidationResult;
47
+ export declare const object: <TValue extends Record<string, unknown>, TLastSchemaValues extends Record<string, unknown> = {}>(schema: Schema<TValue>) => {
48
+ (value: unknown, prevCtx?: ValidationContext<TLastSchemaValues> | undefined): import("../core").ValidationResult;
49
49
  define(overridesDefOptions: Partial<AdditionalDefOptions> & {
50
50
  requiredErrorMessage?: string | undefined;
51
51
  typeErrorMessage?: string | undefined;
52
52
  isOptional?: boolean | undefined;
53
53
  }): any;
54
54
  };
55
- export type ObjectGuard<TValue extends Record<string, unknown>, TValues = unknown> = ReturnType<typeof object<TValue, TValues>>;
55
+ export type ObjectGuard<TValue extends Record<string, unknown>> = ReturnType<typeof object<TValue>>;
56
56
  export {};
package/object/object.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import isPlainObject from 'is-plain-obj';
2
- import { createErrorMap, createGuard, } from '../core';
2
+ import { createContext, createErrorMap, createGuard, } from '../core';
3
3
  import { optional } from '../optional';
4
4
  import { isEmptyErrors } from './isEmptyErrors';
5
5
  import { OBJECT_TYPE_ERROR_INFO } from './constants';
@@ -27,16 +27,17 @@ import { OBJECT_TYPE_ERROR_INFO } from './constants';
27
27
  * ```
28
28
  */
29
29
  export const object = (schema) => createGuard((value, ctx, { typeErrorMessage, isPartial }) => {
30
+ const context = createContext(ctx, value, value);
30
31
  if (!isPlainObject(value)) {
31
- return ctx.createError(Object.assign(Object.assign({}, OBJECT_TYPE_ERROR_INFO), { message: typeErrorMessage || OBJECT_TYPE_ERROR_INFO.message }));
32
+ return context.createError(Object.assign(Object.assign({}, OBJECT_TYPE_ERROR_INFO), { message: typeErrorMessage || OBJECT_TYPE_ERROR_INFO.message }));
32
33
  }
33
34
  const generateErrorMap = () => {
34
35
  const schemaEntries = Object.entries(schema);
35
- const isOptional = ctx.global.overrides.objectIsPartial || isPartial;
36
+ const isOptional = context.global.overrides.objectIsPartial || isPartial;
36
37
  return schemaEntries.reduce((errorMap, [key, rule]) => {
37
38
  const isGuard = 'define' in rule;
38
39
  const callRule = isGuard && isOptional ? optional(rule) : rule;
39
- errorMap[key] = callRule(value[key], ctx);
40
+ errorMap[key] = callRule(value[key], context);
40
41
  return errorMap;
41
42
  }, {});
42
43
  };
@@ -13,5 +13,5 @@ type OgrnIPParams = CommonRuleParams<string> & {
13
13
  * validate('7728168971');
14
14
  * ```
15
15
  */
16
- export declare const ogrnIP: <TValues>(params?: OgrnIPParams) => (value: string, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
16
+ export declare const ogrnIP: <TLastSchemaValues extends Record<string, unknown>>(params?: OgrnIPParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
17
17
  export {};
@@ -13,5 +13,5 @@ type OgrnULParams = CommonRuleParams<string> & {
13
13
  * validate('7728168971');
14
14
  * ```
15
15
  */
16
- export declare const ogrnUL: <TValues>(params?: OgrnULParams) => (value: string, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
16
+ export declare const ogrnUL: <TLastSchemaValues extends Record<string, unknown>>(params?: OgrnULParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
17
17
  export {};
@@ -12,5 +12,5 @@ type OnlyNumberParams = {
12
12
  * validate('123');
13
13
  * ```
14
14
  */
15
- export declare const onlyNumber: <TValues>(params?: OnlyNumberParams) => (value: string, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
15
+ export declare const onlyNumber: <TLastSchemaValues extends Record<string, unknown>>(params?: OnlyNumberParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
16
16
  export {};
@@ -4,4 +4,4 @@ import { Guard } from '../core';
4
4
  * @param guard - правило, проверяющее тип значения
5
5
  * @example object({ name: optional(string(min(22))) })
6
6
  */
7
- export declare const optional: <TValues>(guard: Guard<TValues, {}>) => Guard<TValues, {}>;
7
+ export declare const optional: <TLastSchemaValues extends Record<string, unknown>>(guard: Guard<TLastSchemaValues, {}>) => Guard<TLastSchemaValues, {}>;
package/or/or.d.ts CHANGED
@@ -11,4 +11,4 @@ import { ValidationResult, ValidationRule } from '../core';
11
11
  * const result = validate('string');
12
12
  * ```
13
13
  */
14
- export declare const or: <TValues>(...rules: ValidationRule<unknown, TValues>[]) => (value: unknown, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => ValidationResult;
14
+ export declare const or: <TLastSchemaValues extends Record<string, unknown>>(...rules: ValidationRule<unknown, TLastSchemaValues>[]) => (value: unknown, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => ValidationResult;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astral/validations",
3
- "version": "3.3.0",
3
+ "version": "4.0.0",
4
4
  "browser": "./index.js",
5
5
  "main": "./index.js",
6
6
  "dependencies": {
@@ -5,7 +5,7 @@ import { object } from '../object';
5
5
  * @example partial(object({ name: string() }))
6
6
  */
7
7
  export declare const partial: (objectGuard: ReturnType<typeof object>) => {
8
- (value: unknown, prevCtx?: import("../core").ValidationContext<unknown> | undefined): import("../core").ValidationResult;
8
+ (value: unknown, prevCtx?: import("../core").ValidationContext<Record<string, unknown>> | undefined): import("../core").ValidationResult;
9
9
  define(overridesDefOptions: Partial<{
10
10
  isPartial?: boolean | undefined;
11
11
  }> & {
@@ -14,5 +14,5 @@ type PatternParams = {
14
14
  * string(pattern(/[0-9]/))
15
15
  * ```
16
16
  */
17
- export declare const pattern: <TValues>(regex: RegExp, params?: PatternParams) => (value: string, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
17
+ export declare const pattern: <TLastSchemaValues extends Record<string, unknown>>(regex: RegExp, params?: PatternParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
18
18
  export {};
@@ -21,5 +21,5 @@ type PositiveNumberParams = {
21
21
  * validate(-1)
22
22
  * ```
23
23
  */
24
- export declare const positiveNumber: <TValues>(params?: PositiveNumberParams) => (value: number, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
24
+ export declare const positiveNumber: <TLastSchemaValues extends Record<string, unknown>>(params?: PositiveNumberParams) => (value: number, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
25
25
  export {};
package/snils/snils.d.ts CHANGED
@@ -13,5 +13,5 @@ type SnilsParams = CommonRuleParams<string> & {
13
13
  * validate('15657325992');
14
14
  * ```
15
15
  */
16
- export declare const snils: <TValues>(params?: SnilsParams) => (value: string, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
16
+ export declare const snils: <TLastSchemaValues extends Record<string, unknown>>(params?: SnilsParams) => (value: string, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
17
17
  export {};
@@ -1,6 +1,6 @@
1
1
  import { ValidationRule } from '../core';
2
- export declare const string: <TValues>(...rules: ValidationRule<string, TValues>[]) => {
3
- (value: unknown, prevCtx?: import("../core").ValidationContext<TValues> | undefined): import("../core").ValidationResult;
2
+ export declare const string: <TLastSchemaValues extends Record<string, unknown>>(...rules: ValidationRule<string, TLastSchemaValues>[]) => {
3
+ (value: unknown, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined): import("../core").ValidationResult;
4
4
  define(overridesDefOptions: Partial<{}> & {
5
5
  requiredErrorMessage?: string | undefined;
6
6
  typeErrorMessage?: string | undefined;
@@ -14,5 +14,5 @@ type Transformer<TValue, TResult> = (value: TValue) => TResult;
14
14
  * );
15
15
  * ```
16
16
  */
17
- export declare const transform: <TValue extends unknown, TResult extends unknown, TValues>(transformer: Transformer<TValue, TResult>, ...rules: ValidationRule<TResult, TValues>[]) => (value: TValue, prevCtx?: import("../core").ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
17
+ export declare const transform: <TValue extends unknown, TResult extends unknown, TLastSchemaValues extends Record<string, unknown> = {}>(transformer: Transformer<TValue, TResult>, ...rules: ValidationRule<TResult, TLastSchemaValues>[]) => (value: TValue, prevCtx?: import("../core").ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
18
18
  export {};
package/when/when.d.ts CHANGED
@@ -1,17 +1,17 @@
1
1
  import { ValidationContext, ValidationRule } from '../core';
2
- type Params<TValues> = {
2
+ type Params<TLastSchemaValues extends Record<string, unknown>> = {
3
3
  /**
4
4
  * @description Условие для выбора ветки
5
5
  */
6
- is: (value: unknown, ctx: ValidationContext<TValues>) => boolean;
6
+ is: (value: unknown, ctx: ValidationContext<TLastSchemaValues>) => boolean;
7
7
  /**
8
8
  * Правила валидации, применяемые если is === true
9
9
  */
10
- then: ValidationRule<unknown, TValues>;
10
+ then: ValidationRule<unknown, TLastSchemaValues>;
11
11
  /**
12
12
  * Правила валидации, применяемые если is === false
13
13
  */
14
- otherwise: ValidationRule<unknown, TValues>;
14
+ otherwise: ValidationRule<unknown, TLastSchemaValues>;
15
15
  };
16
16
  /**
17
17
  * @description Позволяет указывать условные валидации
@@ -19,7 +19,7 @@ type Params<TValues> = {
19
19
  * ```ts
20
20
  * type Values = { name: string; isAgree: boolean };
21
21
  *
22
- * const validate = object<Values, Values>({
22
+ * const validate = object<Values>({
23
23
  * name: when({
24
24
  * is: (_, ctx) => ctx.global.values.isAgree,
25
25
  * then: string(),
@@ -35,5 +35,5 @@ type Params<TValues> = {
35
35
  * const result2 = validate({ isAgree: true, name: '' });
36
36
  * ```
37
37
  */
38
- export declare const when: <TValues>({ is, then, otherwise }: Params<TValues>) => (value: unknown, prevCtx?: ValidationContext<TValues> | undefined) => import("../core").ValidationResult;
38
+ export declare const when: <TLastSchemaValues extends Record<string, unknown>>({ is, then, otherwise, }: Params<TLastSchemaValues>) => (value: unknown, prevCtx?: ValidationContext<TLastSchemaValues> | undefined) => import("../core").ValidationResult;
39
39
  export {};
package/when/when.js CHANGED
@@ -5,7 +5,7 @@ import { createRule } from '../core';
5
5
  * ```ts
6
6
  * type Values = { name: string; isAgree: boolean };
7
7
  *
8
- * const validate = object<Values, Values>({
8
+ * const validate = object<Values>({
9
9
  * name: when({
10
10
  * is: (_, ctx) => ctx.global.values.isAgree,
11
11
  * then: string(),
@@ -21,7 +21,7 @@ import { createRule } from '../core';
21
21
  * const result2 = validate({ isAgree: true, name: '' });
22
22
  * ```
23
23
  */
24
- export const when = ({ is, then, otherwise }) => createRule((value, ctx) => {
24
+ export const when = ({ is, then, otherwise, }) => createRule((value, ctx) => {
25
25
  if (is(value, ctx)) {
26
26
  return then(value, ctx);
27
27
  }