@naturalcycles/nodejs-lib 15.144.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.
@@ -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
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@naturalcycles/nodejs-lib",
3
3
  "type": "module",
4
- "version": "15.144.0",
4
+ "version": "15.145.0",
5
5
  "dependencies": {
6
6
  "@naturalcycles/js-lib": "^15",
7
7
  "@standard-schema/spec": "^1",
@@ -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, { msg: 'is not a valid 4-part semver format' })
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, { msg: 'is not a valid language format' })
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, { msg: 'is not a valid country code format' })
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, { msg: 'is not a valid currency format' })
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?: OUT
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
@@ -13,6 +13,7 @@ export const JSON_SCHEMA_ORDER: readonly string[] = [
13
13
  'writeOnly',
14
14
  'type',
15
15
  'default',
16
+ 'examples',
16
17
  // Object,
17
18
  'properties',
18
19
  'required',