Skip to content

Commit 4ba3d32

Browse files
committed
Update type declarations including validator.js-asserts
- Update `validator.js-asserts@9.0.0` - Refactors the type declarations in line with what's done on `validator.js-asserts`, including their exported types
1 parent ebf9529 commit 4ba3d32

3 files changed

Lines changed: 190 additions & 107 deletions

File tree

index.d.ts

Lines changed: 184 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,50 @@
11
import type { Assert as BaseAssert, Constraint as BaseConstraint } from 'validator.js';
2+
import type { ValidatorJSAsserts } from 'validator.js-asserts';
23

34
/**
4-
* Valid values for constraint mapping
5+
* The instance‐side of an Assert (no static factory methods).
6+
* All core “is.X()” methods and custom asserts produce this.
7+
*/
8+
interface AssertInstance {
9+
/** Returns `true` if the value passes, otherwise returns a Violation/object. */
10+
check(value: unknown, group?: string | string[], context?: unknown): true | any;
11+
/** Throws on failure; returns `true` if the value passes. */
12+
validate(value: unknown, group?: string | string[], context?: unknown): true;
13+
/** Does this assert apply to the given validation group(s)? */
14+
requiresValidation(group?: string | string[]): boolean;
15+
/** Is this assert assigned to the given group? */
16+
hasGroup(group: string | string[]): boolean;
17+
/** Is this assert in any of the provided groups? */
18+
hasOneOf(groups: string[]): boolean;
19+
/** Does this assert belong to at least one group? */
20+
hasGroups(): boolean;
21+
}
22+
23+
/**
24+
* The instance‐side of a Constraint (no static/constructor methods).
25+
* Mirrors the Assert API but for Constraint objects.
26+
*/
27+
interface ConstraintInstance extends BaseConstraint {
28+
/** Check if value matches the constraint */
29+
check(value: unknown, group?: string | string[], context?: unknown): true | any;
30+
/** Validate the value against the constraint */
31+
validate(value: unknown, group?: string | string[], context?: unknown): true;
32+
/** Check if the constraint requires validation */
33+
requiresValidation(group?: string | string[]): boolean;
34+
/** Check if the constraint belongs to a specific group */
35+
hasGroup(group: string | string[]): boolean;
36+
/** Check `hasGroup` over the specified groups */
37+
hasOneOf(groups: string[]): boolean;
38+
/** Check if the constraint has any groups */
39+
hasGroups(): boolean;
40+
}
41+
42+
/**
43+
* Valid types that can appear in a constraint mapping:
44+
* - an Assert instance
45+
* - a Constraint instance
46+
* - a nested object mapping
47+
* - an array of any of the above
548
*/
649
type ConstraintValue =
750
| BaseAssert
@@ -14,187 +57,228 @@ type ConstraintValue =
1457
* All core `validator.js` assert factories.
1558
*/
1659
interface CoreAssertsMap {
17-
/** An object must have the given property. */
18-
haveProperty(node: string): ConstraintValue;
60+
/** Object must have the given property. */
61+
haveProperty(node: string): AssertInstance;
1962

2063
/** Alias for `haveProperty`. */
21-
propertyDefined(node: string): ConstraintValue;
64+
propertyDefined(node: string): AssertInstance;
2265

23-
/** A string must be empty or only whitespace. */
24-
blank(): ConstraintValue;
66+
/** String must be empty or only whitespace. */
67+
blank(): AssertInstance;
2568

26-
/** Run a custom callback that returns true on success. */
27-
callback(fn: (value: unknown, ...args: unknown[]) => boolean, ...args: unknown[]): ConstraintValue;
69+
/** Run a custom function that returns true on success. */
70+
callback(fn: (value: unknown, ...args: unknown[]) => boolean, ...args: unknown[]): AssertInstance;
2871

29-
/** Value must be one of the provided list. */
30-
choice(list: unknown[] | (() => unknown[])): ConstraintValue;
72+
/** Value must be one of the supplied list. */
73+
choice(list: unknown[] | (() => unknown[])): AssertInstance;
3174

32-
/** Validate each element of an array. */
33-
collection(assertOrConstraint: ConstraintValue | BaseConstraint | object): ConstraintValue;
75+
/** Each element of an array must match the given Assert/Constraint. */
76+
collection(assertOrConstraint: ConstraintValue | ConstraintInstance | object): AssertInstance;
3477

35-
/** Array must have exactly N items. */
36-
count(count: number | ((arr: unknown[]) => number)): ConstraintValue;
78+
/** Array must have exactly N items (or N computed from a function). */
79+
count(count: number | ((arr: unknown[]) => number)): AssertInstance;
3780

3881
/** Valid email address. */
39-
email(): ConstraintValue;
82+
email(): AssertInstance;
4083

41-
/** Value must equal reference or match function. */
42-
equalTo(reference: unknown | ((value: unknown) => unknown)): ConstraintValue;
84+
/** Value must equal the reference or match the provided function. */
85+
equalTo(reference: unknown | ((value: unknown) => unknown)): AssertInstance;
4386

4487
/** Numeric value must be > threshold. */
45-
greaterThan(threshold: number): ConstraintValue;
88+
greaterThan(threshold: number): AssertInstance;
4689

4790
/** Numeric value must be ≥ threshold. */
48-
greaterThanOrEqual(threshold: number): ConstraintValue;
91+
greaterThanOrEqual(threshold: number): AssertInstance;
4992

50-
/** Value must be `instanceof` the given class. */
51-
instanceOf(classRef: new (...args: unknown[]) => unknown): ConstraintValue;
93+
/** Value must be `instanceof` the specified class. */
94+
instanceOf(classRef: new (...args: unknown[]) => unknown): AssertInstance;
5295

5396
/** Value must be a string. */
54-
string(): ConstraintValue;
97+
string(): AssertInstance;
5598

5699
/** String/array length must be within `[min, max]`. */
57-
length(boundaries: { min?: number; max?: number }): ConstraintValue;
100+
length(boundaries: { min?: number; max?: number }): AssertInstance;
58101

59102
/** Alias for `length()`. */
60-
ofLength(boundaries: { min?: number; max?: number }): ConstraintValue;
103+
ofLength(boundaries: { min?: number; max?: number }): AssertInstance;
61104

62105
/** Numeric value must be < threshold. */
63-
lessThan(threshold: number): ConstraintValue;
106+
lessThan(threshold: number): AssertInstance;
64107

65108
/** Numeric value must be ≤ threshold. */
66-
lessThanOrEqual(threshold: number): ConstraintValue;
109+
lessThanOrEqual(threshold: number): AssertInstance;
67110

68111
/** Value must not be null or undefined. */
69-
notNull(): ConstraintValue;
112+
notNull(): AssertInstance;
70113

71-
/** String must contain ≥1 non-whitespace character. */
72-
notBlank(): ConstraintValue;
114+
/** String must contain at least one non-whitespace character. */
115+
notBlank(): AssertInstance;
73116

74-
/** Value must not equal reference or match fn. */
75-
notEqualTo(reference: unknown | ((value: unknown) => unknown)): ConstraintValue;
117+
/** Value must not equal the reference or match the provided function. */
118+
notEqualTo(reference: unknown | ((value: unknown) => unknown)): AssertInstance;
76119

77120
/** Value must be exactly null. */
78-
null(): ConstraintValue;
121+
null(): AssertInstance;
79122

80-
/** `Number`/`String`/`Array` must fall within `[min, max]`. */
81-
range(min: number, max: number): ConstraintValue;
123+
/** `Number`/`String`/`Array` must lie within `[min, max]`. */
124+
range(min: number, max: number): AssertInstance;
82125

83126
/** `String` must match the given `RegExp`. */
84-
regexp(regexp: string | RegExp, flag?: string): ConstraintValue;
127+
regexp(regexp: string | RegExp, flag?: string): AssertInstance;
85128

86129
/** Value must be defined (not `undefined`). */
87-
required(): ConstraintValue;
130+
required(): AssertInstance;
88131

89-
/** Array items must be unique (by `key` if given). */
90-
unique(opts?: { key: string }): ConstraintValue;
132+
/** Array items must be unique (optionally by `key`). */
133+
unique(opts?: { key: string }): AssertInstance;
91134

92-
/** If `context[ref]` passes `is`, run `then` else `otherwise`. */
135+
/**
136+
* If `context[ref]` satisfies `options.is`, run `options.then`; otherwise `options.otherwise`.
137+
*/
93138
when(
94139
ref: string,
95140
options: {
96141
is: ConstraintValue | object;
97142
then?: ConstraintValue | object;
98143
otherwise?: ConstraintValue | object;
99144
}
100-
): ConstraintValue;
145+
): AssertInstance;
101146
}
102147

