bguard 0.0.5 → 0.0.7
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.
- package/lib/InferType.js +1 -19
- package/lib/InferType.js.map +1 -1
- package/lib/asserts/array/index.js +7 -86
- package/lib/asserts/array/index.js.map +1 -1
- package/lib/asserts/array/index.mjs +7 -59
- package/lib/asserts/array/index.mjs.map +1 -1
- package/lib/asserts/boolean/index.js +7 -114
- package/lib/asserts/boolean/index.js.map +1 -1
- package/lib/asserts/boolean/index.mjs +7 -87
- package/lib/asserts/boolean/index.mjs.map +1 -1
- package/lib/asserts/common/equalTo.js +4 -50
- package/lib/asserts/common/equalTo.js.map +1 -1
- package/lib/asserts/common/equalTo.mjs +4 -23
- package/lib/asserts/common/equalTo.mjs.map +1 -1
- package/lib/asserts/common/index.js +6 -68
- package/lib/asserts/common/index.js.map +1 -1
- package/lib/asserts/common/index.mjs +6 -41
- package/lib/asserts/common/index.mjs.map +1 -1
- package/lib/asserts/number/index.js +8 -108
- package/lib/asserts/number/index.js.map +1 -1
- package/lib/asserts/number/index.mjs +8 -81
- package/lib/asserts/number/index.mjs.map +1 -1
- package/lib/asserts/number/max.js +6 -47
- package/lib/asserts/number/max.js.map +1 -1
- package/lib/asserts/number/max.mjs +3 -17
- package/lib/asserts/number/max.mjs.map +1 -1
- package/lib/asserts/number/maxExcluded.js +6 -47
- package/lib/asserts/number/maxExcluded.js.map +1 -1
- package/lib/asserts/number/maxExcluded.mjs +3 -17
- package/lib/asserts/number/maxExcluded.mjs.map +1 -1
- package/lib/asserts/number/min.js +6 -47
- package/lib/asserts/number/min.js.map +1 -1
- package/lib/asserts/number/min.mjs +3 -17
- package/lib/asserts/number/min.mjs.map +1 -1
- package/lib/asserts/number/minExcluded.js +6 -47
- package/lib/asserts/number/minExcluded.js.map +1 -1
- package/lib/asserts/number/minExcluded.mjs +3 -17
- package/lib/asserts/number/minExcluded.mjs.map +1 -1
- package/lib/asserts/number/negative.js +6 -47
- package/lib/asserts/number/negative.js.map +1 -1
- package/lib/asserts/number/negative.mjs +3 -17
- package/lib/asserts/number/negative.mjs.map +1 -1
- package/lib/asserts/number/positive.js +6 -47
- package/lib/asserts/number/positive.js.map +1 -1
- package/lib/asserts/number/positive.mjs +3 -17
- package/lib/asserts/number/positive.mjs.map +1 -1
- package/lib/asserts/object/index.js +7 -90
- package/lib/asserts/object/index.js.map +1 -1
- package/lib/asserts/object/index.mjs +7 -63
- package/lib/asserts/object/index.mjs.map +1 -1
- package/lib/asserts/string/email.js +6 -47
- package/lib/asserts/string/email.js.map +1 -1
- package/lib/asserts/string/email.mjs +3 -17
- package/lib/asserts/string/email.mjs.map +1 -1
- package/lib/asserts/string/index.js +8 -108
- package/lib/asserts/string/index.js.map +1 -1
- package/lib/asserts/string/index.mjs +8 -81
- package/lib/asserts/string/index.mjs.map +1 -1
- package/lib/asserts/string/maxLength.js +6 -47
- package/lib/asserts/string/maxLength.js.map +1 -1
- package/lib/asserts/string/maxLength.mjs +3 -17
- package/lib/asserts/string/maxLength.mjs.map +1 -1
- package/lib/asserts/string/minLength.js +6 -47
- package/lib/asserts/string/minLength.js.map +1 -1
- package/lib/asserts/string/minLength.mjs +3 -17
- package/lib/asserts/string/minLength.mjs.map +1 -1
- package/lib/asserts/string/regExp.js +6 -47
- package/lib/asserts/string/regExp.js.map +1 -1
- package/lib/asserts/string/regExp.mjs +3 -17
- package/lib/asserts/string/regExp.mjs.map +1 -1
- package/lib/chunk-2AP4OQMT.js +26 -0
- package/lib/chunk-2AP4OQMT.js.map +1 -0
- package/lib/chunk-32IQXZRK.mjs +13 -0
- package/lib/chunk-32IQXZRK.mjs.map +1 -0
- package/lib/chunk-3FEJUC3K.mjs +13 -0
- package/lib/chunk-3FEJUC3K.mjs.map +1 -0
- package/lib/chunk-5NCJN6D2.js +70 -0
- package/lib/chunk-5NCJN6D2.js.map +1 -0
- package/lib/chunk-5ZMICHV3.js +21 -0
- package/lib/chunk-5ZMICHV3.js.map +1 -0
- package/lib/chunk-63IQFNFO.mjs +27 -0
- package/lib/chunk-63IQFNFO.mjs.map +1 -0
- package/lib/chunk-A2SAWKJA.mjs +13 -0
- package/lib/chunk-A2SAWKJA.mjs.map +1 -0
- package/lib/chunk-A3UTB4RE.mjs +28 -0
- package/lib/chunk-A3UTB4RE.mjs.map +1 -0
- package/lib/chunk-A7I2JEQO.js +13 -0
- package/lib/chunk-A7I2JEQO.js.map +1 -0
- package/lib/chunk-AJ4WV5DG.mjs +13 -0
- package/lib/chunk-AJ4WV5DG.mjs.map +1 -0
- package/lib/chunk-APTTIN2L.js +42 -0
- package/lib/chunk-APTTIN2L.js.map +1 -0
- package/lib/chunk-AXOP6HPJ.js +14 -0
- package/lib/chunk-AXOP6HPJ.js.map +1 -0
- package/lib/chunk-BGMR7A6X.mjs +13 -0
- package/lib/chunk-BGMR7A6X.mjs.map +1 -0
- package/lib/chunk-FCFO5J5Y.mjs +14 -0
- package/lib/chunk-FCFO5J5Y.mjs.map +1 -0
- package/lib/chunk-GEZME6V2.mjs +39 -0
- package/lib/chunk-GEZME6V2.mjs.map +1 -0
- package/lib/chunk-GNBSKTFV.js +27 -0
- package/lib/chunk-GNBSKTFV.js.map +1 -0
- package/lib/chunk-IQ3QYABE.js +32 -0
- package/lib/chunk-IQ3QYABE.js.map +1 -0
- package/lib/chunk-K2S3FS5K.js +13 -0
- package/lib/chunk-K2S3FS5K.js.map +1 -0
- package/lib/chunk-KCBOOOTF.mjs +13 -0
- package/lib/chunk-KCBOOOTF.mjs.map +1 -0
- package/lib/chunk-L6A7NXUJ.js +13 -0
- package/lib/chunk-L6A7NXUJ.js.map +1 -0
- package/lib/chunk-L7HUXYFV.mjs +42 -0
- package/lib/chunk-L7HUXYFV.mjs.map +1 -0
- package/lib/chunk-LHTJHMKJ.mjs +27 -0
- package/lib/chunk-LHTJHMKJ.mjs.map +1 -0
- package/lib/chunk-NOADI6PO.mjs +21 -0
- package/lib/chunk-NOADI6PO.mjs.map +1 -0
- package/lib/chunk-NWY33MFU.js +13 -0
- package/lib/chunk-NWY33MFU.js.map +1 -0
- package/lib/chunk-P3Y6IWFA.mjs +70 -0
- package/lib/chunk-P3Y6IWFA.mjs.map +1 -0
- package/lib/chunk-PDVXBE27.js +27 -0
- package/lib/chunk-PDVXBE27.js.map +1 -0
- package/lib/chunk-PJP63SJT.js +13 -0
- package/lib/chunk-PJP63SJT.js.map +1 -0
- package/lib/chunk-QJOXKH7A.mjs +26 -0
- package/lib/chunk-QJOXKH7A.mjs.map +1 -0
- package/lib/chunk-QKGQ4XZC.js +13 -0
- package/lib/chunk-QKGQ4XZC.js.map +1 -0
- package/lib/chunk-QYLH5ZAC.mjs +32 -0
- package/lib/chunk-QYLH5ZAC.mjs.map +1 -0
- package/lib/chunk-VPFIIM2X.js +39 -0
- package/lib/chunk-VPFIIM2X.js.map +1 -0
- package/lib/chunk-YXHH5BF6.js +28 -0
- package/lib/chunk-YXHH5BF6.js.map +1 -0
- package/lib/core.js +6 -107
- package/lib/core.js.map +1 -1
- package/lib/core.mjs +5 -78
- package/lib/core.mjs.map +1 -1
- package/lib/exceptions.js +9 -50
- package/lib/exceptions.js.map +1 -1
- package/lib/exceptions.mjs +5 -19
- package/lib/exceptions.mjs.map +1 -1
- package/lib/index.js +29 -283
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +34 -252
- package/lib/index.mjs.map +1 -1
- package/lib/parseSchema.js +5 -115
- package/lib/parseSchema.js.map +1 -1
- package/lib/parseSchema.mjs +5 -88
- package/lib/parseSchema.mjs.map +1 -1
- package/lib/schemas/ArraySchema.js +6 -81
- package/lib/schemas/ArraySchema.js.map +1 -1
- package/lib/schemas/ArraySchema.mjs +6 -54
- package/lib/schemas/ArraySchema.mjs.map +1 -1
- package/lib/schemas/BooleanSchema.js +6 -109
- package/lib/schemas/BooleanSchema.js.map +1 -1
- package/lib/schemas/BooleanSchema.mjs +6 -82
- package/lib/schemas/BooleanSchema.mjs.map +1 -1
- package/lib/schemas/CommonSchema.js +5 -63
- package/lib/schemas/CommonSchema.js.map +1 -1
- package/lib/schemas/CommonSchema.mjs +5 -36
- package/lib/schemas/CommonSchema.mjs.map +1 -1
- package/lib/schemas/NumberSchema.js +7 -103
- package/lib/schemas/NumberSchema.js.map +1 -1
- package/lib/schemas/NumberSchema.mjs +7 -76
- package/lib/schemas/NumberSchema.mjs.map +1 -1
- package/lib/schemas/ObjectSchema.js +6 -85
- package/lib/schemas/ObjectSchema.js.map +1 -1
- package/lib/schemas/ObjectSchema.mjs +6 -58
- package/lib/schemas/ObjectSchema.mjs.map +1 -1
- package/lib/schemas/StringSchema.js +7 -103
- package/lib/schemas/StringSchema.js.map +1 -1
- package/lib/schemas/StringSchema.mjs +7 -76
- package/lib/schemas/StringSchema.mjs.map +1 -1
- package/package.json +15 -14
- package/lib/__tests__/ArraySchema.test.d.mts +0 -2
- package/lib/__tests__/ArraySchema.test.d.ts +0 -2
- package/lib/__tests__/ArraySchema.test.js +0 -201
- package/lib/__tests__/ArraySchema.test.js.map +0 -1
- package/lib/__tests__/ArraySchema.test.mjs +0 -199
- package/lib/__tests__/ArraySchema.test.mjs.map +0 -1
- package/lib/__tests__/BooleanSchema.test.d.mts +0 -2
- package/lib/__tests__/BooleanSchema.test.d.ts +0 -2
- package/lib/__tests__/BooleanSchema.test.js +0 -219
- package/lib/__tests__/BooleanSchema.test.js.map +0 -1
- package/lib/__tests__/BooleanSchema.test.mjs +0 -217
- package/lib/__tests__/BooleanSchema.test.mjs.map +0 -1
- package/lib/__tests__/CommonSchema.test.d.mts +0 -2
- package/lib/__tests__/CommonSchema.test.d.ts +0 -2
- package/lib/__tests__/CommonSchema.test.js +0 -253
- package/lib/__tests__/CommonSchema.test.js.map +0 -1
- package/lib/__tests__/CommonSchema.test.mjs +0 -251
- package/lib/__tests__/CommonSchema.test.mjs.map +0 -1
- package/lib/__tests__/MixTypes.test.d.mts +0 -2
- package/lib/__tests__/MixTypes.test.d.ts +0 -2
- package/lib/__tests__/MixTypes.test.js +0 -165
- package/lib/__tests__/MixTypes.test.js.map +0 -1
- package/lib/__tests__/MixTypes.test.mjs +0 -163
- package/lib/__tests__/MixTypes.test.mjs.map +0 -1
- package/lib/__tests__/NumberSchema.test.d.mts +0 -2
- package/lib/__tests__/NumberSchema.test.d.ts +0 -2
- package/lib/__tests__/NumberSchema.test.js +0 -253
- package/lib/__tests__/NumberSchema.test.js.map +0 -1
- package/lib/__tests__/NumberSchema.test.mjs +0 -251
- package/lib/__tests__/NumberSchema.test.mjs.map +0 -1
- package/lib/__tests__/ObjectSchema.test.d.mts +0 -2
- package/lib/__tests__/ObjectSchema.test.d.ts +0 -2
- package/lib/__tests__/ObjectSchema.test.js +0 -356
- package/lib/__tests__/ObjectSchema.test.js.map +0 -1
- package/lib/__tests__/ObjectSchema.test.mjs +0 -354
- package/lib/__tests__/ObjectSchema.test.mjs.map +0 -1
- package/lib/__tests__/StringSchema.test.d.mts +0 -2
- package/lib/__tests__/StringSchema.test.d.ts +0 -2
- package/lib/__tests__/StringSchema.test.js +0 -228
- package/lib/__tests__/StringSchema.test.js.map +0 -1
- package/lib/__tests__/StringSchema.test.mjs +0 -226
- package/lib/__tests__/StringSchema.test.mjs.map +0 -1
|
@@ -1,354 +0,0 @@
|
|
|
1
|
-
// jest/setup.ts
|
|
2
|
-
function expectEqualTypes(areEqual) {
|
|
3
|
-
expect(typeof areEqual).toBe("boolean");
|
|
4
|
-
}
|
|
5
|
-
|
|
6
|
-
// src/exceptions.ts
|
|
7
|
-
var ValidationError = class extends Error {
|
|
8
|
-
expected;
|
|
9
|
-
received;
|
|
10
|
-
pathToError;
|
|
11
|
-
message;
|
|
12
|
-
constructor(expected, received, pathToError, message) {
|
|
13
|
-
super();
|
|
14
|
-
this.expected = expected;
|
|
15
|
-
this.received = received;
|
|
16
|
-
this.pathToError = pathToError;
|
|
17
|
-
this.message = message;
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
var BuildSchemaError = class extends Error {
|
|
21
|
-
};
|
|
22
|
-
function throwException(expected, received, pathToError, message) {
|
|
23
|
-
throw new ValidationError(expected, received, pathToError, message);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// src/core.ts
|
|
27
|
-
var ctxSymbol = Symbol("contextSymbol");
|
|
28
|
-
function innerCheck(schema, receivedValue, pathToError) {
|
|
29
|
-
const ctx = schema[ctxSymbol];
|
|
30
|
-
if (receivedValue === void 0) {
|
|
31
|
-
if (!ctx.isOptional) throwException("Required", receivedValue, pathToError, "The required value is missing");
|
|
32
|
-
return receivedValue;
|
|
33
|
-
}
|
|
34
|
-
if (receivedValue === null) {
|
|
35
|
-
if (!ctx.isNullable) throwException("Not null", receivedValue, pathToError, "Value should not be null");
|
|
36
|
-
return receivedValue;
|
|
37
|
-
}
|
|
38
|
-
if (ctx.array) {
|
|
39
|
-
if (!Array.isArray(receivedValue))
|
|
40
|
-
throwException("Array", receivedValue, pathToError, "Expected an array but received a different type");
|
|
41
|
-
const schema2 = ctx.array;
|
|
42
|
-
receivedValue.forEach((elem, i) => {
|
|
43
|
-
innerCheck(schema2, elem, `${pathToError}[${i}]`);
|
|
44
|
-
});
|
|
45
|
-
return receivedValue;
|
|
46
|
-
}
|
|
47
|
-
const typeOfVal = typeof receivedValue;
|
|
48
|
-
if (ctx.object) {
|
|
49
|
-
if (typeOfVal !== "object")
|
|
50
|
-
throwException("Object", receivedValue, pathToError, "Expected an object but received a different type");
|
|
51
|
-
if (Array.isArray(receivedValue))
|
|
52
|
-
throwException(
|
|
53
|
-
"Object",
|
|
54
|
-
receivedValue,
|
|
55
|
-
pathToError,
|
|
56
|
-
"Expected an object but received an array. Invalid type of data"
|
|
57
|
-
);
|
|
58
|
-
const shapeSchema = ctx.object;
|
|
59
|
-
for (const keyPerReceivedValue of Object.keys(receivedValue)) {
|
|
60
|
-
if (shapeSchema[keyPerReceivedValue] === void 0)
|
|
61
|
-
throwException("Not allowed", keyPerReceivedValue, pathToError, "This key is not allowed in the object");
|
|
62
|
-
}
|
|
63
|
-
for (const [keyOfSchema, valueOfSchema] of Object.entries(shapeSchema)) {
|
|
64
|
-
const receivedObjectValuePropery = receivedValue[keyOfSchema];
|
|
65
|
-
if (receivedObjectValuePropery === void 0) {
|
|
66
|
-
if (!valueOfSchema[ctxSymbol].isOptional)
|
|
67
|
-
throwException(
|
|
68
|
-
"Required",
|
|
69
|
-
receivedObjectValuePropery,
|
|
70
|
-
pathToError,
|
|
71
|
-
"Missing required property in the object"
|
|
72
|
-
);
|
|
73
|
-
}
|
|
74
|
-
innerCheck(valueOfSchema, receivedObjectValuePropery, `${pathToError}.${keyOfSchema}`);
|
|
75
|
-
}
|
|
76
|
-
return receivedValue;
|
|
77
|
-
}
|
|
78
|
-
if (ctx.type.length) {
|
|
79
|
-
if (!ctx.type.includes(typeOfVal)) throwException(ctx.type, typeOfVal, pathToError, "Invalid type of data");
|
|
80
|
-
}
|
|
81
|
-
ctx.requiredValidations.forEach((requiredValidation) => {
|
|
82
|
-
requiredValidation(receivedValue, pathToError);
|
|
83
|
-
});
|
|
84
|
-
return receivedValue;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// src/parseSchema.ts
|
|
88
|
-
function parseSchema(schema, receivedValue) {
|
|
89
|
-
try {
|
|
90
|
-
return innerCheck(schema, receivedValue, "");
|
|
91
|
-
} catch (e) {
|
|
92
|
-
if (e instanceof ValidationError) throw e;
|
|
93
|
-
throw new Error("Something unexpected happened");
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// src/asserts/common/equalTo.ts
|
|
98
|
-
var equalTo = (expected) => (received, pathToError) => {
|
|
99
|
-
if (expected !== received)
|
|
100
|
-
throwException(expected, received, pathToError, "The received value is not equal to expected");
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
// src/schemas/CommonSchema.ts
|
|
104
|
-
var CommonSchema = class {
|
|
105
|
-
[ctxSymbol];
|
|
106
|
-
constructor(ctx) {
|
|
107
|
-
this[ctxSymbol] = ctx;
|
|
108
|
-
}
|
|
109
|
-
/**
|
|
110
|
-
* @param validators - One or more custom validation functions.
|
|
111
|
-
* @returns {this} The schema instance with the added custom validation.
|
|
112
|
-
*/
|
|
113
|
-
custom(...validators) {
|
|
114
|
-
this[ctxSymbol].requiredValidations.push(...validators);
|
|
115
|
-
return this;
|
|
116
|
-
}
|
|
117
|
-
/**
|
|
118
|
-
* Marks the schema as nullable, allowing the value to be `null`.
|
|
119
|
-
*
|
|
120
|
-
* @returns {WithNull<this>} The schema instance marked as nullable.
|
|
121
|
-
*/
|
|
122
|
-
nullable() {
|
|
123
|
-
this[ctxSymbol].isNullable = true;
|
|
124
|
-
return this;
|
|
125
|
-
}
|
|
126
|
-
/**
|
|
127
|
-
* Marks the schema as optional, allowing the value to be `undefined`.
|
|
128
|
-
*
|
|
129
|
-
* @returns {WithUndefined<this>}} The schema instance marked as optional.
|
|
130
|
-
*/
|
|
131
|
-
optional() {
|
|
132
|
-
this[ctxSymbol].isOptional = true;
|
|
133
|
-
return this;
|
|
134
|
-
}
|
|
135
|
-
};
|
|
136
|
-
|
|
137
|
-
// src/schemas/NumberSchema.ts
|
|
138
|
-
var NumberSchema = class extends CommonSchema {
|
|
139
|
-
_number = 1;
|
|
140
|
-
/**
|
|
141
|
-
* Restricts the schema to exactly match the specified value and infers the literal value as the TypeScript type.
|
|
142
|
-
*
|
|
143
|
-
* @param expectedValue - The value that the schema must exactly match.
|
|
144
|
-
* @returns - The schema instance restricted to the specified value, with the literal value inferred as the TypeScript type
|
|
145
|
-
*
|
|
146
|
-
* @example - number().equalTo(42); // Infers the type 42
|
|
147
|
-
*/
|
|
148
|
-
equalTo(expectedValue) {
|
|
149
|
-
return this.custom(equalTo(expectedValue));
|
|
150
|
-
}
|
|
151
|
-
};
|
|
152
|
-
|
|
153
|
-
// src/asserts/number/index.ts
|
|
154
|
-
function number() {
|
|
155
|
-
return new NumberSchema({ type: ["number"], requiredValidations: [] });
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// src/schemas/StringSchema.ts
|
|
159
|
-
var StringSchema = class extends CommonSchema {
|
|
160
|
-
_string = 1;
|
|
161
|
-
/**
|
|
162
|
-
* Restricts the schema to exactly match the specified value and infers the literal value as the TypeScript type.
|
|
163
|
-
*
|
|
164
|
-
* @param expectedValue - The value that the schema must exactly match.
|
|
165
|
-
* @returns - The schema instance restricted to the specified value, with the literal value inferred as the TypeScript type
|
|
166
|
-
*
|
|
167
|
-
* @example - string().equalTo('hello'); // Infers the type 'hello'
|
|
168
|
-
*/
|
|
169
|
-
equalTo(expectedValue) {
|
|
170
|
-
return this.custom(equalTo(expectedValue));
|
|
171
|
-
}
|
|
172
|
-
};
|
|
173
|
-
|
|
174
|
-
// src/asserts/string/index.ts
|
|
175
|
-
function string() {
|
|
176
|
-
return new StringSchema({ type: ["string"], requiredValidations: [] });
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
// src/schemas/BooleanSchema.ts
|
|
180
|
-
var isBoolean = (expected) => (received, pathToError) => {
|
|
181
|
-
if (received !== expected) throwException(expected, received, pathToError, `The received value is not ${expected}`);
|
|
182
|
-
};
|
|
183
|
-
var BooleanSchema = class extends CommonSchema {
|
|
184
|
-
_boolean = 1;
|
|
185
|
-
/**
|
|
186
|
-
* Restricts the schema to exactly match the boolean value true and infers the true value as the TypeScript type.
|
|
187
|
-
*
|
|
188
|
-
* @returns - The schema instance restricted to the value true, with the true value inferred as the TypeScript type
|
|
189
|
-
*
|
|
190
|
-
* @example - boolean().onlyTrue(); // Infers the type true
|
|
191
|
-
*/
|
|
192
|
-
onlyTrue() {
|
|
193
|
-
return this.custom(isBoolean(true));
|
|
194
|
-
}
|
|
195
|
-
/**
|
|
196
|
-
* Restricts the schema to exactly match the boolean value false and infers the false value as the TypeScript type.
|
|
197
|
-
*
|
|
198
|
-
* @returns - The schema instance restricted to the value false, with the false value inferred as the TypeScript type
|
|
199
|
-
*
|
|
200
|
-
* @example - boolean().onlyFalse(); // Infers the type false
|
|
201
|
-
*/
|
|
202
|
-
onlyFalse() {
|
|
203
|
-
return this.custom(isBoolean(false));
|
|
204
|
-
}
|
|
205
|
-
};
|
|
206
|
-
|
|
207
|
-
// src/asserts/boolean/index.ts
|
|
208
|
-
function boolean() {
|
|
209
|
-
return new BooleanSchema({ type: ["boolean"], requiredValidations: [] });
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
// src/schemas/ArraySchema.ts
|
|
213
|
-
var ArraySchema = class extends CommonSchema {
|
|
214
|
-
_array = 1;
|
|
215
|
-
constructor(ctx, arraySchema) {
|
|
216
|
-
super(ctx);
|
|
217
|
-
this.validateArrayEntry(arraySchema);
|
|
218
|
-
this[ctxSymbol].array = arraySchema;
|
|
219
|
-
}
|
|
220
|
-
validateArrayEntry(arraySchema) {
|
|
221
|
-
if (!arraySchema) throw new BuildSchemaError("Missing schema in array method");
|
|
222
|
-
if (!(arraySchema instanceof CommonSchema)) throw new BuildSchemaError("Invalid schema in array method");
|
|
223
|
-
}
|
|
224
|
-
};
|
|
225
|
-
|
|
226
|
-
// src/asserts/array/index.ts
|
|
227
|
-
function array(arraySchema) {
|
|
228
|
-
return new ArraySchema({ type: [], requiredValidations: [] }, arraySchema);
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
// src/schemas/ObjectSchema.ts
|
|
232
|
-
var ObjectSchema = class extends CommonSchema {
|
|
233
|
-
_object = 1;
|
|
234
|
-
constructor(ctx, shapeSchema) {
|
|
235
|
-
super(ctx);
|
|
236
|
-
this.validateObjectEntry(shapeSchema);
|
|
237
|
-
this[ctxSymbol].object = shapeSchema;
|
|
238
|
-
}
|
|
239
|
-
validateObjectEntry(shapeSchema) {
|
|
240
|
-
if (!shapeSchema) throw new BuildSchemaError("Missing schema in object method");
|
|
241
|
-
if (shapeSchema instanceof CommonSchema) throw new BuildSchemaError("Invalid schema in object");
|
|
242
|
-
for (const [key, value] of Object.entries(shapeSchema)) {
|
|
243
|
-
if (!(value instanceof CommonSchema))
|
|
244
|
-
throw new BuildSchemaError(`Invalid schema in object method for property '${key}'`);
|
|
245
|
-
}
|
|
246
|
-
}
|
|
247
|
-
};
|
|
248
|
-
|
|
249
|
-
// src/asserts/object/index.ts
|
|
250
|
-
function object(shapeSchema) {
|
|
251
|
-
return new ObjectSchema({ type: [], requiredValidations: [] }, shapeSchema);
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
// src/asserts/string/minLength.ts
|
|
255
|
-
var minLength = (expected) => (received, pathToError) => {
|
|
256
|
-
if (received.length < expected)
|
|
257
|
-
throwException(expected, received, pathToError, "The received value length is less than expected");
|
|
258
|
-
};
|
|
259
|
-
|
|
260
|
-
// src/asserts/string/email.ts
|
|
261
|
-
var emailRegExp = /^[^@]+@[^@]+\.[^@]+$/;
|
|
262
|
-
var email = () => (received, pathToError) => {
|
|
263
|
-
if (!emailRegExp.test(received))
|
|
264
|
-
throwException(emailRegExp, received, pathToError, "The received value does not match the required email pattern");
|
|
265
|
-
};
|
|
266
|
-
|
|
267
|
-
// src/__tests__/ObjectSchema.test.ts
|
|
268
|
-
describe("ObjectSchema", () => {
|
|
269
|
-
it("should be an object", () => {
|
|
270
|
-
const objectWithNumbersSchema = object({ foo: number() });
|
|
271
|
-
expectEqualTypes(true);
|
|
272
|
-
const myObject = { foo: 5 };
|
|
273
|
-
expect(parseSchema(objectWithNumbersSchema, myObject)).toBe(myObject);
|
|
274
|
-
expect(() => parseSchema(objectWithNumbersSchema, "not an object")).toThrow(
|
|
275
|
-
"Expected an object but received a different type"
|
|
276
|
-
);
|
|
277
|
-
expect(() => parseSchema(objectWithNumbersSchema, "not an object")).toThrow(ValidationError);
|
|
278
|
-
});
|
|
279
|
-
it("should not build with missing parameters", () => {
|
|
280
|
-
const invalidObjectSchemaFunction = () => object();
|
|
281
|
-
expectEqualTypes(true);
|
|
282
|
-
expect(invalidObjectSchemaFunction).toThrow("Missing schema in object method");
|
|
283
|
-
expect(invalidObjectSchemaFunction).toThrow(BuildSchemaError);
|
|
284
|
-
});
|
|
285
|
-
it("should not build with invalid primitive parameters", () => {
|
|
286
|
-
const invalidObjectSchemaFunction = () => object("not an object with bguard schema");
|
|
287
|
-
expectEqualTypes(true);
|
|
288
|
-
expect(invalidObjectSchemaFunction).toThrow("Invalid schema in object method");
|
|
289
|
-
expect(invalidObjectSchemaFunction).toThrow(BuildSchemaError);
|
|
290
|
-
});
|
|
291
|
-
it("should not build with an array parameter", () => {
|
|
292
|
-
const invalidObjectSchemaFunction = () => object(array(string()));
|
|
293
|
-
expectEqualTypes(true);
|
|
294
|
-
expect(invalidObjectSchemaFunction).toThrow("Invalid schema in object");
|
|
295
|
-
expect(invalidObjectSchemaFunction).toThrow(BuildSchemaError);
|
|
296
|
-
});
|
|
297
|
-
it("should not run with an array parameter", () => {
|
|
298
|
-
const objectSchema = object({ foo: string() });
|
|
299
|
-
expectEqualTypes(true);
|
|
300
|
-
expect(() => parseSchema(objectSchema, ["foo", "bar"])).toThrow(
|
|
301
|
-
"Expected an object but received an array. Invalid type of data"
|
|
302
|
-
);
|
|
303
|
-
});
|
|
304
|
-
it("should not run with an invalid keys", () => {
|
|
305
|
-
const objectSchema = object({ foo: string() });
|
|
306
|
-
expectEqualTypes(true);
|
|
307
|
-
expect(() => parseSchema(objectSchema, { foo: "valid key foo", bar: "invalid key bar" })).toThrow(
|
|
308
|
-
"This key is not allowed in the object"
|
|
309
|
-
);
|
|
310
|
-
});
|
|
311
|
-
it("should not run with missing required property", () => {
|
|
312
|
-
const objectSchema = object({ foo: string(), bar: string() });
|
|
313
|
-
expectEqualTypes(true);
|
|
314
|
-
expect(() => parseSchema(objectSchema, { foo: "valid key foo" })).toThrow(
|
|
315
|
-
"Missing required property in the object"
|
|
316
|
-
);
|
|
317
|
-
});
|
|
318
|
-
it("should validate complex object schema", () => {
|
|
319
|
-
const userSchema = object({
|
|
320
|
-
email: string().custom(email()),
|
|
321
|
-
userName: string().optional(),
|
|
322
|
-
verified: boolean().onlyTrue().optional(),
|
|
323
|
-
phone: number().nullable().optional(),
|
|
324
|
-
address: array(string().custom(minLength(3)))
|
|
325
|
-
});
|
|
326
|
-
expectEqualTypes(true);
|
|
327
|
-
const validUser = {
|
|
328
|
-
email: "foo@foo.com",
|
|
329
|
-
address: ["my adress"],
|
|
330
|
-
phone: null,
|
|
331
|
-
verified: true
|
|
332
|
-
};
|
|
333
|
-
expect(parseSchema(userSchema, validUser)).toBe(validUser);
|
|
334
|
-
const userWithInvalidAddress = {
|
|
335
|
-
email: "foo@foo.com",
|
|
336
|
-
address: ["my"],
|
|
337
|
-
phone: null,
|
|
338
|
-
verified: true
|
|
339
|
-
};
|
|
340
|
-
expect(() => parseSchema(userSchema, userWithInvalidAddress)).toThrow(
|
|
341
|
-
"The received value length is less than expected"
|
|
342
|
-
);
|
|
343
|
-
const userWithInvalidEmail = {
|
|
344
|
-
email: "foofoo.com",
|
|
345
|
-
address: ["my"],
|
|
346
|
-
phone: null,
|
|
347
|
-
verified: true
|
|
348
|
-
};
|
|
349
|
-
expect(() => parseSchema(userSchema, userWithInvalidEmail)).toThrow(
|
|
350
|
-
"The received value does not match the required email pattern"
|
|
351
|
-
);
|
|
352
|
-
});
|
|
353
|
-
});
|
|
354
|
-
//# sourceMappingURL=ObjectSchema.test.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../jest/setup.ts","../../src/exceptions.ts","../../src/core.ts","../../src/parseSchema.ts","../../src/asserts/common/equalTo.ts","../../src/schemas/CommonSchema.ts","../../src/schemas/NumberSchema.ts","../../src/asserts/number/index.ts","../../src/schemas/StringSchema.ts","../../src/asserts/string/index.ts","../../src/schemas/BooleanSchema.ts","../../src/asserts/boolean/index.ts","../../src/schemas/ArraySchema.ts","../../src/asserts/array/index.ts","../../src/schemas/ObjectSchema.ts","../../src/asserts/object/index.ts","../../src/asserts/string/minLength.ts","../../src/asserts/string/email.ts","../../src/__tests__/ObjectSchema.test.ts"],"sourcesContent":["export type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? true : false;\n\nexport function expectEqualTypes<X, Y>(areEqual: Equal<X, Y>): void {\n expect(typeof areEqual).toBe('boolean');\n}\n","export class ValidationError extends Error {\n expected: unknown;\n received: unknown;\n pathToError: string;\n message: string;\n constructor(expected: unknown, received: unknown, pathToError: string, message: string) {\n super();\n this.expected = expected;\n this.received = received;\n this.pathToError = pathToError;\n this.message = message;\n }\n}\n\nexport class BuildSchemaError extends Error {}\n\nexport function throwException(expected: unknown, received: unknown, pathToError: string, message: string): never {\n throw new ValidationError(expected, received, pathToError, message);\n}\n","export const ctxSymbol = Symbol('contextSymbol');\n\nimport { throwException } from './exceptions';\nimport type { CommonSchema } from './schemas/CommonSchema';\n\nexport function innerCheck(schema: CommonSchema, receivedValue: unknown, pathToError: string) {\n const ctx = schema[ctxSymbol];\n if (receivedValue === undefined) {\n if (!ctx.isOptional) throwException('Required', receivedValue, pathToError, 'The required value is missing');\n return receivedValue;\n }\n\n if (receivedValue === null) {\n if (!ctx.isNullable) throwException('Not null', receivedValue, pathToError, 'Value should not be null');\n return receivedValue;\n }\n\n if (ctx.array) {\n if (!Array.isArray(receivedValue))\n throwException('Array', receivedValue, pathToError, 'Expected an array but received a different type');\n const schema = ctx.array;\n\n receivedValue.forEach((elem, i) => {\n innerCheck(schema, elem, `${pathToError}[${i}]`);\n });\n\n return receivedValue;\n }\n\n const typeOfVal = typeof receivedValue;\n\n if (ctx.object) {\n if (typeOfVal !== 'object')\n throwException('Object', receivedValue, pathToError, 'Expected an object but received a different type');\n if (Array.isArray(receivedValue))\n throwException(\n 'Object',\n receivedValue,\n pathToError,\n 'Expected an object but received an array. Invalid type of data',\n );\n const shapeSchema = ctx.object;\n for (const keyPerReceivedValue of Object.keys(receivedValue)) {\n if (shapeSchema[keyPerReceivedValue] === undefined)\n throwException('Not allowed', keyPerReceivedValue, pathToError, 'This key is not allowed in the object');\n }\n\n for (const [keyOfSchema, valueOfSchema] of Object.entries(shapeSchema)) {\n const receivedObjectValuePropery = (receivedValue as Record<string, unknown>)[keyOfSchema];\n if (receivedObjectValuePropery === undefined) {\n if (!valueOfSchema[ctxSymbol].isOptional)\n throwException(\n 'Required',\n receivedObjectValuePropery,\n pathToError,\n 'Missing required property in the object',\n );\n }\n innerCheck(valueOfSchema, receivedObjectValuePropery, `${pathToError}.${keyOfSchema}`);\n }\n\n return receivedValue;\n }\n\n if (ctx.type.length) {\n if (!ctx.type.includes(typeOfVal)) throwException(ctx.type, typeOfVal, pathToError, 'Invalid type of data');\n }\n\n ctx.requiredValidations.forEach((requiredValidation) => {\n requiredValidation(receivedValue, pathToError);\n });\n\n return receivedValue;\n}\n","import { InferType } from './InferType';\nimport { innerCheck } from './core';\nimport { ValidationError } from './exceptions';\nimport { CommonSchema } from './schemas/CommonSchema';\n\n/**\n * Parses and validates a value against the provided schema, returning a type-safe result.\n *\n * This function will throw a `ValidationError` if the value does not conform to the schema.\n * The inferred TypeScript type of the returned value will match the structure defined by the schema.\n *\n * @template T\n * @param {T} schema - The schema to validate the received value against. This schema dictates the expected structure and type of the value.\n * @param {unknown} receivedValue - The value to be validated and parsed according to the schema.\n * @returns {InferType<T>} The validated value, with its TypeScript type inferred from the schema.\n *\n * @throws {ValidationError} If the received value does not match the schema, a `ValidationError` will be thrown.\n * @throws {Error} If an unexpected error occurs during validation, an error will be thrown with a generic message.\n *\n * @example\n * const schema = object({\n * name: string(),\n * age: number(),\n * });\n *\n * const result = parseSchema(schema, { name: 'Alice', age: 30 });\n * // result will be inferred as { name: string; age: number }\n *\n * parseSchema(schema, { name: 'Alice', age: '30' });\n * // Throws ValidationError because 'age' should be a number, not a string.\n */\nexport function parseSchema<T extends CommonSchema>(schema: T, receivedValue: unknown): InferType<T> {\n try {\n return innerCheck(schema, receivedValue, '') as InferType<T>;\n } catch (e) {\n if (e instanceof ValidationError) throw e;\n /* istanbul ignore next */\n throw new Error('Something unexpected happened');\n }\n}\n","import { throwException } from '../../exceptions';\nimport { RequiredValidation } from '../../schemas/CommonSchema';\n\n/**\n * Creates a custom assertion that checks if a value is equal to the expected value.\n *\n * This assertion can be used within a `.custom` method to enforce that a value strictly matches the expected value.\n * It will throw a `ValidationError` if the values are not equal.\n *\n * @param {unknown} expected - The value that the received value is expected to match.\n * @returns {RequiredValidation} A function that takes the received value and the path to the error,\n * and throws a `ValidationError` if the received value does not equal the expected value.\n *\n * @throws {ValidationError} If the received value does not match the expected value.\n *\n * @example\n * import { number, equalTo } from 'bguard';\n *\n * // Define a schema with a custom assertion\n * const schema = number().custom(equalTo(5));\n *\n * // This will pass\n * parseSchema(schema, 5);\n *\n * // This will throw a ValidationError\n * parseSchema(schema, 3);\n */\nexport const equalTo =\n (expected: unknown): RequiredValidation =>\n (received: number, pathToError: string) => {\n if (expected !== received)\n throwException(expected, received, pathToError, 'The received value is not equal to expected');\n };\n","import { ctxSymbol } from '../core';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type RequiredValidation = (received: any, pathToError: string) => void;\nexport type ObjectShapeSchemaType = Record<string, CommonSchema>;\n\nexport type PrimitiveType = 'number' | 'string' | 'boolean' | 'undefined' | 'object' | 'function' | 'symbol' | 'bigint';\nexport interface ValidatorContext {\n type: PrimitiveType[];\n isNullable?: boolean;\n isOptional?: boolean;\n requiredValidations: RequiredValidation[];\n array?: CommonSchema;\n object?: ObjectShapeSchemaType;\n}\n\nexport class CommonSchema {\n [ctxSymbol]: ValidatorContext;\n constructor(ctx: ValidatorContext) {\n this[ctxSymbol] = ctx;\n }\n\n /**\n * @param validators - One or more custom validation functions.\n * @returns {this} The schema instance with the added custom validation.\n */\n custom(...validators: RequiredValidation[]): this {\n this[ctxSymbol].requiredValidations.push(...validators);\n return this;\n }\n\n /**\n * Marks the schema as nullable, allowing the value to be `null`.\n *\n * @returns {WithNull<this>} The schema instance marked as nullable.\n */\n nullable(): WithNull<this> {\n this[ctxSymbol].isNullable = true;\n return this as WithNull<this>;\n }\n\n /**\n * Marks the schema as optional, allowing the value to be `undefined`.\n *\n * @returns {WithUndefined<this>}} The schema instance marked as optional.\n */\n optional(): WithUndefined<this> {\n this[ctxSymbol].isOptional = true;\n return this as WithUndefined<this>;\n }\n}\n\nexport type WithNull<T extends CommonSchema> = T & { validation_null: true };\nexport type WithUndefined<T extends CommonSchema> = T & { validation_undefined: true };\n\ntype TypeMapping = {\n number: number;\n string: string;\n boolean: boolean;\n undefined: undefined;\n object: object;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n function: Function;\n symbol: symbol;\n bigint: bigint;\n};\n\nexport type WithMix<Y = unknown> = CommonSchema & { validation_mix: Y };\nexport type ExtractFromMix<T> = T extends WithMix<infer X> ? X : never;\n\nexport type MapMixTypes<T extends PrimitiveType[]> = T extends (infer U)[]\n ? U extends keyof TypeMapping\n ? TypeMapping[U]\n : never\n : never;\n","import { equalTo } from '../asserts/common/equalTo';\n\nimport { CommonSchema } from './CommonSchema';\n\nexport class NumberSchema extends CommonSchema {\n _number = 1;\n\n /**\n * Restricts the schema to exactly match the specified value and infers the literal value as the TypeScript type.\n *\n * @param expectedValue - The value that the schema must exactly match.\n * @returns - The schema instance restricted to the specified value, with the literal value inferred as the TypeScript type\n *\n * @example - number().equalTo(42); // Infers the type 42\n */\n equalTo<Y extends number>(expectedValue: Y): WithNumber<this, Y> {\n return this.custom(equalTo(expectedValue)) as WithNumber<this, Y>;\n }\n}\n\nexport type WithNumber<T extends NumberSchema, Y = number> = T & { validation_number: Y };\nexport type ExtractFromNumber<T> = T extends WithNumber<NumberSchema, infer Y> ? Y : never;\n","import { NumberSchema } from '../../schemas/NumberSchema';\n\n/**\n * Creates a new schema for validating number values.\n *\n * @returns {NumberSchema} A new instance of `NumberSchema` for validating numbers.\n *\n * @example\n * const schema = number();\n * parseSchema(schema, 42); // Validates successfully\n * parseSchema(schema, '42'); // Throws a validation error\n */\nexport function number(): NumberSchema {\n return new NumberSchema({ type: ['number'], requiredValidations: [] });\n}\n","import { equalTo } from '../asserts/common/equalTo';\nimport { CommonSchema } from './CommonSchema';\n\nexport class StringSchema extends CommonSchema {\n _string = 1;\n\n /**\n * Restricts the schema to exactly match the specified value and infers the literal value as the TypeScript type.\n *\n * @param expectedValue - The value that the schema must exactly match.\n * @returns - The schema instance restricted to the specified value, with the literal value inferred as the TypeScript type\n *\n * @example - string().equalTo('hello'); // Infers the type 'hello'\n */\n equalTo<Y extends string>(expectedValue: Y): WithString<this, Y> {\n return this.custom(equalTo(expectedValue)) as WithString<this, Y>;\n }\n}\n\nexport type WithString<T extends StringSchema, Y = string> = T & { validation_string: Y };\nexport type ExtractFromString<T> = T extends WithString<StringSchema, infer Y> ? Y : never;\n","import { StringSchema } from '../../schemas/StringSchema';\n\n/**\n * Creates a new schema for validating string values.\n *\n * @returns {StringSchema} A new instance of `StringSchema` for validating strings.\n *\n * @example\n * const schema = string();\n * parseSchema(schema, 'hello'); // Validates successfully\n * parseSchema(schema, 123); // Throws a validation error\n */\nexport function string(): StringSchema {\n return new StringSchema({ type: ['string'], requiredValidations: [] });\n}\n","import { CommonSchema } from './CommonSchema';\nimport { throwException } from '../exceptions';\n\nconst isBoolean = (expected: boolean) => (received: boolean, pathToError: string) => {\n if (received !== expected) throwException(expected, received, pathToError, `The received value is not ${expected}`);\n};\n\nexport class BooleanSchema extends CommonSchema {\n _boolean = 1;\n\n /**\n * Restricts the schema to exactly match the boolean value true and infers the true value as the TypeScript type.\n *\n * @returns - The schema instance restricted to the value true, with the true value inferred as the TypeScript type\n *\n * @example - boolean().onlyTrue(); // Infers the type true\n */\n onlyTrue(): WithBoolean<this, true> {\n return this.custom(isBoolean(true)) as WithBoolean<this, true>;\n }\n\n /**\n * Restricts the schema to exactly match the boolean value false and infers the false value as the TypeScript type.\n *\n * @returns - The schema instance restricted to the value false, with the false value inferred as the TypeScript type\n *\n * @example - boolean().onlyFalse(); // Infers the type false\n */\n onlyFalse(): WithBoolean<this, false> {\n return this.custom(isBoolean(false)) as WithBoolean<this, false>;\n }\n}\n\nexport type WithBoolean<T extends BooleanSchema, Y = boolean> = T & { validation_boolean: Y };\nexport type ExtractFromBoolean<T> = T extends WithBoolean<BooleanSchema, infer Y> ? Y : never;\n","import { BooleanSchema } from '../../schemas/BooleanSchema';\n\n/**\n * Creates a new schema for validating boolean values.\n *\n * @returns {BooleanSchema} A new instance of `BooleanSchema` for validating booleans.\n *\n * @example\n * const schema = boolean();\n * parseSchema(schema, true); // Validates successfully\n * parseSchema(schema, 'true'); // Throws a validation error\n */\nexport function boolean(): BooleanSchema {\n return new BooleanSchema({ type: ['boolean'], requiredValidations: [] });\n}\n","import { ctxSymbol } from '../core';\nimport { BuildSchemaError } from '../exceptions';\nimport { CommonSchema, ValidatorContext } from './CommonSchema';\n\nexport class ArraySchema extends CommonSchema {\n _array = 1;\n constructor(ctx: ValidatorContext, arraySchema: CommonSchema) {\n super(ctx);\n this.validateArrayEntry(arraySchema);\n this[ctxSymbol].array = arraySchema;\n }\n\n private validateArrayEntry(arraySchema: CommonSchema) {\n if (!arraySchema) throw new BuildSchemaError('Missing schema in array method');\n if (!(arraySchema instanceof CommonSchema)) throw new BuildSchemaError('Invalid schema in array method');\n }\n}\n\nexport type WithArray<Y extends CommonSchema> = ArraySchema & { validation_array: Y };\nexport type ExtractFromArray<T> = T extends WithArray<infer X> ? X : never;\n","import { ArraySchema, WithArray } from '../../schemas/ArraySchema';\nimport { CommonSchema } from '../../schemas/CommonSchema';\n\n/**\n * Creates a new schema for validating arrays where each element must match the specified schema.\n *\n * @template T\n * @param {T} arraySchema - The schema that each element of the array must match.\n * @returns {WithArray<T>} A new instance of `ArraySchema` for validating arrays of elements that match the specified schema.\n *\n * @example\n * const schema = array(string());\n * parseSchema(schema, ['hello', 'world']); // Validates successfully\n * parseSchema(schema, ['hello', 123]); // Throws a validation error\n */\nexport function array<T extends CommonSchema>(arraySchema: T): WithArray<T> {\n return new ArraySchema({ type: [], requiredValidations: [] }, arraySchema) as WithArray<T>;\n}\n","import { ctxSymbol } from '../core';\nimport { BuildSchemaError } from '../exceptions';\nimport { CommonSchema, ObjectShapeSchemaType, ValidatorContext } from './CommonSchema';\n\nexport class ObjectSchema extends CommonSchema {\n _object = 1;\n constructor(ctx: ValidatorContext, shapeSchema: ObjectShapeSchemaType) {\n super(ctx);\n this.validateObjectEntry(shapeSchema);\n this[ctxSymbol].object = shapeSchema;\n }\n\n private validateObjectEntry(shapeSchema: ObjectShapeSchemaType) {\n if (!shapeSchema) throw new BuildSchemaError('Missing schema in object method');\n if (shapeSchema instanceof CommonSchema) throw new BuildSchemaError('Invalid schema in object');\n for (const [key, value] of Object.entries(shapeSchema)) {\n if (!(value instanceof CommonSchema))\n throw new BuildSchemaError(`Invalid schema in object method for property '${key}'`);\n }\n }\n}\n\nexport type WithObject<Y extends ObjectShapeSchemaType> = ObjectSchema & { validation_object: Y };\n","import { ObjectShapeSchemaType } from '../../schemas/CommonSchema';\nimport { ObjectSchema, WithObject } from '../../schemas/ObjectSchema';\n\n/**\n * Creates a new schema for validating objects where each property must match the specified schema.\n *\n * @template T\n * @param {T} shapeSchema - The schema that each property of the object must match.\n * @returns {WithObject<T>} A new instance of `ObjectSchema` for validating objects with properties matching the specified schema.\n *\n * @example\n * const schema = object({\n * name: string(),\n * age: number()\n * });\n * parseSchema(schema, { name: 'John', age: 30 }); // Validates successfully\n * parseSchema(schema, { name: 'John', age: '30' }); // Throws a validation error\n */\nexport function object<T extends ObjectShapeSchemaType>(shapeSchema: T): WithObject<T> {\n return new ObjectSchema({ type: [], requiredValidations: [] }, shapeSchema) as WithObject<T>;\n}\n","import { throwException } from '../../exceptions';\nimport type { RequiredValidation } from '../../schemas/CommonSchema';\n\n/**\n * Asserts that the length of a string value is not less than a specified minimum length.\n *\n * @param {number} expected - The minimum required length for the string.\n * @returns {RequiredValidation} - A validation function that takes a received string and a path to the error message. Throws an error if the length of the received value is less than the expected length.\n *\n * @example\n * const schema = string().custom(minLength(5));\n * parseSchema(schema, 'short'); // Throws an error: 'The received value length is less than expected'\n * parseSchema(schema, 'adequate'); // Valid\n */\nexport const minLength =\n (expected: number): RequiredValidation =>\n (received: string, pathToError: string) => {\n if (received.length < expected)\n throwException(expected, received, pathToError, 'The received value length is less than expected');\n };\n","import { throwException } from '../../exceptions';\nimport type { RequiredValidation } from '../../schemas/CommonSchema';\n\nconst emailRegExp = /^[^@]+@[^@]+\\.[^@]+$/;\n\n/**\n * Asserts that a string value matches the email pattern.\n * The pattern is defined as /^[^@]+@[^@]+\\.[^@]+$/, which checks for a basic email format.\n *\n * @returns {RequiredValidation} - A validation function that takes a received string and a path to the error message. Throws an error if the received value does not match the email pattern.\n *\n * @example\n * const schema = string().custom(email());\n * parseSchema(schema, 'example@example.com'); // Valid\n * parseSchema(schema, 'invalid-email'); // Throws an error: 'The received value does not match the required email pattern'\n */\nexport const email = (): RequiredValidation => (received: string, pathToError: string) => {\n if (!emailRegExp.test(received))\n throwException(emailRegExp, received, pathToError, 'The received value does not match the required email pattern');\n};\n","import { expectEqualTypes } from '../../jest/setup';\nimport { InferType, object, boolean, string, number, array, parseSchema, BuildSchemaError, ValidationError } from '../';\nimport { minLength } from '../asserts/string/minLength';\nimport { email } from '../asserts/string/email';\n\ndescribe('ObjectSchema', () => {\n type UnkownObject = {\n [x: string]: unknown;\n };\n it('should be an object', () => {\n const objectWithNumbersSchema = object({ foo: number() });\n type MyObjectWithNumbers = {\n foo: number;\n };\n expectEqualTypes<MyObjectWithNumbers, InferType<typeof objectWithNumbersSchema>>(true);\n const myObject = { foo: 5 };\n expect(parseSchema(objectWithNumbersSchema, myObject)).toBe(myObject);\n expect(() => parseSchema(objectWithNumbersSchema, 'not an object')).toThrow(\n 'Expected an object but received a different type',\n );\n expect(() => parseSchema(objectWithNumbersSchema, 'not an object')).toThrow(ValidationError);\n });\n\n it('should not build with missing parameters', () => {\n //@ts-expect-error testing invalid schema in runtime\n const invalidObjectSchemaFunction = () => object();\n\n expectEqualTypes<UnkownObject, InferType<ReturnType<typeof invalidObjectSchemaFunction>>>(true);\n expect(invalidObjectSchemaFunction).toThrow('Missing schema in object method');\n expect(invalidObjectSchemaFunction).toThrow(BuildSchemaError);\n });\n\n it('should not build with invalid primitive parameters', () => {\n //@ts-expect-error testing invalid schema in runtime\n const invalidObjectSchemaFunction = () => object('not an object with bguard schema');\n expectEqualTypes<UnkownObject, InferType<ReturnType<typeof invalidObjectSchemaFunction>>>(true);\n expect(invalidObjectSchemaFunction).toThrow('Invalid schema in object method');\n expect(invalidObjectSchemaFunction).toThrow(BuildSchemaError);\n });\n\n it('should not build with an array parameter', () => {\n //@ts-expect-error testing invalid schema in runtime\n const invalidObjectSchemaFunction = () => object(array(string()));\n expectEqualTypes<UnkownObject, InferType<ReturnType<typeof invalidObjectSchemaFunction>>>(true);\n expect(invalidObjectSchemaFunction).toThrow('Invalid schema in object');\n expect(invalidObjectSchemaFunction).toThrow(BuildSchemaError);\n });\n\n it('should not run with an array parameter', () => {\n const objectSchema = object({ foo: string() });\n expectEqualTypes<\n {\n foo: string;\n },\n InferType<typeof objectSchema>\n >(true);\n expect(() => parseSchema(objectSchema, ['foo', 'bar'])).toThrow(\n 'Expected an object but received an array. Invalid type of data',\n );\n });\n\n it('should not run with an invalid keys', () => {\n const objectSchema = object({ foo: string() });\n\n expectEqualTypes<\n {\n foo: string;\n },\n InferType<typeof objectSchema>\n >(true);\n expect(() => parseSchema(objectSchema, { foo: 'valid key foo', bar: 'invalid key bar' })).toThrow(\n 'This key is not allowed in the object',\n );\n });\n\n it('should not run with missing required property', () => {\n const objectSchema = object({ foo: string(), bar: string() });\n\n expectEqualTypes<\n {\n foo: string;\n bar: string;\n },\n InferType<typeof objectSchema>\n >(true);\n expect(() => parseSchema(objectSchema, { foo: 'valid key foo' })).toThrow(\n 'Missing required property in the object',\n );\n });\n\n it('should validate complex object schema', () => {\n const userSchema = object({\n email: string().custom(email()),\n userName: string().optional(),\n verified: boolean().onlyTrue().optional(),\n phone: number().nullable().optional(),\n address: array(string().custom(minLength(3))),\n });\n\n interface User {\n email: string;\n address: string[];\n userName?: string | undefined;\n verified?: true | undefined;\n phone?: number | null | undefined;\n }\n\n expectEqualTypes<\n {\n email: string;\n address: string[];\n userName?: string | undefined;\n verified?: true | undefined;\n phone?: number | null | undefined;\n },\n InferType<typeof userSchema>\n >(true);\n\n const validUser: User = {\n email: 'foo@foo.com',\n address: ['my adress'],\n phone: null,\n verified: true,\n };\n\n expect(parseSchema(userSchema, validUser)).toBe(validUser);\n\n const userWithInvalidAddress: User = {\n email: 'foo@foo.com',\n address: ['my'],\n phone: null,\n verified: true,\n };\n\n expect(() => parseSchema(userSchema, userWithInvalidAddress)).toThrow(\n 'The received value length is less than expected',\n );\n\n const userWithInvalidEmail: User = {\n email: 'foofoo.com',\n address: ['my'],\n phone: null,\n verified: true,\n };\n\n expect(() => parseSchema(userSchema, userWithInvalidEmail)).toThrow(\n 'The received value does not match the required email pattern',\n );\n });\n});\n"],"mappings":";AAEO,SAAS,iBAAuB,UAA6B;AAClE,SAAO,OAAO,QAAQ,EAAE,KAAK,SAAS;AACxC;;;ACJO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY,UAAmB,UAAmB,aAAqB,SAAiB;AACtF,UAAM;AACN,SAAK,WAAW;AAChB,SAAK,WAAW;AAChB,SAAK,cAAc;AACnB,SAAK,UAAU;AAAA,EACjB;AACF;AAEO,IAAM,mBAAN,cAA+B,MAAM;AAAC;AAEtC,SAAS,eAAe,UAAmB,UAAmB,aAAqB,SAAwB;AAChH,QAAM,IAAI,gBAAgB,UAAU,UAAU,aAAa,OAAO;AACpE;;;AClBO,IAAM,YAAY,OAAO,eAAe;AAKxC,SAAS,WAAW,QAAsB,eAAwB,aAAqB;AAC5F,QAAM,MAAM,OAAO,SAAS;AAC5B,MAAI,kBAAkB,QAAW;AAC/B,QAAI,CAAC,IAAI,WAAY,gBAAe,YAAY,eAAe,aAAa,+BAA+B;AAC3G,WAAO;AAAA,EACT;AAEA,MAAI,kBAAkB,MAAM;AAC1B,Q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OAAO,MAAM,CAAC;AAAA,MAC9B,UAAU,OAAO,EAAE,SAAS;AAAA,MAC5B,UAAU,QAAQ,EAAE,SAAS,EAAE,SAAS;AAAA,MACxC,OAAO,OAAO,EAAE,SAAS,EAAE,SAAS;AAAA,MACpC,SAAS,MAAM,OAAO,EAAE,OAAO,UAAU,CAAC,CAAC,CAAC;AAAA,IAC9C,CAAC;AAUD,qBASE,IAAI;AAEN,UAAM,YAAkB;AAAA,MACtB,OAAO;AAAA,MACP,SAAS,CAAC,WAAW;AAAA,MACrB,OAAO;AAAA,MACP,UAAU;AAAA,IACZ;AAEA,WAAO,YAAY,YAAY,SAAS,CAAC,EAAE,KAAK,SAAS;AAEzD,UAAM,yBAA+B;AAAA,MACnC,OAAO;AAAA,MACP,SAAS,CAAC,IAAI;AAAA,MACd,OAAO;AAAA,MACP,UAAU;AAAA,IACZ;AAEA,WAAO,MAAM,YAAY,YAAY,sBAAsB,CAAC,EAAE;AAAA,MAC5D;AAAA,IACF;AAEA,UAAM,uBAA6B;AAAA,MACjC,OAAO;AAAA,MACP,SAAS,CAAC,IAAI;AAAA,MACd,OAAO;AAAA,MACP,UAAU;AAAA,IACZ;AAEA,WAAO,MAAM,YAAY,YAAY,oBAAoB,CAAC,EAAE;AAAA,MAC1D;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;","names":["schema"]}
|
|
@@ -1,228 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
// jest/setup.ts
|
|
4
|
-
function expectEqualTypes(areEqual) {
|
|
5
|
-
expect(typeof areEqual).toBe("boolean");
|
|
6
|
-
}
|
|
7
|
-
|
|
8
|
-
// src/exceptions.ts
|
|
9
|
-
var ValidationError = class extends Error {
|
|
10
|
-
expected;
|
|
11
|
-
received;
|
|
12
|
-
pathToError;
|
|
13
|
-
message;
|
|
14
|
-
constructor(expected, received, pathToError, message) {
|
|
15
|
-
super();
|
|
16
|
-
this.expected = expected;
|
|
17
|
-
this.received = received;
|
|
18
|
-
this.pathToError = pathToError;
|
|
19
|
-
this.message = message;
|
|
20
|
-
}
|
|
21
|
-
};
|
|
22
|
-
function throwException(expected, received, pathToError, message) {
|
|
23
|
-
throw new ValidationError(expected, received, pathToError, message);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// src/core.ts
|
|
27
|
-
var ctxSymbol = Symbol("contextSymbol");
|
|
28
|
-
function innerCheck(schema, receivedValue, pathToError) {
|
|
29
|
-
const ctx = schema[ctxSymbol];
|
|
30
|
-
if (receivedValue === void 0) {
|
|
31
|
-
if (!ctx.isOptional) throwException("Required", receivedValue, pathToError, "The required value is missing");
|
|
32
|
-
return receivedValue;
|
|
33
|
-
}
|
|
34
|
-
if (receivedValue === null) {
|
|
35
|
-
if (!ctx.isNullable) throwException("Not null", receivedValue, pathToError, "Value should not be null");
|
|
36
|
-
return receivedValue;
|
|
37
|
-
}
|
|
38
|
-
if (ctx.array) {
|
|
39
|
-
if (!Array.isArray(receivedValue))
|
|
40
|
-
throwException("Array", receivedValue, pathToError, "Expected an array but received a different type");
|
|
41
|
-
const schema2 = ctx.array;
|
|
42
|
-
receivedValue.forEach((elem, i) => {
|
|
43
|
-
innerCheck(schema2, elem, `${pathToError}[${i}]`);
|
|
44
|
-
});
|
|
45
|
-
return receivedValue;
|
|
46
|
-
}
|
|
47
|
-
const typeOfVal = typeof receivedValue;
|
|
48
|
-
if (ctx.object) {
|
|
49
|
-
if (typeOfVal !== "object")
|
|
50
|
-
throwException("Object", receivedValue, pathToError, "Expected an object but received a different type");
|
|
51
|
-
if (Array.isArray(receivedValue))
|
|
52
|
-
throwException(
|
|
53
|
-
"Object",
|
|
54
|
-
receivedValue,
|
|
55
|
-
pathToError,
|
|
56
|
-
"Expected an object but received an array. Invalid type of data"
|
|
57
|
-
);
|
|
58
|
-
const shapeSchema = ctx.object;
|
|
59
|
-
for (const keyPerReceivedValue of Object.keys(receivedValue)) {
|
|
60
|
-
if (shapeSchema[keyPerReceivedValue] === void 0)
|
|
61
|
-
throwException("Not allowed", keyPerReceivedValue, pathToError, "This key is not allowed in the object");
|
|
62
|
-
}
|
|
63
|
-
for (const [keyOfSchema, valueOfSchema] of Object.entries(shapeSchema)) {
|
|
64
|
-
const receivedObjectValuePropery = receivedValue[keyOfSchema];
|
|
65
|
-
if (receivedObjectValuePropery === void 0) {
|
|
66
|
-
if (!valueOfSchema[ctxSymbol].isOptional)
|
|
67
|
-
throwException(
|
|
68
|
-
"Required",
|
|
69
|
-
receivedObjectValuePropery,
|
|
70
|
-
pathToError,
|
|
71
|
-
"Missing required property in the object"
|
|
72
|
-
);
|
|
73
|
-
}
|
|
74
|
-
innerCheck(valueOfSchema, receivedObjectValuePropery, `${pathToError}.${keyOfSchema}`);
|
|
75
|
-
}
|
|
76
|
-
return receivedValue;
|
|
77
|
-
}
|
|
78
|
-
if (ctx.type.length) {
|
|
79
|
-
if (!ctx.type.includes(typeOfVal)) throwException(ctx.type, typeOfVal, pathToError, "Invalid type of data");
|
|
80
|
-
}
|
|
81
|
-
ctx.requiredValidations.forEach((requiredValidation) => {
|
|
82
|
-
requiredValidation(receivedValue, pathToError);
|
|
83
|
-
});
|
|
84
|
-
return receivedValue;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// src/parseSchema.ts
|
|
88
|
-
function parseSchema(schema, receivedValue) {
|
|
89
|
-
try {
|
|
90
|
-
return innerCheck(schema, receivedValue, "");
|
|
91
|
-
} catch (e) {
|
|
92
|
-
if (e instanceof ValidationError) throw e;
|
|
93
|
-
throw new Error("Something unexpected happened");
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// src/asserts/string/regExp.ts
|
|
98
|
-
var regExp = (expected) => (received, pathToError) => {
|
|
99
|
-
if (!expected.test(received))
|
|
100
|
-
throwException(expected, received, pathToError, "The received value does not match the required text pattern");
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
// src/asserts/common/equalTo.ts
|
|
104
|
-
var equalTo = (expected) => (received, pathToError) => {
|
|
105
|
-
if (expected !== received)
|
|
106
|
-
throwException(expected, received, pathToError, "The received value is not equal to expected");
|
|
107
|
-
};
|
|
108
|
-
|
|
109
|
-
// src/schemas/CommonSchema.ts
|
|
110
|
-
var CommonSchema = class {
|
|
111
|
-
[ctxSymbol];
|
|
112
|
-
constructor(ctx) {
|
|
113
|
-
this[ctxSymbol] = ctx;
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
|
-
* @param validators - One or more custom validation functions.
|
|
117
|
-
* @returns {this} The schema instance with the added custom validation.
|
|
118
|
-
*/
|
|
119
|
-
custom(...validators) {
|
|
120
|
-
this[ctxSymbol].requiredValidations.push(...validators);
|
|
121
|
-
return this;
|
|
122
|
-
}
|
|
123
|
-
/**
|
|
124
|
-
* Marks the schema as nullable, allowing the value to be `null`.
|
|
125
|
-
*
|
|
126
|
-
* @returns {WithNull<this>} The schema instance marked as nullable.
|
|
127
|
-
*/
|
|
128
|
-
nullable() {
|
|
129
|
-
this[ctxSymbol].isNullable = true;
|
|
130
|
-
return this;
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* Marks the schema as optional, allowing the value to be `undefined`.
|
|
134
|
-
*
|
|
135
|
-
* @returns {WithUndefined<this>}} The schema instance marked as optional.
|
|
136
|
-
*/
|
|
137
|
-
optional() {
|
|
138
|
-
this[ctxSymbol].isOptional = true;
|
|
139
|
-
return this;
|
|
140
|
-
}
|
|
141
|
-
};
|
|
142
|
-
|
|
143
|
-
// src/schemas/StringSchema.ts
|
|
144
|
-
var StringSchema = class extends CommonSchema {
|
|
145
|
-
_string = 1;
|
|
146
|
-
/**
|
|
147
|
-
* Restricts the schema to exactly match the specified value and infers the literal value as the TypeScript type.
|
|
148
|
-
*
|
|
149
|
-
* @param expectedValue - The value that the schema must exactly match.
|
|
150
|
-
* @returns - The schema instance restricted to the specified value, with the literal value inferred as the TypeScript type
|
|
151
|
-
*
|
|
152
|
-
* @example - string().equalTo('hello'); // Infers the type 'hello'
|
|
153
|
-
*/
|
|
154
|
-
equalTo(expectedValue) {
|
|
155
|
-
return this.custom(equalTo(expectedValue));
|
|
156
|
-
}
|
|
157
|
-
};
|
|
158
|
-
|
|
159
|
-
// src/asserts/string/index.ts
|
|
160
|
-
function string() {
|
|
161
|
-
return new StringSchema({ type: ["string"], requiredValidations: [] });
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// src/asserts/string/maxLength.ts
|
|
165
|
-
var maxLength = (expected) => (received, pathToError) => {
|
|
166
|
-
if (received.length > expected)
|
|
167
|
-
throwException(expected, received, pathToError, "The received value length is greater than expected");
|
|
168
|
-
};
|
|
169
|
-
|
|
170
|
-
// src/__tests__/StringSchema.test.ts
|
|
171
|
-
describe("StringSchema", () => {
|
|
172
|
-
const emailRegExp = /^[^@]+@[^@]+\.[^@]+$/;
|
|
173
|
-
it("should be a string", () => {
|
|
174
|
-
const stringSchema = string();
|
|
175
|
-
const actualString = "this is a string";
|
|
176
|
-
expectEqualTypes(true);
|
|
177
|
-
const parsedValue = parseSchema(stringSchema, actualString);
|
|
178
|
-
expect(parsedValue).toBe(actualString);
|
|
179
|
-
});
|
|
180
|
-
it("should not be a string", () => {
|
|
181
|
-
const stringSchema = string();
|
|
182
|
-
const actualNumber = 9;
|
|
183
|
-
expectEqualTypes(false);
|
|
184
|
-
expect(() => parseSchema(stringSchema, actualNumber)).toThrow("Invalid type of data");
|
|
185
|
-
});
|
|
186
|
-
it("should be an email", () => {
|
|
187
|
-
const emailSchema = string().custom(regExp(emailRegExp));
|
|
188
|
-
const email = "mygoodemail@email.com";
|
|
189
|
-
expectEqualTypes(true);
|
|
190
|
-
const parsedValue = parseSchema(emailSchema, email);
|
|
191
|
-
expect(parsedValue).toBe(email);
|
|
192
|
-
});
|
|
193
|
-
it("should not be an email", () => {
|
|
194
|
-
const emailSchema = string().custom(regExp(emailRegExp));
|
|
195
|
-
const email = "mybademailemail.com";
|
|
196
|
-
expectEqualTypes(true);
|
|
197
|
-
expect(() => parseSchema(emailSchema, email)).toThrow(
|
|
198
|
-
"The received value does not match the required text pattern"
|
|
199
|
-
);
|
|
200
|
-
});
|
|
201
|
-
it("should be equal to", () => {
|
|
202
|
-
const stringLiteralSchema = string().equalTo("rightStringLiteral");
|
|
203
|
-
const rightStringLiteral = "rightStringLiteral";
|
|
204
|
-
const wrongStringLiteral = "wrongStringLiteral";
|
|
205
|
-
expectEqualTypes(true);
|
|
206
|
-
expectEqualTypes(false);
|
|
207
|
-
expect(rightStringLiteral).toBe(rightStringLiteral);
|
|
208
|
-
expect(() => parseSchema(stringLiteralSchema, wrongStringLiteral)).toThrow(
|
|
209
|
-
"The received value is not equal to expected"
|
|
210
|
-
);
|
|
211
|
-
});
|
|
212
|
-
it("should be an alphanumeric pattern", () => {
|
|
213
|
-
const alphanumericSchema = string().custom(regExp(/^[A-Za-z0-9]+$/));
|
|
214
|
-
expectEqualTypes(true);
|
|
215
|
-
expect(parseSchema(alphanumericSchema, "valid123")).toBe("valid123");
|
|
216
|
-
expect(() => parseSchema(alphanumericSchema, "invalid!@#")).toThrow(
|
|
217
|
-
"The received value does not match the required text pattern"
|
|
218
|
-
);
|
|
219
|
-
});
|
|
220
|
-
it("should be an alphanumeric pattern", () => {
|
|
221
|
-
const textSchema = string().custom(maxLength(5));
|
|
222
|
-
expectEqualTypes(true);
|
|
223
|
-
expect(parseSchema(textSchema, "short")).toBe("short");
|
|
224
|
-
expect(parseSchema(textSchema, "yes")).toBe("yes");
|
|
225
|
-
expect(() => parseSchema(textSchema, "toolong")).toThrow("The received value length is greater than expected");
|
|
226
|
-
});
|
|
227
|
-
});
|
|
228
|
-
//# sourceMappingURL=StringSchema.test.js.map
|