@naturalcycles/nodejs-lib 15.144.0 → 15.145.1
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/dist/validation/ajv/index.d.ts +1 -0
- package/dist/validation/ajv/index.js +1 -0
- package/dist/validation/ajv/jSchema.d.ts +15 -1
- package/dist/validation/ajv/jSchema.js +31 -12
- package/dist/validation/ajv/jsonSchemaBuilder.util.js +1 -0
- package/dist/validation/ajv/mock/generateMockFromSchema.d.ts +71 -0
- package/dist/validation/ajv/mock/generateMockFromSchema.js +535 -0
- package/package.json +1 -1
- package/src/validation/ajv/index.ts +1 -0
- package/src/validation/ajv/jSchema.ts +44 -13
- package/src/validation/ajv/jsonSchemaBuilder.util.ts +1 -0
- package/src/validation/ajv/mock/generateMockFromSchema.ts +650 -0
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
import { _clamp, _isPlainObject } from '@naturalcycles/js-lib';
|
|
2
|
+
import { localDate, localTime } from '@naturalcycles/js-lib/datetime';
|
|
3
|
+
import { _mapValues, Set2 } from '@naturalcycles/js-lib/object';
|
|
4
|
+
import { _stringMapEntries } from '@naturalcycles/js-lib/types';
|
|
5
|
+
/**
|
|
6
|
+
* Generates a value that passes the schema, e.g for a mock in a test.
|
|
7
|
+
* Uses the example or default of a field when it has one, except an empty list or object as default.
|
|
8
|
+
* A string with a pattern needs an example or a default.
|
|
9
|
+
*
|
|
10
|
+
* ```
|
|
11
|
+
* const account = generateMockFromSchema(accountSchema, { allFields: true })
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* @experimental
|
|
15
|
+
*/
|
|
16
|
+
export function generateMockFromSchema(schema, opt = {}) {
|
|
17
|
+
const value = generateValue(schema.build(), '', { opt, choices: new Map(), reachedChoices: [] });
|
|
18
|
+
return schema.validate(value);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Generates the mock of `generateMockFromSchema` with `allFields`, plus one variant for each other
|
|
22
|
+
* branch of each `j.anyOfThese` and `j.anyOfBy` union, and for each other property of each group
|
|
23
|
+
* of exclusive properties, so every field appears in some variant.
|
|
24
|
+
* `j.anyOf` and `j.oneOf` always take their first branch, since their branches add no fields.
|
|
25
|
+
* With `maxProperties`, only the first fields up to the limit appear,
|
|
26
|
+
* e.g `b` never appears for `{ a?, b? }.maxProperties(1)`. With overlapping groups of exclusive
|
|
27
|
+
* properties, a property shared by two groups may not appear. When an earlier `j.anyOfThese` branch
|
|
28
|
+
* also matches a later branch's value, validation drops the later branch's extra fields, so put the
|
|
29
|
+
* wider branch first.
|
|
30
|
+
*
|
|
31
|
+
* ```
|
|
32
|
+
* const variants = generateMockVariantsFromSchema(accountSchema)
|
|
33
|
+
* // [{ value }, { value, choice: { path: 'address.taxId', option: 1, key: 'mx_rfc' } }]
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* @experimental
|
|
37
|
+
*/
|
|
38
|
+
export function generateMockVariantsFromSchema(schema) {
|
|
39
|
+
// Built once, so a choice is the same object in every run
|
|
40
|
+
const root = schema.build();
|
|
41
|
+
const queue = [{ choices: new Map() }];
|
|
42
|
+
const seenChoices = new Set();
|
|
43
|
+
const variants = [];
|
|
44
|
+
for (const { choices, choice } of queue) {
|
|
45
|
+
const ctx = { opt: { allFields: true }, choices, reachedChoices: [] };
|
|
46
|
+
const value = generateValue(root, '', ctx);
|
|
47
|
+
variants.push({ value: schema.validate(value), ...(choice && { choice }) });
|
|
48
|
+
for (const { point, path, options } of ctx.reachedChoices) {
|
|
49
|
+
if (seenChoices.has(point))
|
|
50
|
+
continue;
|
|
51
|
+
seenChoices.add(point);
|
|
52
|
+
for (let option = 1; option < options.length; option++) {
|
|
53
|
+
const { key } = options[option];
|
|
54
|
+
queue.push({
|
|
55
|
+
choices: new Map(choices).set(point, option),
|
|
56
|
+
choice: { path, option, ...(key !== undefined && { key }) },
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return variants;
|
|
62
|
+
}
|
|
63
|
+
const MOCK_UNIX_TIMESTAMP = 1_655_287_200; // 2022-06-15T10:00:00Z
|
|
64
|
+
const MOCK_ISO_DATE = '2022-06-15';
|
|
65
|
+
function generateValue(node, path, ctx) {
|
|
66
|
+
assertSupportedKeywords(node, path);
|
|
67
|
+
const value = generateValueFromKeywords(node, path, ctx);
|
|
68
|
+
if (node.optionalValues?.includes(value)) {
|
|
69
|
+
throw cannotGenerate(path, `the generated value ${JSON.stringify(value)} would be removed by optionalValues, give the field an example`);
|
|
70
|
+
}
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
function generateValueFromKeywords(node, path, ctx) {
|
|
74
|
+
if (node.examples?.length)
|
|
75
|
+
return copyPlainValue(node.examples[0]);
|
|
76
|
+
// An empty list or object as the default would leave nothing to show, e.g with `allFields`
|
|
77
|
+
if (node.default !== undefined && !isEmptyCollection(node.default)) {
|
|
78
|
+
return copyPlainValue(node.default);
|
|
79
|
+
}
|
|
80
|
+
if (node.isUndefined)
|
|
81
|
+
return undefined;
|
|
82
|
+
if (node.enum)
|
|
83
|
+
return node.enum[0];
|
|
84
|
+
if (node.ifDefined)
|
|
85
|
+
return generateValue(node.ifDefined, path, ctx);
|
|
86
|
+
if (node.anyOfThese || node.anyOfBy)
|
|
87
|
+
return generateFieldUnion(node, path, ctx);
|
|
88
|
+
const branches = [...(node.anyOf || []), ...(node.oneOf || [])];
|
|
89
|
+
if (branches.length) {
|
|
90
|
+
return generateValue(branches.find(isNonNullBranch) || branches[0], path, ctx);
|
|
91
|
+
}
|
|
92
|
+
if (node.instanceof === 'Date')
|
|
93
|
+
return localTime.fromUnix(MOCK_UNIX_TIMESTAMP).toDate();
|
|
94
|
+
if (node.instanceof) {
|
|
95
|
+
throw cannotGenerate(path, `cannot create an instance of ${node.instanceof}`);
|
|
96
|
+
}
|
|
97
|
+
if (node.Buffer)
|
|
98
|
+
return Buffer.from('mock');
|
|
99
|
+
if (node.Set2)
|
|
100
|
+
return new Set2(generateList(node, node.Set2, path, ctx));
|
|
101
|
+
if (node.type === 'string')
|
|
102
|
+
return generateString(node, path);
|
|
103
|
+
if (node.type === 'number' || node.type === 'integer')
|
|
104
|
+
return generateNumber(node, path);
|
|
105
|
+
if (node.type === 'boolean')
|
|
106
|
+
return true;
|
|
107
|
+
if (node.type === 'null')
|
|
108
|
+
return null;
|
|
109
|
+
if (node.type === 'array')
|
|
110
|
+
return generateArray(node, path, ctx);
|
|
111
|
+
if (node.type === 'object')
|
|
112
|
+
return generateObject(node, path, ctx);
|
|
113
|
+
// A schema without a type, e.g `j.any()`, accepts any value
|
|
114
|
+
return 'mock';
|
|
115
|
+
}
|
|
116
|
+
function assertSupportedKeywords(node, path) {
|
|
117
|
+
for (const keyword of Object.keys(node)) {
|
|
118
|
+
if (!SUPPORTED_KEYWORDS[keyword]) {
|
|
119
|
+
throw cannotGenerate(path, `the keyword ${keyword} is not supported`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function isEmptyCollection(value) {
|
|
124
|
+
if (Array.isArray(value))
|
|
125
|
+
return !value.length;
|
|
126
|
+
return _isPlainObject(value) && !Object.keys(value).length;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Copies plain objects, arrays and sets, so a variant does not share them with the schema
|
|
130
|
+
* or with other variants.
|
|
131
|
+
*/
|
|
132
|
+
function copyPlainValue(value) {
|
|
133
|
+
if (Array.isArray(value))
|
|
134
|
+
return value.map(copyPlainValue);
|
|
135
|
+
if (value instanceof Set2)
|
|
136
|
+
return new Set2(Array.from(value, copyPlainValue));
|
|
137
|
+
if (!_isPlainObject(value))
|
|
138
|
+
return value;
|
|
139
|
+
return _mapValues(value, (_, item) => copyPlainValue(item));
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Generates one branch of the union: the branch listed for it in `ctx.choices`, or else the first.
|
|
143
|
+
*/
|
|
144
|
+
function generateFieldUnion(node, path, ctx) {
|
|
145
|
+
const branches = getUnionBranches(node).filter(branch => isNonNullBranch(branch.schema));
|
|
146
|
+
if (!branches.length)
|
|
147
|
+
throw cannotGenerate(path, 'the union has no branch that is not null');
|
|
148
|
+
ctx.reachedChoices.push({ point: node, path, options: branches });
|
|
149
|
+
const { key, schema } = branches[ctx.choices.get(node) ?? 0];
|
|
150
|
+
const value = generateValue(schema, path, ctx);
|
|
151
|
+
if (!node.anyOfBy)
|
|
152
|
+
return value;
|
|
153
|
+
const { propertyName } = node.anyOfBy;
|
|
154
|
+
const properties = schema.properties || {};
|
|
155
|
+
return { ...value, [propertyName]: toPropertyValue(key, properties[propertyName]) };
|
|
156
|
+
}
|
|
157
|
+
function getUnionBranches(node) {
|
|
158
|
+
if (node.anyOfBy) {
|
|
159
|
+
return _stringMapEntries(node.anyOfBy.schemaDictionary).map(([key, schema]) => ({
|
|
160
|
+
key,
|
|
161
|
+
schema,
|
|
162
|
+
}));
|
|
163
|
+
}
|
|
164
|
+
return (node.anyOfThese || []).map(schema => ({ schema }));
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Dictionary keys are strings, while the property can be e.g a number enum.
|
|
168
|
+
* A nullable or optional property wraps its schema, e.g in `anyOf`, so those are searched too.
|
|
169
|
+
*/
|
|
170
|
+
function toPropertyValue(key, propertySchema) {
|
|
171
|
+
const schemas = [
|
|
172
|
+
propertySchema,
|
|
173
|
+
...(propertySchema?.anyOf || []),
|
|
174
|
+
...(propertySchema?.oneOf || []),
|
|
175
|
+
propertySchema?.ifDefined,
|
|
176
|
+
].filter(schema => schema !== undefined);
|
|
177
|
+
const enumValue = schemas
|
|
178
|
+
.flatMap(schema => schema.enum || [])
|
|
179
|
+
.find((value) => String(value) === key);
|
|
180
|
+
if (enumValue !== undefined)
|
|
181
|
+
return enumValue;
|
|
182
|
+
const types = new Set(schemas.map(schema => schema.type));
|
|
183
|
+
if (types.has('number') || types.has('integer'))
|
|
184
|
+
return Number(key);
|
|
185
|
+
if (types.has('boolean'))
|
|
186
|
+
return key === 'true';
|
|
187
|
+
return key;
|
|
188
|
+
}
|
|
189
|
+
function isNonNullBranch(branch) {
|
|
190
|
+
if (branch.type === 'null' || branch.isUndefined)
|
|
191
|
+
return false;
|
|
192
|
+
// `j.literal(null)` builds `{ enum: [null] }`
|
|
193
|
+
return !(branch.enum?.length === 1 && branch.enum[0] === null);
|
|
194
|
+
}
|
|
195
|
+
function generateString(node, path) {
|
|
196
|
+
if (node.IsoDate)
|
|
197
|
+
return generateIsoDate(node.IsoDate);
|
|
198
|
+
if (node.IsoDateTime)
|
|
199
|
+
return `${MOCK_ISO_DATE}T10:00:00Z`;
|
|
200
|
+
if (node.IsoMonth)
|
|
201
|
+
return MOCK_ISO_DATE.slice(0, 7);
|
|
202
|
+
if (node.UtcOffset)
|
|
203
|
+
return '+02:00';
|
|
204
|
+
if (node.email)
|
|
205
|
+
return 'mock@example.com';
|
|
206
|
+
if (node.pattern) {
|
|
207
|
+
throw cannotGenerate(path, 'a string with a pattern needs an example, .example(...)');
|
|
208
|
+
}
|
|
209
|
+
const value = 'mock'.padEnd(node.minLength || 0, 'x');
|
|
210
|
+
return value.slice(0, node.maxLength ?? value.length);
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* ISO dates sort as strings, so the bounds are compared as strings.
|
|
214
|
+
*/
|
|
215
|
+
function generateIsoDate(bounds) {
|
|
216
|
+
const { sameOrAfter, after, sameOrBefore, before } = bounds;
|
|
217
|
+
let date = MOCK_ISO_DATE;
|
|
218
|
+
if (sameOrAfter && date < sameOrAfter)
|
|
219
|
+
date = sameOrAfter;
|
|
220
|
+
if (after && date <= after) {
|
|
221
|
+
date = localDate(after)
|
|
222
|
+
.plusDays(1)
|
|
223
|
+
.toISODate();
|
|
224
|
+
}
|
|
225
|
+
if (sameOrBefore && date > sameOrBefore)
|
|
226
|
+
date = sameOrBefore;
|
|
227
|
+
if (before && date >= before) {
|
|
228
|
+
date = localDate(before)
|
|
229
|
+
.minusDays(1)
|
|
230
|
+
.toISODate();
|
|
231
|
+
}
|
|
232
|
+
return date;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* The preferred number if it fits the schema, else the preferred number rounded to the step,
|
|
236
|
+
* else the first number that fits from the lower bound up, or from the upper bound down.
|
|
237
|
+
*/
|
|
238
|
+
function generateNumber(node, path) {
|
|
239
|
+
const step = getStep(node);
|
|
240
|
+
const preferred = getPreferredNumber(node);
|
|
241
|
+
const candidates = [preferred, ...roundToStep(preferred, step), ...getBoundCandidates(node, step)];
|
|
242
|
+
const value = candidates.find(candidate => fitsNumberSchema(node, candidate, step));
|
|
243
|
+
if (value === undefined) {
|
|
244
|
+
throw cannotGenerate(path, 'no number satisfies the bounds of the schema');
|
|
245
|
+
}
|
|
246
|
+
// Turns -0 into 0
|
|
247
|
+
return value + 0;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* `multipleOf`, or 1 for an integer. For an integer with a fractional `multipleOf`,
|
|
251
|
+
* the smallest whole multiple of it, e.g 2 for 0.4.
|
|
252
|
+
*/
|
|
253
|
+
function getStep(node) {
|
|
254
|
+
const { multipleOf } = node;
|
|
255
|
+
if (node.type !== 'integer')
|
|
256
|
+
return multipleOf;
|
|
257
|
+
if (!multipleOf)
|
|
258
|
+
return 1;
|
|
259
|
+
// With `multipleOf` as a fraction `scaled / scale`, the whole multiple is `scaled / gcd`
|
|
260
|
+
const scale = getDecimalScale(multipleOf);
|
|
261
|
+
const scaled = Math.round(multipleOf * scale);
|
|
262
|
+
return scaled / getGreatestCommonDivisor(scaled, scale);
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* The power of 10 that makes the number whole, e.g 100 for 0.25.
|
|
266
|
+
* Stops at 10^15, the precision of a number, e.g for 1/3.
|
|
267
|
+
*/
|
|
268
|
+
function getDecimalScale(value) {
|
|
269
|
+
let scale = 1;
|
|
270
|
+
while (Math.abs(value * scale - Math.round(value * scale)) > 1e-9 && scale < 1e15)
|
|
271
|
+
scale *= 10;
|
|
272
|
+
return scale;
|
|
273
|
+
}
|
|
274
|
+
function getGreatestCommonDivisor(a, b) {
|
|
275
|
+
if (!b)
|
|
276
|
+
return a;
|
|
277
|
+
return getGreatestCommonDivisor(b, a % b);
|
|
278
|
+
}
|
|
279
|
+
function getPreferredNumber(node) {
|
|
280
|
+
if (node.format === 'UnixTimestamp')
|
|
281
|
+
return MOCK_UNIX_TIMESTAMP;
|
|
282
|
+
if (node.format === 'UnixTimestampMillis')
|
|
283
|
+
return MOCK_UNIX_TIMESTAMP * 1000;
|
|
284
|
+
return 1;
|
|
285
|
+
}
|
|
286
|
+
function roundToStep(value, step) {
|
|
287
|
+
if (!step)
|
|
288
|
+
return [];
|
|
289
|
+
return [Math.ceil(value / step) * step, Math.floor(value / step) * step];
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* The first numbers at or inside the lower bound, or else the upper bound: with a step, the first
|
|
293
|
+
* two multiples, without one the bound itself, the midpoint between the bounds, and the bound + 1.
|
|
294
|
+
*/
|
|
295
|
+
function getBoundCandidates(node, step) {
|
|
296
|
+
const lower = getTightestBound([node.minimum, node.exclusiveMinimum], Math.max);
|
|
297
|
+
const upper = getTightestBound([node.maximum, node.exclusiveMaximum], Math.min);
|
|
298
|
+
if (lower !== undefined && step) {
|
|
299
|
+
const first = Math.ceil(lower / step) * step;
|
|
300
|
+
return [first, first + step];
|
|
301
|
+
}
|
|
302
|
+
if (lower !== undefined) {
|
|
303
|
+
const midpoint = upper === undefined ? lower : lower + (upper - lower) / 2;
|
|
304
|
+
return [lower, midpoint, lower + 1];
|
|
305
|
+
}
|
|
306
|
+
if (upper !== undefined && step) {
|
|
307
|
+
const last = Math.floor(upper / step) * step;
|
|
308
|
+
return [last, last - step];
|
|
309
|
+
}
|
|
310
|
+
if (upper !== undefined)
|
|
311
|
+
return [upper, upper - 1];
|
|
312
|
+
return [];
|
|
313
|
+
}
|
|
314
|
+
function getTightestBound(bounds, pick) {
|
|
315
|
+
const definedBounds = bounds.filter(bound => bound !== undefined);
|
|
316
|
+
if (!definedBounds.length)
|
|
317
|
+
return;
|
|
318
|
+
return pick(...definedBounds);
|
|
319
|
+
}
|
|
320
|
+
function fitsNumberSchema(node, value, step) {
|
|
321
|
+
if (node.minimum !== undefined && value < node.minimum)
|
|
322
|
+
return false;
|
|
323
|
+
if (node.exclusiveMinimum !== undefined && value <= node.exclusiveMinimum)
|
|
324
|
+
return false;
|
|
325
|
+
if (node.maximum !== undefined && value > node.maximum)
|
|
326
|
+
return false;
|
|
327
|
+
if (node.exclusiveMaximum !== undefined && value >= node.exclusiveMaximum)
|
|
328
|
+
return false;
|
|
329
|
+
if (node.multipleOf && !Number.isInteger(value / node.multipleOf))
|
|
330
|
+
return false;
|
|
331
|
+
if (step && !Number.isInteger(value / step))
|
|
332
|
+
return false;
|
|
333
|
+
if (node.type === 'integer' && !Number.isInteger(value))
|
|
334
|
+
return false;
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
function generateArray(node, path, ctx) {
|
|
338
|
+
if (node.prefixItems) {
|
|
339
|
+
return node.prefixItems.map(item => generateValue(item, path, ctx));
|
|
340
|
+
}
|
|
341
|
+
if (!node.items)
|
|
342
|
+
return [];
|
|
343
|
+
return generateList(node, node.items, path, ctx);
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* `minItems` items, at least one with `allFields`, at most `maxItems`.
|
|
347
|
+
*/
|
|
348
|
+
function generateList(node, itemSchema, path, ctx) {
|
|
349
|
+
const minCount = Math.max(node.minItems || 0, ctx.opt.allFields ? 1 : 0);
|
|
350
|
+
const count = _clamp(minCount, 0, node.maxItems ?? minCount);
|
|
351
|
+
if (count > 1 && (node.Set2 || node.uniqueItems)) {
|
|
352
|
+
throw cannotGenerate(path, `a list of ${count} distinct items needs an example, .example([...])`);
|
|
353
|
+
}
|
|
354
|
+
// The items share the path of the list: they come from the same schema
|
|
355
|
+
return Array.from({ length: count }, () => generateValue(itemSchema, path, ctx));
|
|
356
|
+
}
|
|
357
|
+
function generateObject(node, path, ctx) {
|
|
358
|
+
const keys = selectPropertyKeys(node, path, ctx);
|
|
359
|
+
const properties = node.properties || {};
|
|
360
|
+
const result = {};
|
|
361
|
+
for (const key of keys) {
|
|
362
|
+
const value = generateValue(properties[key], joinPath(path, key), ctx);
|
|
363
|
+
if (value !== undefined)
|
|
364
|
+
result[key] = value;
|
|
365
|
+
}
|
|
366
|
+
const shouldFillMaps = ctx.opt.allFields || keys.length < (node.minProperties || 0);
|
|
367
|
+
const hasRoomForMaps = keys.length < (node.maxProperties ?? Infinity);
|
|
368
|
+
if (!shouldFillMaps || !hasRoomForMaps)
|
|
369
|
+
return result;
|
|
370
|
+
const missingCount = (node.minProperties || 0) - keys.length;
|
|
371
|
+
if (missingCount > 1) {
|
|
372
|
+
throw cannotGenerate(path, `a map of ${missingCount} keys needs an example, .example({...})`);
|
|
373
|
+
}
|
|
374
|
+
for (const [pattern, valueSchema] of _stringMapEntries(node.patternProperties || {})) {
|
|
375
|
+
const key = generateKey(node, path, ctx);
|
|
376
|
+
if (key === undefined) {
|
|
377
|
+
throw cannotGenerate(path, `a map with keys matching ${pattern} needs an example, .example({...})`);
|
|
378
|
+
}
|
|
379
|
+
assertKeyIsFree(node, result, key, path);
|
|
380
|
+
result[key] = generateValue(valueSchema, joinPath(path, key), ctx);
|
|
381
|
+
}
|
|
382
|
+
if (typeof node.additionalProperties === 'object') {
|
|
383
|
+
const key = generateKey(node, path, ctx) ?? findFreeKey(node, result);
|
|
384
|
+
assertKeyIsFree(node, result, key, path);
|
|
385
|
+
result[key] = generateValue(node.additionalProperties, joinPath(path, key), ctx);
|
|
386
|
+
}
|
|
387
|
+
// An object of any shape, e.g `j.object.any()`, gets one entry like a map
|
|
388
|
+
if (node.additionalProperties === true && !Object.keys(properties).length) {
|
|
389
|
+
result['key'] = 'mock';
|
|
390
|
+
}
|
|
391
|
+
return result;
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* `key`, or else `key1`, `key2` and so on, whichever the object does not have yet.
|
|
395
|
+
*/
|
|
396
|
+
function findFreeKey(node, result) {
|
|
397
|
+
let key = 'key';
|
|
398
|
+
for (let index = 1; isKeyTaken(node, result, key); index++)
|
|
399
|
+
key = `key${index}`;
|
|
400
|
+
return key;
|
|
401
|
+
}
|
|
402
|
+
function assertKeyIsFree(node, result, key, path) {
|
|
403
|
+
if (isKeyTaken(node, result, key)) {
|
|
404
|
+
throw cannotGenerate(joinPath(path, key), `the key schema gives the key ${JSON.stringify(key)}, which is also a field of the object: give the key schema another example, or the map an example, .example({...})`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
function isKeyTaken(node, result, key) {
|
|
408
|
+
return Object.hasOwn(node.properties || {}, key) || Object.hasOwn(result, key);
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* The required keys, or every key with `allFields`, plus optional keys until `minProperties`
|
|
412
|
+
* is reached, and at most `maxProperties` keys. Only one key of each group of exclusive properties
|
|
413
|
+
* is kept. The keys keep the order of the schema.
|
|
414
|
+
*/
|
|
415
|
+
function selectPropertyKeys(node, path, ctx) {
|
|
416
|
+
const required = node.required || [];
|
|
417
|
+
const excludedKeys = new Set((node.exclusiveProperties || []).flatMap(group => {
|
|
418
|
+
const keptKey = chooseExclusiveKey(group, required, path, ctx);
|
|
419
|
+
return group.filter(key => key !== keptKey);
|
|
420
|
+
}));
|
|
421
|
+
const candidateKeys = Object.keys(node.properties || {}).filter(key => !excludedKeys.has(key));
|
|
422
|
+
const requiredKeys = candidateKeys.filter(key => required.includes(key));
|
|
423
|
+
const optionalKeys = candidateKeys.filter(key => !required.includes(key));
|
|
424
|
+
const minCount = ctx.opt.allFields
|
|
425
|
+
? candidateKeys.length
|
|
426
|
+
: Math.max(requiredKeys.length, node.minProperties || 0);
|
|
427
|
+
const count = _clamp(minCount, 0, node.maxProperties ?? minCount);
|
|
428
|
+
const keptOptionalKeys = new Set(optionalKeys.slice(0, Math.max(0, count - requiredKeys.length)));
|
|
429
|
+
return candidateKeys.filter(key => required.includes(key) || keptOptionalKeys.has(key));
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* The required key of the group, or else the key listed for the group in `ctx.choices`,
|
|
433
|
+
* or else the first.
|
|
434
|
+
*/
|
|
435
|
+
function chooseExclusiveKey(group, required, path, ctx) {
|
|
436
|
+
const requiredKey = group.find(key => required.includes(key));
|
|
437
|
+
if (requiredKey)
|
|
438
|
+
return requiredKey;
|
|
439
|
+
ctx.reachedChoices.push({ point: group, path, options: group.map(key => ({ key })) });
|
|
440
|
+
return group[ctx.choices.get(group) ?? 0];
|
|
441
|
+
}
|
|
442
|
+
function generateKey(node, path, ctx) {
|
|
443
|
+
if (!node.keySchema)
|
|
444
|
+
return;
|
|
445
|
+
return String(generateValue(node.keySchema, joinPath(path, '<key>'), ctx));
|
|
446
|
+
}
|
|
447
|
+
function cannotGenerate(path, reason) {
|
|
448
|
+
return new Error(`Cannot generate a value at ${path || '(root)'}: ${reason}`);
|
|
449
|
+
}
|
|
450
|
+
function joinPath(path, segment) {
|
|
451
|
+
if (!path)
|
|
452
|
+
return segment;
|
|
453
|
+
return `${path}.${segment}`;
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Whether the generator supports each keyword. A schema with an unsupported or unknown keyword
|
|
457
|
+
* throws, so the generator does not silently produce a wrong value.
|
|
458
|
+
*/
|
|
459
|
+
const SUPPORTED_KEYWORDS = {
|
|
460
|
+
// Values
|
|
461
|
+
type: true,
|
|
462
|
+
default: true,
|
|
463
|
+
examples: true,
|
|
464
|
+
enum: true,
|
|
465
|
+
// Unions
|
|
466
|
+
anyOf: true,
|
|
467
|
+
oneOf: true,
|
|
468
|
+
anyOfThese: true,
|
|
469
|
+
anyOfBy: true,
|
|
470
|
+
ifDefined: true,
|
|
471
|
+
isUndefined: true,
|
|
472
|
+
// Strings
|
|
473
|
+
pattern: true,
|
|
474
|
+
minLength: true,
|
|
475
|
+
maxLength: true,
|
|
476
|
+
format: true,
|
|
477
|
+
email: true,
|
|
478
|
+
IsoDate: true,
|
|
479
|
+
IsoDateTime: true,
|
|
480
|
+
IsoMonth: true,
|
|
481
|
+
UtcOffset: true,
|
|
482
|
+
// Numbers
|
|
483
|
+
minimum: true,
|
|
484
|
+
exclusiveMinimum: true,
|
|
485
|
+
maximum: true,
|
|
486
|
+
exclusiveMaximum: true,
|
|
487
|
+
multipleOf: true,
|
|
488
|
+
precision: true,
|
|
489
|
+
// Arrays and sets
|
|
490
|
+
items: true,
|
|
491
|
+
prefixItems: true,
|
|
492
|
+
minItems: true,
|
|
493
|
+
maxItems: true,
|
|
494
|
+
uniqueItems: true,
|
|
495
|
+
Set2: true,
|
|
496
|
+
// Objects
|
|
497
|
+
properties: true,
|
|
498
|
+
required: true,
|
|
499
|
+
patternProperties: true,
|
|
500
|
+
additionalProperties: true,
|
|
501
|
+
keySchema: true,
|
|
502
|
+
minProperties: true,
|
|
503
|
+
minProperties2: true,
|
|
504
|
+
maxProperties: true,
|
|
505
|
+
exclusiveProperties: true,
|
|
506
|
+
instanceof: true,
|
|
507
|
+
Buffer: true,
|
|
508
|
+
// Annotations, and rules that the validation at the end checks
|
|
509
|
+
$schema: true,
|
|
510
|
+
$id: true,
|
|
511
|
+
title: true,
|
|
512
|
+
description: true,
|
|
513
|
+
deprecated: true,
|
|
514
|
+
readOnly: true,
|
|
515
|
+
writeOnly: true,
|
|
516
|
+
hasIsOfTypeCheck: true,
|
|
517
|
+
errorMessages: true,
|
|
518
|
+
enumNames: true,
|
|
519
|
+
enumKeys: true,
|
|
520
|
+
transform: true,
|
|
521
|
+
optionalValues: true,
|
|
522
|
+
customValidations: true,
|
|
523
|
+
customConversions: true,
|
|
524
|
+
postValidation: true,
|
|
525
|
+
// Not built by `j`
|
|
526
|
+
if: false,
|
|
527
|
+
// oxlint-disable-next-line unicorn/no-thenable -- a JSON Schema keyword, the object is never awaited
|
|
528
|
+
then: false,
|
|
529
|
+
else: false,
|
|
530
|
+
contentMediaType: false,
|
|
531
|
+
contentEncoding: false,
|
|
532
|
+
// Type-only and parser-only fields, never in a built schema
|
|
533
|
+
out: false,
|
|
534
|
+
optionalField: false,
|
|
535
|
+
};
|
package/package.json
CHANGED
|
@@ -4,6 +4,7 @@ export * from './ajvValidationError.js'
|
|
|
4
4
|
export * from './from-data/generateJsonSchemaFromData.js'
|
|
5
5
|
export * from './getAjv.js'
|
|
6
6
|
export * from './jSchema.js'
|
|
7
|
+
export * from './mock/generateMockFromSchema.js'
|
|
7
8
|
export { jFormats, type JFormat } from './jsonSchemaBuilder.util.js'
|
|
8
9
|
|
|
9
10
|
export { Ajv }
|
|
@@ -590,6 +590,18 @@ export class JBuilder<OUT, Opt> extends JSchema<OUT, Opt> {
|
|
|
590
590
|
return this.cloneAndUpdateSchema({ default: v })
|
|
591
591
|
}
|
|
592
592
|
|
|
593
|
+
/**
|
|
594
|
+
* Gives an example of a valid input value. It is not validated.
|
|
595
|
+
* The example must be a plain value: `build()` does not keep class instances.
|
|
596
|
+
*
|
|
597
|
+
* ```
|
|
598
|
+
* const schema = j.string().regex(/^[A-Z]{3}-\d{4}$/).example('ABC-1234')
|
|
599
|
+
* ```
|
|
600
|
+
*/
|
|
601
|
+
example(example: any): this {
|
|
602
|
+
return this.cloneAndUpdateSchema({ examples: [example] })
|
|
603
|
+
}
|
|
604
|
+
|
|
593
605
|
instanceof(of: string): this {
|
|
594
606
|
return this.cloneAndUpdateSchema({ type: 'object', instanceof: of })
|
|
595
607
|
}
|
|
@@ -828,30 +840,34 @@ export class JString<
|
|
|
828
840
|
* Expects the JWT to be signed!
|
|
829
841
|
*/
|
|
830
842
|
jwt(): this {
|
|
831
|
-
return this.regex(JWT_REGEX, { msg: 'is not a valid JWT format' })
|
|
843
|
+
return this.regex(JWT_REGEX, { msg: 'is not a valid JWT format' }).example(
|
|
844
|
+
'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIn0.c2lnbmF0dXJl',
|
|
845
|
+
)
|
|
832
846
|
}
|
|
833
847
|
|
|
834
848
|
url(): this {
|
|
835
|
-
return this.regex(URL_REGEX, { msg: 'is not a valid URL format' })
|
|
849
|
+
return this.regex(URL_REGEX, { msg: 'is not a valid URL format' }).example(
|
|
850
|
+
'https://example.com',
|
|
851
|
+
)
|
|
836
852
|
}
|
|
837
853
|
|
|
838
854
|
ipv4(): this {
|
|
839
|
-
return this.regex(IPV4_REGEX, { msg: 'is not a valid IPv4 format' })
|
|
855
|
+
return this.regex(IPV4_REGEX, { msg: 'is not a valid IPv4 format' }).example('192.0.2.1')
|
|
840
856
|
}
|
|
841
857
|
|
|
842
858
|
ipv6(): this {
|
|
843
|
-
return this.regex(IPV6_REGEX, { msg: 'is not a valid IPv6 format' })
|
|
859
|
+
return this.regex(IPV6_REGEX, { msg: 'is not a valid IPv6 format' }).example('2001:db8::1')
|
|
844
860
|
}
|
|
845
861
|
|
|
846
862
|
slug(): this {
|
|
847
|
-
return this.regex(SLUG_REGEX, { msg: 'is not a valid slug format' })
|
|
863
|
+
return this.regex(SLUG_REGEX, { msg: 'is not a valid slug format' }).example('my-slug')
|
|
848
864
|
}
|
|
849
865
|
|
|
850
866
|
/**
|
|
851
867
|
* Validates the 3-part semver format: `major.minor.patch`, e.g `1.2.3`.
|
|
852
868
|
*/
|
|
853
869
|
semVer(): this {
|
|
854
|
-
return this.regex(SEMVER_REGEX, { msg: 'is not a valid semver format' })
|
|
870
|
+
return this.regex(SEMVER_REGEX, { msg: 'is not a valid semver format' }).example('1.2.3')
|
|
855
871
|
}
|
|
856
872
|
|
|
857
873
|
/**
|
|
@@ -860,19 +876,27 @@ export class JString<
|
|
|
860
876
|
* Not a semver by the spec, but is used by e.g .NET and some mobile app versions.
|
|
861
877
|
*/
|
|
862
878
|
semVer4(): this {
|
|
863
|
-
return this.regex(SEMVER4_REGEX, {
|
|
879
|
+
return this.regex(SEMVER4_REGEX, {
|
|
880
|
+
msg: 'is not a valid 4-part semver format',
|
|
881
|
+
}).example('1.2.3.4')
|
|
864
882
|
}
|
|
865
883
|
|
|
866
884
|
languageTag(): this {
|
|
867
|
-
return this.regex(LANGUAGE_TAG_REGEX, {
|
|
885
|
+
return this.regex(LANGUAGE_TAG_REGEX, {
|
|
886
|
+
msg: 'is not a valid language format',
|
|
887
|
+
}).example('en-US')
|
|
868
888
|
}
|
|
869
889
|
|
|
870
890
|
countryCode(): this {
|
|
871
|
-
return this.regex(COUNTRY_CODE_REGEX, {
|
|
891
|
+
return this.regex(COUNTRY_CODE_REGEX, {
|
|
892
|
+
msg: 'is not a valid country code format',
|
|
893
|
+
}).example('US')
|
|
872
894
|
}
|
|
873
895
|
|
|
874
896
|
currency(): this {
|
|
875
|
-
return this.regex(CURRENCY_REGEX, {
|
|
897
|
+
return this.regex(CURRENCY_REGEX, {
|
|
898
|
+
msg: 'is not a valid currency format',
|
|
899
|
+
}).example('USD')
|
|
876
900
|
}
|
|
877
901
|
|
|
878
902
|
/**
|
|
@@ -889,11 +913,13 @@ export class JString<
|
|
|
889
913
|
base64Url(): this {
|
|
890
914
|
return this.regex(BASE64URL_REGEX, {
|
|
891
915
|
msg: 'contains characters not allowed in Base64 URL characterset',
|
|
892
|
-
})
|
|
916
|
+
}).example('abc-DEF_123')
|
|
893
917
|
}
|
|
894
918
|
|
|
895
919
|
uuid(): this {
|
|
896
|
-
return this.regex(UUID_REGEX, { msg: 'is an invalid UUID' })
|
|
920
|
+
return this.regex(UUID_REGEX, { msg: 'is an invalid UUID' }).example(
|
|
921
|
+
'123e4567-e89b-12d3-a456-426614174000',
|
|
922
|
+
)
|
|
897
923
|
}
|
|
898
924
|
}
|
|
899
925
|
|
|
@@ -2143,7 +2169,12 @@ export interface JsonSchema<OUT = unknown> {
|
|
|
2143
2169
|
minProperties?: number
|
|
2144
2170
|
maxProperties?: number
|
|
2145
2171
|
|
|
2146
|
-
default?:
|
|
2172
|
+
default?: unknown
|
|
2173
|
+
/**
|
|
2174
|
+
* Examples of a valid input value.
|
|
2175
|
+
* Annotation only (not validated), lets consumers generate e.g a mock value.
|
|
2176
|
+
*/
|
|
2177
|
+
examples?: unknown[]
|
|
2147
2178
|
|
|
2148
2179
|
// https://json-schema.org/understanding-json-schema/reference/conditionals.html#id6
|
|
2149
2180
|
if?: JsonSchema
|