103-
type ExtraAssertType = {
104-
[key: string]: ConstraintValue;
105-
};
106-
107148
/**
108-
* Map runtime‐passed `extraAsserts` into uncapitalized methods.
109-
* This can include both built‐ins *and* entirely custom keys.
149+
* If the user passes an object of `extraAsserts` (e.g. `{ MyFoo: () => new FooAssert() }`),
150+
* this type will expose each key as a lowercase method returning `AssertInstance`.
110151
*/
111-
type ExtraAsserts<EA extends ExtraAssertType> = {
112-
[K in keyof EA as Uncapitalize<string & K>]: EA[K];
113-
};
152+
type ExtraAsserts<EA> = EA extends Record<string, any>
153+
? {
154+
[K in keyof EA as Uncapitalize<string & K>]: () => AssertInstance;
155+
}
156+
: {};
114157

115-
/** Callable/newable `Assert` constructor. */
158+
/** Callable/newable `Assert` constructor function itself. */
116159
interface BaseAssertStatic {
117-
new (group?: string | string[]): BaseAssert;
118-
(group?: string | string[]): BaseAssert;
160+
new (group?: string | string[]): AssertInstance;
161+
(group?: string | string[]): AssertInstance;
119162
}
120163

121164
/**
122-
* The full `is` API:
123-
* - BaseAssert constructor.
124-
* - core `validator.js` asserts.
125-
* - all `validator.js-asserts` (camelCased).
126-
* - any `extraAsserts` passed at runtime.
165+
* Everything available under `is`:
166+
* - The base‐factory (`new is()` or `is()`).
167+
* - All core `validator.js` methods (`haveProperty`, `blank`, `email`, …).
168+
* - All built‐in `validator.js-asserts` (via `ValidatorJSAsserts`).
169+
* - Any user‐passed `extraAsserts` (lowercased).
127170
*/
128-
type AssertStatic<EA extends ExtraAssertType> = BaseAssertStatic & CoreAssertsMap & ExtraAsserts<EA> & ExtraAssertType;
171+
type AssertStatic<EA> = BaseAssertStatic & CoreAssertsMap & ValidatorJSAsserts & ExtraAsserts<EA>;
129172

