@naturalcycles/nodejs-lib 15.143.0 → 15.145.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/validation/ajv/getAjv.js +5 -0
- package/dist/validation/ajv/index.d.ts +1 -0
- package/dist/validation/ajv/index.js +1 -0
- package/dist/validation/ajv/jSchema.d.ts +49 -1
- package/dist/validation/ajv/jSchema.js +84 -30
- package/dist/validation/ajv/jsonSchemaBuilder.util.js +2 -0
- package/dist/validation/ajv/mock/generateMockFromSchema.d.ts +67 -0
- package/dist/validation/ajv/mock/generateMockFromSchema.js +524 -0
- package/package.json +1 -1
- package/src/validation/ajv/getAjv.ts +6 -0
- package/src/validation/ajv/index.ts +1 -0
- package/src/validation/ajv/jSchema.ts +127 -40
- package/src/validation/ajv/jsonSchemaBuilder.util.ts +2 -0
- package/src/validation/ajv/mock/generateMockFromSchema.ts +633 -0
|
@@ -0,0 +1,524 @@
|
|
|
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.
|
|
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
|
+
if (node.default !== undefined)
|
|
77
|
+
return copyPlainValue(node.default);
|
|
78
|
+
if (node.isUndefined)
|
|
79
|
+
return undefined;
|
|
80
|
+
if (node.enum)
|
|
81
|
+
return node.enum[0];
|
|
82
|
+
if (node.ifDefined)
|
|
83
|
+
return generateValue(node.ifDefined, path, ctx);
|
|
84
|
+
if (node.anyOfThese || node.anyOfBy)
|
|
85
|
+
return generateFieldUnion(node, path, ctx);
|
|
86
|
+
const branches = [...(node.anyOf || []), ...(node.oneOf || [])];
|
|
87
|
+
if (branches.length) {
|
|
88
|
+
return generateValue(branches.find(isNonNullBranch) || branches[0], path, ctx);
|
|
89
|
+
}
|
|
90
|
+
if (node.instanceof === 'Date')
|
|
91
|
+
return localTime.fromUnix(MOCK_UNIX_TIMESTAMP).toDate();
|
|
92
|
+
if (node.instanceof) {
|
|
93
|
+
throw cannotGenerate(path, `cannot create an instance of ${node.instanceof}`);
|
|
94
|
+
}
|
|
95
|
+
if (node.Buffer)
|
|
96
|
+
return Buffer.from('mock');
|
|
97
|
+
if (node.Set2)
|
|
98
|
+
return new Set2(generateList(node, node.Set2, path, ctx));
|
|
99
|
+
if (node.type === 'string')
|
|
100
|
+
return generateString(node, path);
|
|
101
|
+
if (node.type === 'number' || node.type === 'integer')
|
|
102
|
+
return generateNumber(node, path);
|
|
103
|
+
if (node.type === 'boolean')
|
|
104
|
+
return true;
|
|
105
|
+
if (node.type === 'null')
|
|
106
|
+
return null;
|
|
107
|
+
if (node.type === 'array')
|
|
108
|
+
return generateArray(node, path, ctx);
|
|
109
|
+
if (node.type === 'object')
|
|
110
|
+
return generateObject(node, path, ctx);
|
|
111
|
+
// A schema without a type, e.g `j.any()`, accepts any value
|
|
112
|
+
return 'mock';
|
|
113
|
+
}
|
|
114
|
+
function assertSupportedKeywords(node, path) {
|
|
115
|
+
for (const keyword of Object.keys(node)) {
|
|
116
|
+
if (!SUPPORTED_KEYWORDS[keyword]) {
|
|
117
|
+
throw cannotGenerate(path, `the keyword ${keyword} is not supported`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Copies plain objects, arrays and sets, so a variant does not share them with the schema
|
|
123
|
+
* or with other variants.
|
|
124
|
+
*/
|
|
125
|
+
function copyPlainValue(value) {
|
|
126
|
+
if (Array.isArray(value))
|
|
127
|
+
return value.map(copyPlainValue);
|
|
128
|
+
if (value instanceof Set2)
|
|
129
|
+
return new Set2(Array.from(value, copyPlainValue));
|
|
130
|
+
if (!_isPlainObject(value))
|
|
131
|
+
return value;
|
|
132
|
+
return _mapValues(value, (_, item) => copyPlainValue(item));
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Generates one branch of the union: the branch listed for it in `ctx.choices`, or else the first.
|
|
136
|
+
*/
|
|
137
|
+
function generateFieldUnion(node, path, ctx) {
|
|
138
|
+
const branches = getUnionBranches(node).filter(branch => isNonNullBranch(branch.schema));
|
|
139
|
+
if (!branches.length)
|
|
140
|
+
throw cannotGenerate(path, 'the union has no branch that is not null');
|
|
141
|
+
ctx.reachedChoices.push({ point: node, path, options: branches });
|
|
142
|
+
const { key, schema } = branches[ctx.choices.get(node) ?? 0];
|
|
143
|
+
const value = generateValue(schema, path, ctx);
|
|
144
|
+
if (!node.anyOfBy)
|
|
145
|
+
return value;
|
|
146
|
+
const { propertyName } = node.anyOfBy;
|
|
147
|
+
const properties = schema.properties || {};
|
|
148
|
+
return { ...value, [propertyName]: toPropertyValue(key, properties[propertyName]) };
|
|
149
|
+
}
|
|
150
|
+
function getUnionBranches(node) {
|
|
151
|
+
if (node.anyOfBy) {
|
|
152
|
+
return _stringMapEntries(node.anyOfBy.schemaDictionary).map(([key, schema]) => ({
|
|
153
|
+
key,
|
|
154
|
+
schema,
|
|
155
|
+
}));
|
|
156
|
+
}
|
|
157
|
+
return (node.anyOfThese || []).map(schema => ({ schema }));
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Dictionary keys are strings, while the property can be e.g a number enum.
|
|
161
|
+
* A nullable or optional property wraps its schema, e.g in `anyOf`, so those are searched too.
|
|
162
|
+
*/
|
|
163
|
+
function toPropertyValue(key, propertySchema) {
|
|
164
|
+
const schemas = [
|
|
165
|
+
propertySchema,
|
|
166
|
+
...(propertySchema?.anyOf || []),
|
|
167
|
+
...(propertySchema?.oneOf || []),
|
|
168
|
+
propertySchema?.ifDefined,
|
|
169
|
+
].filter(schema => schema !== undefined);
|
|
170
|
+
const enumValue = schemas
|
|
171
|
+
.flatMap(schema => schema.enum || [])
|
|
172
|
+
.find((value) => String(value) === key);
|
|
173
|
+
if (enumValue !== undefined)
|
|
174
|
+
return enumValue;
|
|
175
|
+
const types = new Set(schemas.map(schema => schema.type));
|
|
176
|
+
if (types.has('number') || types.has('integer'))
|
|
177
|
+
return Number(key);
|
|
178
|
+
if (types.has('boolean'))
|
|
179
|
+
return key === 'true';
|
|
180
|
+
return key;
|
|
181
|
+
}
|
|
182
|
+
function isNonNullBranch(branch) {
|
|
183
|
+
if (branch.type === 'null' || branch.isUndefined)
|
|
184
|
+
return false;
|
|
185
|
+
// `j.literal(null)` builds `{ enum: [null] }`
|
|
186
|
+
return !(branch.enum?.length === 1 && branch.enum[0] === null);
|
|
187
|
+
}
|
|
188
|
+
function generateString(node, path) {
|
|
189
|
+
if (node.IsoDate)
|
|
190
|
+
return generateIsoDate(node.IsoDate);
|
|
191
|
+
if (node.IsoDateTime)
|
|
192
|
+
return `${MOCK_ISO_DATE}T10:00:00Z`;
|
|
193
|
+
if (node.IsoMonth)
|
|
194
|
+
return MOCK_ISO_DATE.slice(0, 7);
|
|
195
|
+
if (node.UtcOffset)
|
|
196
|
+
return '+02:00';
|
|
197
|
+
if (node.email)
|
|
198
|
+
return 'mock@example.com';
|
|
199
|
+
if (node.pattern) {
|
|
200
|
+
throw cannotGenerate(path, 'a string with a pattern needs an example, .example(...)');
|
|
201
|
+
}
|
|
202
|
+
const value = 'mock'.padEnd(node.minLength || 0, 'x');
|
|
203
|
+
return value.slice(0, node.maxLength ?? value.length);
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* ISO dates sort as strings, so the bounds are compared as strings.
|
|
207
|
+
*/
|
|
208
|
+
function generateIsoDate(bounds) {
|
|
209
|
+
const { sameOrAfter, after, sameOrBefore, before } = bounds;
|
|
210
|
+
let date = MOCK_ISO_DATE;
|
|
211
|
+
if (sameOrAfter && date < sameOrAfter)
|
|
212
|
+
date = sameOrAfter;
|
|
213
|
+
if (after && date <= after) {
|
|
214
|
+
date = localDate(after)
|
|
215
|
+
.plusDays(1)
|
|
216
|
+
.toISODate();
|
|
217
|
+
}
|
|
218
|
+
if (sameOrBefore && date > sameOrBefore)
|
|
219
|
+
date = sameOrBefore;
|
|
220
|
+
if (before && date >= before) {
|
|
221
|
+
date = localDate(before)
|
|
222
|
+
.minusDays(1)
|
|
223
|
+
.toISODate();
|
|
224
|
+
}
|
|
225
|
+
return date;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* The preferred number if it fits the schema, else the preferred number rounded to the step,
|
|
229
|
+
* else the first number that fits from the lower bound up, or from the upper bound down.
|
|
230
|
+
*/
|
|
231
|
+
function generateNumber(node, path) {
|
|
232
|
+
const step = getStep(node);
|
|
233
|
+
const preferred = getPreferredNumber(node);
|
|
234
|
+
const candidates = [preferred, ...roundToStep(preferred, step), ...getBoundCandidates(node, step)];
|
|
235
|
+
const value = candidates.find(candidate => fitsNumberSchema(node, candidate, step));
|
|
236
|
+
if (value === undefined) {
|
|
237
|
+
throw cannotGenerate(path, 'no number satisfies the bounds of the schema');
|
|
238
|
+
}
|
|
239
|
+
// Turns -0 into 0
|
|
240
|
+
return value + 0;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* `multipleOf`, or 1 for an integer. For an integer with a fractional `multipleOf`,
|
|
244
|
+
* the smallest whole multiple of it, e.g 2 for 0.4.
|
|
245
|
+
*/
|
|
246
|
+
function getStep(node) {
|
|
247
|
+
const { multipleOf } = node;
|
|
248
|
+
if (node.type !== 'integer')
|
|
249
|
+
return multipleOf;
|
|
250
|
+
if (!multipleOf)
|
|
251
|
+
return 1;
|
|
252
|
+
// With `multipleOf` as a fraction `scaled / scale`, the whole multiple is `scaled / gcd`
|
|
253
|
+
const scale = getDecimalScale(multipleOf);
|
|
254
|
+
const scaled = Math.round(multipleOf * scale);
|
|
255
|
+
return scaled / getGreatestCommonDivisor(scaled, scale);
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* The power of 10 that makes the number whole, e.g 100 for 0.25.
|
|
259
|
+
* Stops at 10^15, the precision of a number, e.g for 1/3.
|
|
260
|
+
*/
|
|
261
|
+
function getDecimalScale(value) {
|
|
262
|
+
let scale = 1;
|
|
263
|
+
while (Math.abs(value * scale - Math.round(value * scale)) > 1e-9 && scale < 1e15)
|
|
264
|
+
scale *= 10;
|
|
265
|
+
return scale;
|
|
266
|
+
}
|
|
267
|
+
function getGreatestCommonDivisor(a, b) {
|
|
268
|
+
if (!b)
|
|
269
|
+
return a;
|
|
270
|
+
return getGreatestCommonDivisor(b, a % b);
|
|
271
|
+
}
|
|
272
|
+
function getPreferredNumber(node) {
|
|
273
|
+
if (node.format === 'UnixTimestamp')
|
|
274
|
+
return MOCK_UNIX_TIMESTAMP;
|
|
275
|
+
if (node.format === 'UnixTimestampMillis')
|
|
276
|
+
return MOCK_UNIX_TIMESTAMP * 1000;
|
|
277
|
+
return 1;
|
|
278
|
+
}
|
|
279
|
+
function roundToStep(value, step) {
|
|
280
|
+
if (!step)
|
|
281
|
+
return [];
|
|
282
|
+
return [Math.ceil(value / step) * step, Math.floor(value / step) * step];
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* The first numbers at or inside the lower bound, or else the upper bound: with a step, the first
|
|
286
|
+
* two multiples, without one the bound itself, the midpoint between the bounds, and the bound + 1.
|
|
287
|
+
*/
|
|
288
|
+
function getBoundCandidates(node, step) {
|
|
289
|
+
const lower = getTightestBound([node.minimum, node.exclusiveMinimum], Math.max);
|
|
290
|
+
const upper = getTightestBound([node.maximum, node.exclusiveMaximum], Math.min);
|
|
291
|
+
if (lower !== undefined && step) {
|
|
292
|
+
const first = Math.ceil(lower / step) * step;
|
|
293
|
+
return [first, first + step];
|
|
294
|
+
}
|
|
295
|
+
if (lower !== undefined) {
|
|
296
|
+
const midpoint = upper === undefined ? lower : lower + (upper - lower) / 2;
|
|
297
|
+
return [lower, midpoint, lower + 1];
|
|
298
|
+
}
|
|
299
|
+
if (upper !== undefined && step) {
|
|
300
|
+
const last = Math.floor(upper / step) * step;
|
|
301
|
+
return [last, last - step];
|
|
302
|
+
}
|
|
303
|
+
if (upper !== undefined)
|
|
304
|
+
return [upper, upper - 1];
|
|
305
|
+
return [];
|
|
306
|
+
}
|
|
307
|
+
function getTightestBound(bounds, pick) {
|
|
308
|
+
const definedBounds = bounds.filter(bound => bound !== undefined);
|
|
309
|
+
if (!definedBounds.length)
|
|
310
|
+
return;
|
|
311
|
+
return pick(...definedBounds);
|
|
312
|
+
}
|
|
313
|
+
function fitsNumberSchema(node, value, step) {
|
|
314
|
+
if (node.minimum !== undefined && value < node.minimum)
|
|
315
|
+
return false;
|
|
316
|
+
if (node.exclusiveMinimum !== undefined && value <= node.exclusiveMinimum)
|
|
317
|
+
return false;
|
|
318
|
+
if (node.maximum !== undefined && value > node.maximum)
|
|
319
|
+
return false;
|
|
320
|
+
if (node.exclusiveMaximum !== undefined && value >= node.exclusiveMaximum)
|
|
321
|
+
return false;
|
|
322
|
+
if (node.multipleOf && !Number.isInteger(value / node.multipleOf))
|
|
323
|
+
return false;
|
|
324
|
+
if (step && !Number.isInteger(value / step))
|
|
325
|
+
return false;
|
|
326
|
+
if (node.type === 'integer' && !Number.isInteger(value))
|
|
327
|
+
return false;
|
|
328
|
+
return true;
|
|
329
|
+
}
|
|
330
|
+
function generateArray(node, path, ctx) {
|
|
331
|
+
if (node.prefixItems) {
|
|
332
|
+
return node.prefixItems.map(item => generateValue(item, path, ctx));
|
|
333
|
+
}
|
|
334
|
+
if (!node.items)
|
|
335
|
+
return [];
|
|
336
|
+
return generateList(node, node.items, path, ctx);
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* `minItems` items, at least one with `allFields`, at most `maxItems`.
|
|
340
|
+
*/
|
|
341
|
+
function generateList(node, itemSchema, path, ctx) {
|
|
342
|
+
const minCount = Math.max(node.minItems || 0, ctx.opt.allFields ? 1 : 0);
|
|
343
|
+
const count = _clamp(minCount, 0, node.maxItems ?? minCount);
|
|
344
|
+
if (count > 1 && (node.Set2 || node.uniqueItems)) {
|
|
345
|
+
throw cannotGenerate(path, `a list of ${count} distinct items needs an example, .example([...])`);
|
|
346
|
+
}
|
|
347
|
+
// The items share the path of the list: they come from the same schema
|
|
348
|
+
return Array.from({ length: count }, () => generateValue(itemSchema, path, ctx));
|
|
349
|
+
}
|
|
350
|
+
function generateObject(node, path, ctx) {
|
|
351
|
+
const keys = selectPropertyKeys(node, path, ctx);
|
|
352
|
+
const properties = node.properties || {};
|
|
353
|
+
const result = {};
|
|
354
|
+
for (const key of keys) {
|
|
355
|
+
const value = generateValue(properties[key], joinPath(path, key), ctx);
|
|
356
|
+
if (value !== undefined)
|
|
357
|
+
result[key] = value;
|
|
358
|
+
}
|
|
359
|
+
const shouldFillMaps = ctx.opt.allFields || keys.length < (node.minProperties || 0);
|
|
360
|
+
const hasRoomForMaps = keys.length < (node.maxProperties ?? Infinity);
|
|
361
|
+
if (!shouldFillMaps || !hasRoomForMaps)
|
|
362
|
+
return result;
|
|
363
|
+
const missingCount = (node.minProperties || 0) - keys.length;
|
|
364
|
+
if (missingCount > 1) {
|
|
365
|
+
throw cannotGenerate(path, `a map of ${missingCount} keys needs an example, .example({...})`);
|
|
366
|
+
}
|
|
367
|
+
for (const [pattern, valueSchema] of _stringMapEntries(node.patternProperties || {})) {
|
|
368
|
+
const key = generateKey(node, path, ctx);
|
|
369
|
+
if (key === undefined) {
|
|
370
|
+
throw cannotGenerate(path, `a map with keys matching ${pattern} needs an example, .example({...})`);
|
|
371
|
+
}
|
|
372
|
+
assertKeyIsFree(node, result, key, path);
|
|
373
|
+
result[key] = generateValue(valueSchema, joinPath(path, key), ctx);
|
|
374
|
+
}
|
|
375
|
+
if (typeof node.additionalProperties === 'object') {
|
|
376
|
+
const key = generateKey(node, path, ctx) ?? findFreeKey(node, result);
|
|
377
|
+
assertKeyIsFree(node, result, key, path);
|
|
378
|
+
result[key] = generateValue(node.additionalProperties, joinPath(path, key), ctx);
|
|
379
|
+
}
|
|
380
|
+
return result;
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* `key`, or else `key1`, `key2` and so on, whichever the object does not have yet.
|
|
384
|
+
*/
|
|
385
|
+
function findFreeKey(node, result) {
|
|
386
|
+
let key = 'key';
|
|
387
|
+
for (let index = 1; isKeyTaken(node, result, key); index++)
|
|
388
|
+
key = `key${index}`;
|
|
389
|
+
return key;
|
|
390
|
+
}
|
|
391
|
+
function assertKeyIsFree(node, result, key, path) {
|
|
392
|
+
if (isKeyTaken(node, result, key)) {
|
|
393
|
+
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({...})`);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
function isKeyTaken(node, result, key) {
|
|
397
|
+
return Object.hasOwn(node.properties || {}, key) || Object.hasOwn(result, key);
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* The required keys, or every key with `allFields`, plus optional keys until `minProperties`
|
|
401
|
+
* is reached, and at most `maxProperties` keys. Only one key of each group of exclusive properties
|
|
402
|
+
* is kept. The keys keep the order of the schema.
|
|
403
|
+
*/
|
|
404
|
+
function selectPropertyKeys(node, path, ctx) {
|
|
405
|
+
const required = node.required || [];
|
|
406
|
+
const excludedKeys = new Set((node.exclusiveProperties || []).flatMap(group => {
|
|
407
|
+
const keptKey = chooseExclusiveKey(group, required, path, ctx);
|
|
408
|
+
return group.filter(key => key !== keptKey);
|
|
409
|
+
}));
|
|
410
|
+
const candidateKeys = Object.keys(node.properties || {}).filter(key => !excludedKeys.has(key));
|
|
411
|
+
const requiredKeys = candidateKeys.filter(key => required.includes(key));
|
|
412
|
+
const optionalKeys = candidateKeys.filter(key => !required.includes(key));
|
|
413
|
+
const minCount = ctx.opt.allFields
|
|
414
|
+
? candidateKeys.length
|
|
415
|
+
: Math.max(requiredKeys.length, node.minProperties || 0);
|
|
416
|
+
const count = _clamp(minCount, 0, node.maxProperties ?? minCount);
|
|
417
|
+
const keptOptionalKeys = new Set(optionalKeys.slice(0, Math.max(0, count - requiredKeys.length)));
|
|
418
|
+
return candidateKeys.filter(key => required.includes(key) || keptOptionalKeys.has(key));
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* The required key of the group, or else the key listed for the group in `ctx.choices`,
|
|
422
|
+
* or else the first.
|
|
423
|
+
*/
|
|
424
|
+
function chooseExclusiveKey(group, required, path, ctx) {
|
|
425
|
+
const requiredKey = group.find(key => required.includes(key));
|
|
426
|
+
if (requiredKey)
|
|
427
|
+
return requiredKey;
|
|
428
|
+
ctx.reachedChoices.push({ point: group, path, options: group.map(key => ({ key })) });
|
|
429
|
+
return group[ctx.choices.get(group) ?? 0];
|
|
430
|
+
}
|
|
431
|
+
function generateKey(node, path, ctx) {
|
|
432
|
+
if (!node.keySchema)
|
|
433
|
+
return;
|
|
434
|
+
return String(generateValue(node.keySchema, joinPath(path, '<key>'), ctx));
|
|
435
|
+
}
|
|
436
|
+
function cannotGenerate(path, reason) {
|
|
437
|
+
return new Error(`Cannot generate a value at ${path || '(root)'}: ${reason}`);
|
|
438
|
+
}
|
|
439
|
+
function joinPath(path, segment) {
|
|
440
|
+
if (!path)
|
|
441
|
+
return segment;
|
|
442
|
+
return `${path}.${segment}`;
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Whether the generator supports each keyword. A schema with an unsupported or unknown keyword
|
|
446
|
+
* throws, so the generator does not silently produce a wrong value.
|
|
447
|
+
*/
|
|
448
|
+
const SUPPORTED_KEYWORDS = {
|
|
449
|
+
// Values
|
|
450
|
+
type: true,
|
|
451
|
+
default: true,
|
|
452
|
+
examples: true,
|
|
453
|
+
enum: true,
|
|
454
|
+
// Unions
|
|
455
|
+
anyOf: true,
|
|
456
|
+
oneOf: true,
|
|
457
|
+
anyOfThese: true,
|
|
458
|
+
anyOfBy: true,
|
|
459
|
+
ifDefined: true,
|
|
460
|
+
isUndefined: true,
|
|
461
|
+
// Strings
|
|
462
|
+
pattern: true,
|
|
463
|
+
minLength: true,
|
|
464
|
+
maxLength: true,
|
|
465
|
+
format: true,
|
|
466
|
+
email: true,
|
|
467
|
+
IsoDate: true,
|
|
468
|
+
IsoDateTime: true,
|
|
469
|
+
IsoMonth: true,
|
|
470
|
+
UtcOffset: true,
|
|
471
|
+
// Numbers
|
|
472
|
+
minimum: true,
|
|
473
|
+
exclusiveMinimum: true,
|
|
474
|
+
maximum: true,
|
|
475
|
+
exclusiveMaximum: true,
|
|
476
|
+
multipleOf: true,
|
|
477
|
+
precision: true,
|
|
478
|
+
// Arrays and sets
|
|
479
|
+
items: true,
|
|
480
|
+
prefixItems: true,
|
|
481
|
+
minItems: true,
|
|
482
|
+
maxItems: true,
|
|
483
|
+
uniqueItems: true,
|
|
484
|
+
Set2: true,
|
|
485
|
+
// Objects
|
|
486
|
+
properties: true,
|
|
487
|
+
required: true,
|
|
488
|
+
patternProperties: true,
|
|
489
|
+
additionalProperties: true,
|
|
490
|
+
keySchema: true,
|
|
491
|
+
minProperties: true,
|
|
492
|
+
minProperties2: true,
|
|
493
|
+
maxProperties: true,
|
|
494
|
+
exclusiveProperties: true,
|
|
495
|
+
instanceof: true,
|
|
496
|
+
Buffer: true,
|
|
497
|
+
// Annotations, and rules that the validation at the end checks
|
|
498
|
+
$schema: true,
|
|
499
|
+
$id: true,
|
|
500
|
+
title: true,
|
|
501
|
+
description: true,
|
|
502
|
+
deprecated: true,
|
|
503
|
+
readOnly: true,
|
|
504
|
+
writeOnly: true,
|
|
505
|
+
hasIsOfTypeCheck: true,
|
|
506
|
+
errorMessages: true,
|
|
507
|
+
enumNames: true,
|
|
508
|
+
enumKeys: true,
|
|
509
|
+
transform: true,
|
|
510
|
+
optionalValues: true,
|
|
511
|
+
customValidations: true,
|
|
512
|
+
customConversions: true,
|
|
513
|
+
postValidation: true,
|
|
514
|
+
// Not built by `j`
|
|
515
|
+
if: false,
|
|
516
|
+
// oxlint-disable-next-line unicorn/no-thenable -- a JSON Schema keyword, the object is never awaited
|
|
517
|
+
then: false,
|
|
518
|
+
else: false,
|
|
519
|
+
contentMediaType: false,
|
|
520
|
+
contentEncoding: false,
|
|
521
|
+
// Type-only and parser-only fields, never in a built schema
|
|
522
|
+
out: false,
|
|
523
|
+
optionalField: false,
|
|
524
|
+
};
|
package/package.json
CHANGED
|
@@ -391,6 +391,12 @@ export function createAjv(opt?: Options): Ajv2020 {
|
|
|
391
391
|
schemaType: 'array',
|
|
392
392
|
})
|
|
393
393
|
|
|
394
|
+
// Annotation only (the keys are validated by `properties`), registered so strict mode doesn't reject it
|
|
395
|
+
ajv.addKeyword({
|
|
396
|
+
keyword: 'enumKeys',
|
|
397
|
+
schemaType: 'object',
|
|
398
|
+
})
|
|
399
|
+
|
|
394
400
|
// Annotation only (validated by the custom keywords, e.g `IsoDate`).
|
|
395
401
|
// `true` makes Ajv skip the format check, while unknown formats would throw in strict mode.
|
|
396
402
|
for (const format of jFormats) {
|
|
@@ -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 }
|