@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.
@@ -0,0 +1,650 @@
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 type { AnyObject, IsoDate, StringMap, UnixTimestamp } from '@naturalcycles/js-lib/types'
5
+ import { _stringMapEntries } from '@naturalcycles/js-lib/types'
6
+ import type { JSchema, JsonSchema, JsonSchemaIsoDateOptions } from '../jSchema.js'
7
+
8
+ /**
9
+ * Generates a value that passes the schema, e.g for a mock in a test.
10
+ * Uses the example or default of a field when it has one, except an empty list or object as default.
11
+ * A string with a pattern needs an example or a default.
12
+ *
13
+ * ```
14
+ * const account = generateMockFromSchema(accountSchema, { allFields: true })
15
+ * ```
16
+ *
17
+ * @experimental
18
+ */
19
+ export function generateMockFromSchema<OUT>(
20
+ schema: JSchema<OUT, any>,
21
+ opt: GenerateMockFromSchemaOptions = {},
22
+ ): OUT {
23
+ const value = generateValue(schema.build(), '', { opt, choices: new Map(), reachedChoices: [] })
24
+ return schema.validate(value)
25
+ }
26
+
27
+ /**
28
+ * Generates the mock of `generateMockFromSchema` with `allFields`, plus one variant for each other
29
+ * branch of each `j.anyOfThese` and `j.anyOfBy` union, and for each other property of each group
30
+ * of exclusive properties, so every field appears in some variant.
31
+ * `j.anyOf` and `j.oneOf` always take their first branch, since their branches add no fields.
32
+ * With `maxProperties`, only the first fields up to the limit appear,
33
+ * e.g `b` never appears for `{ a?, b? }.maxProperties(1)`. With overlapping groups of exclusive
34
+ * properties, a property shared by two groups may not appear. When an earlier `j.anyOfThese` branch
35
+ * also matches a later branch's value, validation drops the later branch's extra fields, so put the
36
+ * wider branch first.
37
+ *
38
+ * ```
39
+ * const variants = generateMockVariantsFromSchema(accountSchema)
40
+ * // [{ value }, { value, choice: { path: 'address.taxId', option: 1, key: 'mx_rfc' } }]
41
+ * ```
42
+ *
43
+ * @experimental
44
+ */
45
+ export function generateMockVariantsFromSchema<OUT>(schema: JSchema<OUT, any>): MockVariant<OUT>[] {
46
+ // Built once, so a choice is the same object in every run
47
+ const root = schema.build()
48
+ const queue: QueuedVariant[] = [{ choices: new Map() }]
49
+ const seenChoices = new Set<ChoicePoint>()
50
+ const variants: MockVariant<OUT>[] = []
51
+
52
+ for (const { choices, choice } of queue) {
53
+ const ctx: GenerationContext = { opt: { allFields: true }, choices, reachedChoices: [] }
54
+ const value = generateValue(root, '', ctx)
55
+ variants.push({ value: schema.validate(value), ...(choice && { choice }) })
56
+
57
+ for (const { point, path, options } of ctx.reachedChoices) {
58
+ if (seenChoices.has(point)) continue
59
+ seenChoices.add(point)
60
+ for (let option = 1; option < options.length; option++) {
61
+ const { key } = options[option]!
62
+ queue.push({
63
+ choices: new Map(choices).set(point, option),
64
+ choice: { path, option, ...(key !== undefined && { key }) },
65
+ })
66
+ }
67
+ }
68
+ }
69
+
70
+ return variants
71
+ }
72
+
73
+ const MOCK_UNIX_TIMESTAMP = 1_655_287_200 as UnixTimestamp // 2022-06-15T10:00:00Z
74
+ const MOCK_ISO_DATE = '2022-06-15'
75
+
76
+ function generateValue(node: JsonSchema, path: string, ctx: GenerationContext): any {
77
+ assertSupportedKeywords(node, path)
78
+ const value = generateValueFromKeywords(node, path, ctx)
79
+ if (node.optionalValues?.includes(value)) {
80
+ throw cannotGenerate(
81
+ path,
82
+ `the generated value ${JSON.stringify(value)} would be removed by optionalValues, give the field an example`,
83
+ )
84
+ }
85
+ return value
86
+ }
87
+
88
+ function generateValueFromKeywords(node: JsonSchema, path: string, ctx: GenerationContext): any {
89
+ if (node.examples?.length) return copyPlainValue(node.examples[0])
90
+ // An empty list or object as the default would leave nothing to show, e.g with `allFields`
91
+ if (node.default !== undefined && !isEmptyCollection(node.default)) {
92
+ return copyPlainValue(node.default)
93
+ }
94
+ if (node.isUndefined) return undefined
95
+ if (node.enum) return node.enum[0]
96
+ if (node.ifDefined) return generateValue(node.ifDefined, path, ctx)
97
+
98
+ if (node.anyOfThese || node.anyOfBy) return generateFieldUnion(node, path, ctx)
99
+ const branches = [...(node.anyOf || []), ...(node.oneOf || [])]
100
+ if (branches.length) {
101
+ return generateValue(branches.find(isNonNullBranch) || branches[0]!, path, ctx)
102
+ }
103
+
104
+ if (node.instanceof === 'Date') return localTime.fromUnix(MOCK_UNIX_TIMESTAMP).toDate()
105
+ if (node.instanceof) {
106
+ throw cannotGenerate(path, `cannot create an instance of ${node.instanceof}`)
107
+ }
108
+ if (node.Buffer) return Buffer.from('mock')
109
+ if (node.Set2) return new Set2(generateList(node, node.Set2, path, ctx))
110
+
111
+ if (node.type === 'string') return generateString(node, path)
112
+ if (node.type === 'number' || node.type === 'integer') return generateNumber(node, path)
113
+ if (node.type === 'boolean') return true
114
+ if (node.type === 'null') return null
115
+ if (node.type === 'array') return generateArray(node, path, ctx)
116
+ if (node.type === 'object') return generateObject(node, path, ctx)
117
+ // A schema without a type, e.g `j.any()`, accepts any value
118
+ return 'mock'
119
+ }
120
+
121
+ function assertSupportedKeywords(node: JsonSchema, path: string): void {
122
+ for (const keyword of Object.keys(node)) {
123
+ if (!SUPPORTED_KEYWORDS[keyword as keyof JsonSchema]) {
124
+ throw cannotGenerate(path, `the keyword ${keyword} is not supported`)
125
+ }
126
+ }
127
+ }
128
+
129
+ function isEmptyCollection(value: unknown): boolean {
130
+ if (Array.isArray(value)) return !value.length
131
+ return _isPlainObject(value) && !Object.keys(value).length
132
+ }
133
+
134
+ /**
135
+ * Copies plain objects, arrays and sets, so a variant does not share them with the schema
136
+ * or with other variants.
137
+ */
138
+ function copyPlainValue(value: any): any {
139
+ if (Array.isArray(value)) return value.map(copyPlainValue)
140
+ if (value instanceof Set2) return new Set2(Array.from(value, copyPlainValue))
141
+ if (!_isPlainObject(value)) return value
142
+ return _mapValues(value, (_, item) => copyPlainValue(item))
143
+ }
144
+
145
+ /**
146
+ * Generates one branch of the union: the branch listed for it in `ctx.choices`, or else the first.
147
+ */
148
+ function generateFieldUnion(node: JsonSchema, path: string, ctx: GenerationContext): any {
149
+ const branches = getUnionBranches(node).filter(branch => isNonNullBranch(branch.schema))
150
+ if (!branches.length) throw cannotGenerate(path, 'the union has no branch that is not null')
151
+ ctx.reachedChoices.push({ point: node, path, options: branches })
152
+
153
+ const { key, schema } = branches[ctx.choices.get(node) ?? 0]!
154
+ const value = generateValue(schema, path, ctx)
155
+ if (!node.anyOfBy) return value
156
+
157
+ const { propertyName } = node.anyOfBy
158
+ const properties: StringMap<JsonSchema> = schema.properties || {}
159
+ return { ...value, [propertyName]: toPropertyValue(key!, properties[propertyName]) }
160
+ }
161
+
162
+ function getUnionBranches(node: JsonSchema): UnionBranch[] {
163
+ if (node.anyOfBy) {
164
+ return _stringMapEntries(node.anyOfBy.schemaDictionary).map(([key, schema]) => ({
165
+ key,
166
+ schema,
167
+ }))
168
+ }
169
+ return (node.anyOfThese || []).map(schema => ({ schema }))
170
+ }
171
+
172
+ /**
173
+ * Dictionary keys are strings, while the property can be e.g a number enum.
174
+ * A nullable or optional property wraps its schema, e.g in `anyOf`, so those are searched too.
175
+ */
176
+ function toPropertyValue(key: string, propertySchema: JsonSchema | undefined): unknown {
177
+ const schemas = [
178
+ propertySchema,
179
+ ...(propertySchema?.anyOf || []),
180
+ ...(propertySchema?.oneOf || []),
181
+ propertySchema?.ifDefined,
182
+ ].filter(schema => schema !== undefined)
183
+ const enumValue = schemas
184
+ .flatMap(schema => schema.enum || [])
185
+ .find((value: unknown) => String(value) === key)
186
+ if (enumValue !== undefined) return enumValue
187
+ const types = new Set(schemas.map(schema => schema.type))
188
+ if (types.has('number') || types.has('integer')) return Number(key)
189
+ if (types.has('boolean')) return key === 'true'
190
+ return key
191
+ }
192
+
193
+ function isNonNullBranch(branch: JsonSchema): boolean {
194
+ if (branch.type === 'null' || branch.isUndefined) return false
195
+ // `j.literal(null)` builds `{ enum: [null] }`
196
+ return !(branch.enum?.length === 1 && branch.enum[0] === null)
197
+ }
198
+
199
+ function generateString(node: JsonSchema, path: string): string {
200
+ if (node.IsoDate) return generateIsoDate(node.IsoDate)
201
+ if (node.IsoDateTime) return `${MOCK_ISO_DATE}T10:00:00Z`
202
+ if (node.IsoMonth) return MOCK_ISO_DATE.slice(0, 7)
203
+ if (node.UtcOffset) return '+02:00'
204
+ if (node.email) return 'mock@example.com'
205
+ if (node.pattern) {
206
+ throw cannotGenerate(path, 'a string with a pattern needs an example, .example(...)')
207
+ }
208
+
209
+ const value = 'mock'.padEnd(node.minLength || 0, 'x')
210
+ return value.slice(0, node.maxLength ?? value.length)
211
+ }
212
+
213
+ /**
214
+ * ISO dates sort as strings, so the bounds are compared as strings.
215
+ */
216
+ function generateIsoDate(bounds: JsonSchemaIsoDateOptions): string {
217
+ const { sameOrAfter, after, sameOrBefore, before } = bounds
218
+ let date: string = MOCK_ISO_DATE
219
+ if (sameOrAfter && date < sameOrAfter) date = sameOrAfter
220
+ if (after && date <= after) {
221
+ date = localDate(after as IsoDate)
222
+ .plusDays(1)
223
+ .toISODate()
224
+ }
225
+ if (sameOrBefore && date > sameOrBefore) date = sameOrBefore
226
+ if (before && date >= before) {
227
+ date = localDate(before as IsoDate)
228
+ .minusDays(1)
229
+ .toISODate()
230
+ }
231
+ return date
232
+ }
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: JsonSchema, path: string): number {
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
+ /**
251
+ * `multipleOf`, or 1 for an integer. For an integer with a fractional `multipleOf`,
252
+ * the smallest whole multiple of it, e.g 2 for 0.4.
253
+ */
254
+ function getStep(node: JsonSchema): number | undefined {
255
+ const { multipleOf } = node
256
+ if (node.type !== 'integer') return multipleOf
257
+ if (!multipleOf) return 1
258
+ // With `multipleOf` as a fraction `scaled / scale`, the whole multiple is `scaled / gcd`
259
+ const scale = getDecimalScale(multipleOf)
260
+ const scaled = Math.round(multipleOf * scale)
261
+ return scaled / getGreatestCommonDivisor(scaled, scale)
262
+ }
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: number): number {
269
+ let scale = 1
270
+ while (Math.abs(value * scale - Math.round(value * scale)) > 1e-9 && scale < 1e15) scale *= 10
271
+ return scale
272
+ }
273
+
274
+ function getGreatestCommonDivisor(a: number, b: number): number {
275
+ if (!b) return a
276
+ return getGreatestCommonDivisor(b, a % b)
277
+ }
278
+
279
+ function getPreferredNumber(node: JsonSchema): number {
280
+ if (node.format === 'UnixTimestamp') return MOCK_UNIX_TIMESTAMP
281
+ if (node.format === 'UnixTimestampMillis') return MOCK_UNIX_TIMESTAMP * 1000
282
+ return 1
283
+ }
284
+
285
+ function roundToStep(value: number, step: number | undefined): number[] {
286
+ if (!step) return []
287
+ return [Math.ceil(value / step) * step, Math.floor(value / step) * step]
288
+ }
289
+
290
+ /**
291
+ * The first numbers at or inside the lower bound, or else the upper bound: with a step, the first
292
+ * two multiples, without one the bound itself, the midpoint between the bounds, and the bound + 1.
293
+ */
294
+ function getBoundCandidates(node: JsonSchema, step: number | undefined): number[] {
295
+ const lower = getTightestBound([node.minimum, node.exclusiveMinimum], Math.max)
296
+ const upper = getTightestBound([node.maximum, node.exclusiveMaximum], Math.min)
297
+
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) return [upper, upper - 1]
311
+ return []
312
+ }
313
+
314
+ function getTightestBound(
315
+ bounds: (number | undefined)[],
316
+ pick: (...values: number[]) => number,
317
+ ): number | undefined {
318
+ const definedBounds = bounds.filter(bound => bound !== undefined)
319
+ if (!definedBounds.length) return
320
+ return pick(...definedBounds)
321
+ }
322
+
323
+ function fitsNumberSchema(node: JsonSchema, value: number, step: number | undefined): boolean {
324
+ if (node.minimum !== undefined && value < node.minimum) return false
325
+ if (node.exclusiveMinimum !== undefined && value <= node.exclusiveMinimum) return false
326
+ if (node.maximum !== undefined && value > node.maximum) return false
327
+ if (node.exclusiveMaximum !== undefined && value >= node.exclusiveMaximum) return false
328
+ if (node.multipleOf && !Number.isInteger(value / node.multipleOf)) return false
329
+ if (step && !Number.isInteger(value / step)) return false
330
+ if (node.type === 'integer' && !Number.isInteger(value)) return false
331
+ return true
332
+ }
333
+
334
+ function generateArray(node: JsonSchema, path: string, ctx: GenerationContext): any[] {
335
+ if (node.prefixItems) {
336
+ return node.prefixItems.map(item => generateValue(item, path, ctx))
337
+ }
338
+ if (!node.items) return []
339
+ return generateList(node, node.items, path, ctx)
340
+ }
341
+
342
+ /**
343
+ * `minItems` items, at least one with `allFields`, at most `maxItems`.
344
+ */
345
+ function generateList(
346
+ node: JsonSchema,
347
+ itemSchema: JsonSchema,
348
+ path: string,
349
+ ctx: GenerationContext,
350
+ ): any[] {
351
+ const minCount = Math.max(node.minItems || 0, ctx.opt.allFields ? 1 : 0)
352
+ const count = _clamp(minCount, 0, node.maxItems ?? minCount)
353
+
354
+ if (count > 1 && (node.Set2 || node.uniqueItems)) {
355
+ throw cannotGenerate(
356
+ path,
357
+ `a list of ${count} distinct items needs an example, .example([...])`,
358
+ )
359
+ }
360
+
361
+ // The items share the path of the list: they come from the same schema
362
+ return Array.from({ length: count }, () => generateValue(itemSchema, path, ctx))
363
+ }
364
+
365
+ function generateObject(node: JsonSchema, path: string, ctx: GenerationContext): AnyObject {
366
+ const keys = selectPropertyKeys(node, path, ctx)
367
+ const properties: StringMap<JsonSchema> = node.properties || {}
368
+ const result: AnyObject = {}
369
+
370
+ for (const key of keys) {
371
+ const value = generateValue(properties[key]!, joinPath(path, key), ctx)
372
+ if (value !== undefined) result[key] = value
373
+ }
374
+
375
+ const shouldFillMaps = ctx.opt.allFields || keys.length < (node.minProperties || 0)
376
+ const hasRoomForMaps = keys.length < (node.maxProperties ?? Infinity)
377
+ if (!shouldFillMaps || !hasRoomForMaps) return result
378
+
379
+ const missingCount = (node.minProperties || 0) - keys.length
380
+ if (missingCount > 1) {
381
+ throw cannotGenerate(path, `a map of ${missingCount} keys needs an example, .example({...})`)
382
+ }
383
+
384
+ for (const [pattern, valueSchema] of _stringMapEntries(node.patternProperties || {})) {
385
+ const key = generateKey(node, path, ctx)
386
+ if (key === undefined) {
387
+ throw cannotGenerate(
388
+ path,
389
+ `a map with keys matching ${pattern} needs an example, .example({...})`,
390
+ )
391
+ }
392
+ assertKeyIsFree(node, result, key, path)
393
+ result[key] = generateValue(valueSchema, joinPath(path, key), ctx)
394
+ }
395
+ if (typeof node.additionalProperties === 'object') {
396
+ const key = generateKey(node, path, ctx) ?? findFreeKey(node, result)
397
+ assertKeyIsFree(node, result, key, path)
398
+ result[key] = generateValue(node.additionalProperties, joinPath(path, key), ctx)
399
+ }
400
+ // An object of any shape, e.g `j.object.any()`, gets one entry like a map
401
+ if (node.additionalProperties === true && !Object.keys(properties).length) {
402
+ result['key'] = 'mock'
403
+ }
404
+
405
+ return result
406
+ }
407
+
408
+ /**
409
+ * `key`, or else `key1`, `key2` and so on, whichever the object does not have yet.
410
+ */
411
+ function findFreeKey(node: JsonSchema, result: AnyObject): string {
412
+ let key = 'key'
413
+ for (let index = 1; isKeyTaken(node, result, key); index++) key = `key${index}`
414
+ return key
415
+ }
416
+
417
+ function assertKeyIsFree(node: JsonSchema, result: AnyObject, key: string, path: string): void {
418
+ if (isKeyTaken(node, result, key)) {
419
+ throw cannotGenerate(
420
+ joinPath(path, key),
421
+ `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({...})`,
422
+ )
423
+ }
424
+ }
425
+
426
+ function isKeyTaken(node: JsonSchema, result: AnyObject, key: string): boolean {
427
+ return Object.hasOwn(node.properties || {}, key) || Object.hasOwn(result, key)
428
+ }
429
+
430
+ /**
431
+ * The required keys, or every key with `allFields`, plus optional keys until `minProperties`
432
+ * is reached, and at most `maxProperties` keys. Only one key of each group of exclusive properties
433
+ * is kept. The keys keep the order of the schema.
434
+ */
435
+ function selectPropertyKeys(node: JsonSchema, path: string, ctx: GenerationContext): string[] {
436
+ const required = node.required || []
437
+ const excludedKeys = new Set(
438
+ (node.exclusiveProperties || []).flatMap(group => {
439
+ const keptKey = chooseExclusiveKey(group, required, path, ctx)
440
+ return group.filter(key => key !== keptKey)
441
+ }),
442
+ )
443
+ const candidateKeys = Object.keys(node.properties || {}).filter(key => !excludedKeys.has(key))
444
+ const requiredKeys = candidateKeys.filter(key => required.includes(key))
445
+ const optionalKeys = candidateKeys.filter(key => !required.includes(key))
446
+
447
+ const minCount = ctx.opt.allFields
448
+ ? candidateKeys.length
449
+ : Math.max(requiredKeys.length, node.minProperties || 0)
450
+ const count = _clamp(minCount, 0, node.maxProperties ?? minCount)
451
+
452
+ const keptOptionalKeys = new Set(optionalKeys.slice(0, Math.max(0, count - requiredKeys.length)))
453
+ return candidateKeys.filter(key => required.includes(key) || keptOptionalKeys.has(key))
454
+ }
455
+
456
+ /**
457
+ * The required key of the group, or else the key listed for the group in `ctx.choices`,
458
+ * or else the first.
459
+ */
460
+ function chooseExclusiveKey(
461
+ group: readonly string[],
462
+ required: string[],
463
+ path: string,
464
+ ctx: GenerationContext,
465
+ ): string {
466
+ const requiredKey = group.find(key => required.includes(key))
467
+ if (requiredKey) return requiredKey
468
+ ctx.reachedChoices.push({ point: group, path, options: group.map(key => ({ key })) })
469
+ return group[ctx.choices.get(group) ?? 0]!
470
+ }
471
+
472
+ function generateKey(node: JsonSchema, path: string, ctx: GenerationContext): string | undefined {
473
+ if (!node.keySchema) return
474
+ return String(generateValue(node.keySchema, joinPath(path, '<key>'), ctx))
475
+ }
476
+
477
+ function cannotGenerate(path: string, reason: string): Error {
478
+ return new Error(`Cannot generate a value at ${path || '(root)'}: ${reason}`)
479
+ }
480
+
481
+ function joinPath(path: string, segment: string): string {
482
+ if (!path) return segment
483
+ return `${path}.${segment}`
484
+ }
485
+
486
+ /**
487
+ * Whether the generator supports each keyword. A schema with an unsupported or unknown keyword
488
+ * throws, so the generator does not silently produce a wrong value.
489
+ */
490
+ const SUPPORTED_KEYWORDS: Record<keyof JsonSchema, boolean> = {
491
+ // Values
492
+ type: true,
493
+ default: true,
494
+ examples: true,
495
+ enum: true,
496
+ // Unions
497
+ anyOf: true,
498
+ oneOf: true,
499
+ anyOfThese: true,
500
+ anyOfBy: true,
501
+ ifDefined: true,
502
+ isUndefined: true,
503
+ // Strings
504
+ pattern: true,
505
+ minLength: true,
506
+ maxLength: true,
507
+ format: true,
508
+ email: true,
509
+ IsoDate: true,
510
+ IsoDateTime: true,
511
+ IsoMonth: true,
512
+ UtcOffset: true,
513
+ // Numbers
514
+ minimum: true,
515
+ exclusiveMinimum: true,
516
+ maximum: true,
517
+ exclusiveMaximum: true,
518
+ multipleOf: true,
519
+ precision: true,
520
+ // Arrays and sets
521
+ items: true,
522
+ prefixItems: true,
523
+ minItems: true,
524
+ maxItems: true,
525
+ uniqueItems: true,
526
+ Set2: true,
527
+ // Objects
528
+ properties: true,
529
+ required: true,
530
+ patternProperties: true,
531
+ additionalProperties: true,
532
+ keySchema: true,
533
+ minProperties: true,
534
+ minProperties2: true,
535
+ maxProperties: true,
536
+ exclusiveProperties: true,
537
+ instanceof: true,
538
+ Buffer: true,
539
+ // Annotations, and rules that the validation at the end checks
540
+ $schema: true,
541
+ $id: true,
542
+ title: true,
543
+ description: true,
544
+ deprecated: true,
545
+ readOnly: true,
546
+ writeOnly: true,
547
+ hasIsOfTypeCheck: true,
548
+ errorMessages: true,
549
+ enumNames: true,
550
+ enumKeys: true,
551
+ transform: true,
552
+ optionalValues: true,
553
+ customValidations: true,
554
+ customConversions: true,
555
+ postValidation: true,
556
+ // Not built by `j`
557
+ if: false,
558
+ // oxlint-disable-next-line unicorn/no-thenable -- a JSON Schema keyword, the object is never awaited
559
+ then: false,
560
+ else: false,
561
+ contentMediaType: false,
562
+ contentEncoding: false,
563
+ // Type-only and parser-only fields, never in a built schema
564
+ out: false,
565
+ optionalField: false,
566
+ }
567
+
568
+ /**
569
+ * @experimental
570
+ */
571
+ export interface GenerateMockFromSchemaOptions {
572
+ /**
573
+ * Fills every optional field, and puts one item in each list and one key in each map.
574
+ * Default: false, only the required fields.
575
+ */
576
+ allFields?: boolean
577
+ }
578
+
579
+ /**
580
+ * @experimental
581
+ */
582
+ export interface MockVariant<OUT> {
583
+ value: OUT
584
+ /**
585
+ * The choice this variant changes: a branch of a union, or a property of a group of exclusive
586
+ * properties. Absent for the first variant.
587
+ */
588
+ choice?: MockChoice
589
+ }
590
+
591
+ /**
592
+ * @experimental
593
+ */
594
+ export interface MockChoice {
595
+ /**
596
+ * Path of the union, or of the object with the group, e.g `address.taxId`, empty at the root.
597
+ * Two unions can share a path when one is directly inside a branch of the other.
598
+ */
599
+ path: string
600
+ /**
601
+ * Index of the branch, counting only branches that are not `null`, or of the property in the group.
602
+ */
603
+ option: number
604
+ /**
605
+ * Key of the branch in a `j.anyOfBy` union, or the property of the group.
606
+ */
607
+ key?: string
608
+ }
609
+
610
+ interface GenerationContext {
611
+ opt: GenerateMockFromSchemaOptions
612
+ /**
613
+ * The option to take at a choice. Other choices take their first option.
614
+ */
615
+ choices: Map<ChoicePoint, number>
616
+ /**
617
+ * Filled while generating: the choices, in the order they are reached.
618
+ */
619
+ reachedChoices: ReachedChoice[]
620
+ }
621
+
622
+ /**
623
+ * A union, by its schema node, or a group of exclusive properties.
624
+ */
625
+ type ChoicePoint = JsonSchema | readonly string[]
626
+
627
+ interface ReachedChoice {
628
+ point: ChoicePoint
629
+ path: string
630
+ /**
631
+ * For a union, the branches that are not `null`. For a group, its properties.
632
+ */
633
+ options: ChoiceOption[]
634
+ }
635
+
636
+ interface ChoiceOption {
637
+ /**
638
+ * Key of the branch in a `j.anyOfBy` union, or the property of a group of exclusive properties.
639
+ */
640
+ key?: string
641
+ }
642
+
643
+ interface UnionBranch extends ChoiceOption {
644
+ schema: JsonSchema
645
+ }
646
+
647
+ interface QueuedVariant {
648
+ choices: Map<ChoicePoint, number>
649
+ choice?: MockChoice
650
+ }