130-
/** Map a data type to `validator.js` constraints. */
173+
/**
174+
* Given a type `T`, map each key to either:
175+
* - a single `ConstraintValue`, or
176+
* - an array of `ConstraintValue`.
177+
*
178+
* @example `{ foo: is.string(), bar: [is.required(), is.email()] }`
179+
*/
131180
type ConstraintMapping<T> =
132181
| { [P in keyof T]?: ConstraintValue | ConstraintValue[] }
133182
| Record<string, ConstraintValue | ConstraintValue[]>;
134183

135-
/** `validate`/`assert` function signature. */
184+
/** Signature of `assert(data, constraints)` or `validate(data, constraints)`. */
136185
type ValidateFunction = <T>(data: T, constraints: ConstraintMapping<T> | Record<string, ConstraintValue>) => T;
137186

138-
/** Type of `Error` to pass to `AssertionError`/`ValidationError`. */
187+
/** Custom Error type for `AssertionError`/`ValidationError`. */
139188
type ValidatorErrorType = new (...args: any[]) => Error;
140189

141-
/** Options for creating a validator. */
142-
interface ValidatorOptions<EA extends ExtraAssertType = ExtraAssertType> {
143-
AssertionError?: ValidatorErrorType;
144-
ValidationError?: ValidatorErrorType;
145-
extraAsserts?: EA;
146-
logger?: (errors: any) => void;
147-
obfuscator?: (input: { errors: any }) => { errors: any };
148-
mask?: boolean;
149-
}
150-
151-
/**
152-
* Base exports with just `is`.
153-
*/
154-
interface BaseValidatorExports<EA extends ExtraAssertType = ExtraAssertType> {
190+
/** You always get an `{ is: AssertStatic<EA> }` back. */
191+
interface BaseValidatorExports<EA = any> {
155192
is: AssertStatic<EA>;
156193
}
157194

158-
/**
159-
* Exports with `assert` added when `AssertionError` is provided.
160-
*/
161-
interface ValidatorExportsWithAssert<EA extends ExtraAssertType = ExtraAssertType> extends BaseValidatorExports<EA> {
195+
/** If `AssertionError` was passed, you also get `assert(data, …)`. */
196+
interface ValidatorExportsWithAssert<EA = any> extends BaseValidatorExports<EA> {
162197
assert: ValidateFunction;
163198
}
164199

165-
/**
166-
* Exports with `validate` added when `ValidationError` is provided.
167-
*/
168-
interface ValidatorExportsWithValidate<EA extends ExtraAssertType = ExtraAssertType> extends BaseValidatorExports<EA> {
200+
/** If `ValidationError` was passed, you also get `validate(data, …)`. */
201+
interface ValidatorExportsWithValidate<EA = any> extends BaseValidatorExports<EA> {
169202
validate: ValidateFunction;
170203
}
171204

172-
/**
173-
* Exports with both `assert` and `validate` when both errors are provided.
174-
*/
175-
interface ValidatorExportsWithBoth<EA extends ExtraAssertType = ExtraAssertType> extends BaseValidatorExports<EA> {
205+
/** If both errors were passed, you get both `assert` and `validate`. */
206+
interface ValidatorExportsWithBoth<EA = any> extends BaseValidatorExports<EA> {
176207
assert: ValidateFunction;
177208
validate: ValidateFunction;
178209
}
179210

180211
/**
181-
* Factory function to create a `validator` instance.
212+
* Create a new validator instance.
213+
* TypeScript will infer `EA` from the shape of `options.extraAsserts`.
214+
*
215+
* - If you supply both `AssertionError` and `ValidationError`, you get: `{ is, assert, validate }`
216+
* - If you supply only one of them, you get exactly that method plus `is`.
217+
* - If you supply neither, you get only `{ is }`.
182218
*/
183-
declare function validator<EA extends ExtraAssertType = ExtraAssertType>(
184-
options: ValidatorOptions<EA> & { AssertionError: ValidatorErrorType; ValidationError: ValidatorErrorType }
185-
): ValidatorExportsWithBoth<EA>;
219+
declare function validator<EA extends Record<string, any>>(options: {
220+
AssertionError: ValidatorErrorType;
221+
ValidationError: ValidatorErrorType;
222+
extraAsserts: EA;
223+
logger?: (errors: any) => void;
224+
obfuscator?: (input: { errors: any }) => { errors: any };
225+
mask?: boolean;
226+
}): ValidatorExportsWithBoth<EA>;
227+
228+
declare function validator(options: {
229+
AssertionError: ValidatorErrorType;
230+
ValidationError: ValidatorErrorType;
231+
extraAsserts?: undefined;
232+
logger?: (errors: any) => void;
233+
obfuscator?: (input: { errors: any }) => { errors: any };
234+
mask?: boolean;
235+
}): ValidatorExportsWithBoth<{}>;
236+
237+
declare function validator<EA extends Record<string, any>>(options: {
238+
AssertionError: ValidatorErrorType;
239+
extraAsserts: EA;
240+
logger?: (errors: any) => void;
241+
obfuscator?: (input: { errors: any }) => { errors: any };
242+
mask?: boolean;
243+
}): ValidatorExportsWithAssert<EA>;
244+
245+
declare function validator(options: {
246+
AssertionError: ValidatorErrorType;
247+
extraAsserts?: undefined;
248+
logger?: (errors: any) => void;
249+
obfuscator?: (input: { errors: any }) => { errors: any };
250+
mask?: boolean;
251+
}): ValidatorExportsWithAssert<{}>;
186252

187-
declare function validator<EA extends ExtraAssertType = ExtraAssertType>(
188-
options: ValidatorOptions<EA> & { AssertionError: ValidatorErrorType }
189-
): ValidatorExportsWithAssert<EA>;
253+
declare function validator<EA extends Record<string, any>>(options: {
254+
ValidationError: ValidatorErrorType;
255+
extraAsserts: EA;
256+
logger?: (errors: any) => void;
257+
obfuscator?: (input: { errors: any }) => { errors: any };
258+
mask?: boolean;
259+
}): ValidatorExportsWithValidate<EA>;
190260

191-
declare function validator<EA extends ExtraAssertType = ExtraAssertType>(
192-
options: ValidatorOptions<EA> & { ValidationError: ValidatorErrorType }
193-
): ValidatorExportsWithValidate<EA>;
261+
declare function validator(options: {
262+
ValidationError: ValidatorErrorType;
263+
extraAsserts?: undefined;
264+
logger?: (errors: any) => void;
265+
obfuscator?: (input: { errors: any }) => { errors: any };
266+
mask?: boolean;
267+
}): ValidatorExportsWithValidate<{}>;
194268

195-
declare function validator<EA extends ExtraAssertType = ExtraAssertType>(
196-
options?: ValidatorOptions<EA>
197-
): BaseValidatorExports<EA>;
269+
declare function validator<EA extends Record<string, any>>(options?: {
270+
extraAsserts: EA;
271+
logger?: (errors: any) => void;
272+
obfuscator?: (input: { errors: any }) => { errors: any };
273+
mask?: boolean;
274+
}): BaseValidatorExports<EA>;
275+
276+
declare function validator(options?: {
277+
extraAsserts?: undefined;
278+
logger?: (errors: any) => void;
279+
obfuscator?: (input: { errors: any }) => { errors: any };
280+
mask?: boolean;
281+
}): BaseValidatorExports<{}>;
198282

199283
/**
200284
* Export `validator`.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
"json-mask": "^2.0.0",
2424
"lodash": "^4.17.21",
2525
"validator.js": "^2.0.3",
26-
"validator.js-asserts": "^7.3.1"
26+
"validator.js-asserts": "^9.0.0"
2727
},
2828
"devDependencies": {
2929
"@fastify/pre-commit": "^2.2.0",

0 commit comments

Comments
 (0)