@naturalcycles/nodejs-lib 15.90.2 → 15.91.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.
@@ -1,1975 +0,0 @@
1
- /* eslint-disable id-denylist */
2
- // oxlint-disable max-lines
3
-
4
- import {
5
- _isUndefined,
6
- _numberEnumValues,
7
- _stringEnumValues,
8
- getEnumType,
9
- } from '@naturalcycles/js-lib'
10
- import { _uniq } from '@naturalcycles/js-lib/array'
11
- import { _assert } from '@naturalcycles/js-lib/error'
12
- import type { Set2 } from '@naturalcycles/js-lib/object'
13
- import { _sortObject } from '@naturalcycles/js-lib/object'
14
- import { _objectAssign, _typeCast, JWT_REGEX } from '@naturalcycles/js-lib/types'
15
- import type {
16
- AnyObject,
17
- BaseDBEntity,
18
- IANATimezone,
19
- Inclusiveness,
20
- IsoDate,
21
- IsoDateTime,
22
- IsoMonth,
23
- NumberEnum,
24
- StringEnum,
25
- StringMap,
26
- UnixTimestamp,
27
- UnixTimestampMillis,
28
- } from '@naturalcycles/js-lib/types'
29
- import {
30
- BASE64URL_REGEX,
31
- COUNTRY_CODE_REGEX,
32
- CURRENCY_REGEX,
33
- IPV4_REGEX,
34
- IPV6_REGEX,
35
- LANGUAGE_TAG_REGEX,
36
- SEMVER_REGEX,
37
- SLUG_REGEX,
38
- URL_REGEX,
39
- UUID_REGEX,
40
- } from '../regexes.js'
41
- import { TIMEZONES } from '../timezones.js'
42
- import {
43
- isEveryItemNumber,
44
- isEveryItemPrimitive,
45
- isEveryItemString,
46
- JSON_SCHEMA_ORDER,
47
- mergeJsonSchemaObjects,
48
- } from './jsonSchemaBuilder.util.js'
49
-
50
- export const j = {
51
- /**
52
- * Matches literally any value - equivalent to TypeScript's `any` type.
53
- * Use sparingly, as it bypasses type validation entirely.
54
- */
55
- any(): JsonSchemaAnyBuilder<any, any, false> {
56
- return new JsonSchemaAnyBuilder({})
57
- },
58
-
59
- string(): JsonSchemaStringBuilder<string, string, false> {
60
- return new JsonSchemaStringBuilder()
61
- },
62
-
63
- number(): JsonSchemaNumberBuilder<number, number, false> {
64
- return new JsonSchemaNumberBuilder()
65
- },
66
-
67
- boolean(): JsonSchemaBooleanBuilder<boolean, boolean, false> {
68
- return new JsonSchemaBooleanBuilder()
69
- },
70
-
71
- object: Object.assign(object, {
72
- dbEntity: objectDbEntity,
73
- infer: objectInfer,
74
- any() {
75
- return j.object<AnyObject>({}).allowAdditionalProperties()
76
- },
77
-
78
- stringMap<S extends JsonSchemaTerminal<any, any, any>>(
79
- schema: S,
80
- ): JsonSchemaObjectBuilder<StringMap<SchemaIn<S>>, StringMap<SchemaOut<S>>> {
81
- const isValueOptional = schema.getSchema().optionalField
82
- const builtSchema = schema.build()
83
- const finalValueSchema: JsonSchema = isValueOptional
84
- ? { anyOf: [{ isUndefined: true }, builtSchema] }
85
- : builtSchema
86
-
87
- return new JsonSchemaObjectBuilder<StringMap<SchemaIn<S>>, StringMap<SchemaOut<S>>>(
88
- {},
89
- {
90
- hasIsOfTypeCheck: false,
91
- patternProperties: {
92
- '^.+$': finalValueSchema,
93
- },
94
- },
95
- )
96
- },
97
-
98
- /**
99
- * @experimental Look around, maybe you find a rule that is better for your use-case.
100
- *
101
- * For Record<K, V> type of validations.
102
- * ```ts
103
- * const schema = j.object
104
- * .record(
105
- * j
106
- * .string()
107
- * .regex(/^\d{3,4}$/)
108
- * .branded<B>(),
109
- * j.number().nullable(),
110
- * )
111
- * .isOfType<Record<B, number | null>>()
112
- * ```
113
- *
114
- * When the keys of the Record are values from an Enum, prefer `j.object.withEnumKeys`!
115
- *
116
- * Non-matching keys will be stripped from the object, i.e. they will not cause an error.
117
- *
118
- * Caveat: This rule first validates values of every properties of the object, and only then validates the keys.
119
- * A consequence of that is that the validation will throw when there is an unexpected property with a value not matching the value schema.
120
- */
121
- record,
122
-
123
- /**
124
- * For Record<ENUM, V> type of validations.
125
- *
126
- * When the keys of the Record are values from an Enum,
127
- * this helper is more performant and behaves in a more conventional manner than `j.object.record` would.
128
- *
129
- *
130
- */
131
- withEnumKeys,
132
- withRegexKeys,
133
- }),
134
-
135
- array<IN, OUT, Opt>(
136
- itemSchema: JsonSchemaAnyBuilder<IN, OUT, Opt>,
137
- ): JsonSchemaArrayBuilder<IN, OUT, Opt> {
138
- return new JsonSchemaArrayBuilder(itemSchema)
139
- },
140
-
141
- tuple<const S extends JsonSchemaAnyBuilder<any, any, any>[]>(
142
- items: S,
143
- ): JsonSchemaTupleBuilder<S> {
144
- return new JsonSchemaTupleBuilder<S>(items)
145
- },
146
-
147
- set<IN, OUT, Opt>(
148
- itemSchema: JsonSchemaAnyBuilder<IN, OUT, Opt>,
149
- ): JsonSchemaSet2Builder<IN, OUT, Opt> {
150
- return new JsonSchemaSet2Builder(itemSchema)
151
- },
152
-
153
- buffer(): JsonSchemaBufferBuilder {
154
- return new JsonSchemaBufferBuilder()
155
- },
156
-
157
- enum<const T extends readonly (string | number | boolean | null)[] | StringEnum | NumberEnum>(
158
- input: T,
159
- opt?: JsonBuilderRuleOpt,
160
- ): JsonSchemaEnumBuilder<
161
- T extends readonly (infer U)[]
162
- ? U
163
- : T extends StringEnum
164
- ? T[keyof T]
165
- : T extends NumberEnum
166
- ? T[keyof T]
167
- : never
168
- > {
169
- let enumValues: readonly (string | number | boolean | null)[] | undefined
170
- let baseType: EnumBaseType = 'other'
171
-
172
- if (Array.isArray(input)) {
173
- enumValues = input
174
- if (isEveryItemNumber(input)) {
175
- baseType = 'number'
176
- } else if (isEveryItemString(input)) {
177
- baseType = 'string'
178
- }
179
- } else if (typeof input === 'object') {
180
- const enumType = getEnumType(input)
181
- if (enumType === 'NumberEnum') {
182
- enumValues = _numberEnumValues(input as NumberEnum)
183
- baseType = 'number'
184
- } else if (enumType === 'StringEnum') {
185
- enumValues = _stringEnumValues(input as StringEnum)
186
- baseType = 'string'
187
- }
188
- }
189
-
190
- _assert(enumValues, 'Unsupported enum input')
191
- return new JsonSchemaEnumBuilder(enumValues as any, baseType, opt)
192
- },
193
-
194
- /**
195
- * Use only with primitive values, otherwise this function will throw to avoid bugs.
196
- * To validate objects, use `anyOfBy`.
197
- *
198
- * Our Ajv is configured to strip unexpected properties from objects,
199
- * and since Ajv is mutating the input, this means that it cannot
200
- * properly validate the same data over multiple schemas.
201
- *
202
- * Use `anyOf` when schemas may overlap (e.g., AccountId | PartnerId with same format).
203
- * Use `oneOf` when schemas are mutually exclusive.
204
- */
205
- oneOf<
206
- B extends readonly JsonSchemaAnyBuilder<any, any, boolean>[],
207
- IN = BuilderInUnion<B>,
208
- OUT = BuilderOutUnion<B>,
209
- >(items: [...B]): JsonSchemaAnyBuilder<IN, OUT, false> {
210
- const schemas = items.map(b => b.build())
211
- _assert(
212
- schemas.every(hasNoObjectSchemas),
213
- 'Do not use `oneOf` validation with non-primitive types!',
214
- )
215
-
216
- return new JsonSchemaAnyBuilder<IN, OUT, false>({
217
- oneOf: schemas,
218
- })
219
- },
220
-
221
- /**
222
- * Use only with primitive values, otherwise this function will throw to avoid bugs.
223
- * To validate objects, use `anyOfBy` or `anyOfThese`.
224
- *
225
- * Our Ajv is configured to strip unexpected properties from objects,
226
- * and since Ajv is mutating the input, this means that it cannot
227
- * properly validate the same data over multiple schemas.
228
- *
229
- * Use `anyOf` when schemas may overlap (e.g., AccountId | PartnerId with same format).
230
- * Use `oneOf` when schemas are mutually exclusive.
231
- */
232
- anyOf<
233
- B extends readonly JsonSchemaAnyBuilder<any, any, boolean>[],
234
- IN = BuilderInUnion<B>,
235
- OUT = BuilderOutUnion<B>,
236
- >(items: [...B]): JsonSchemaAnyBuilder<IN, OUT, false> {
237
- const schemas = items.map(b => b.build())
238
- _assert(
239
- schemas.every(hasNoObjectSchemas),
240
- 'Do not use `anyOf` validation with non-primitive types!',
241
- )
242
-
243
- return new JsonSchemaAnyBuilder<IN, OUT, false>({
244
- anyOf: schemas,
245
- })
246
- },
247
-
248
- /**
249
- * Pick validation schema for an object based on the value of a specific property.
250
- *
251
- * ```
252
- * const schemaMap = {
253
- * true: successSchema,
254
- * false: errorSchema
255
- * }
256
- *
257
- * const schema = j.anyOfBy('success', schemaMap)
258
- * ```
259
- */
260
- anyOfBy<
261
- P extends string,
262
- D extends Record<PropertyKey, JsonSchemaTerminal<any, any, any>>,
263
- IN = AnyOfByIn<D>,
264
- OUT = AnyOfByOut<D>,
265
- >(propertyName: P, schemaDictionary: D): JsonSchemaAnyOfByBuilder<IN, OUT, P> {
266
- return new JsonSchemaAnyOfByBuilder<IN, OUT, P>(propertyName, schemaDictionary)
267
- },
268
-
269
- /**
270
- * Custom version of `anyOf` which - in contrast to the original function - does not mutate the input.
271
- * This comes with a performance penalty, so do not use it where performance matters.
272
- *
273
- * ```
274
- * const schema = j.anyOfThese([successSchema, errorSchema])
275
- * ```
276
- */
277
- anyOfThese<
278
- B extends readonly JsonSchemaAnyBuilder<any, any, boolean>[],
279
- IN = BuilderInUnion<B>,
280
- OUT = BuilderOutUnion<B>,
281
- >(items: [...B]): JsonSchemaAnyBuilder<IN, OUT, false> {
282
- return new JsonSchemaAnyBuilder<IN, OUT, false>({
283
- anyOfThese: items.map(b => b.build()),
284
- })
285
- },
286
-
287
- and() {
288
- return {
289
- silentBob: () => {
290
- throw new Error('...strike back!')
291
- },
292
- }
293
- },
294
-
295
- literal<const V extends string | number | boolean | null>(v: V) {
296
- let baseType: EnumBaseType = 'other'
297
- if (typeof v === 'string') baseType = 'string'
298
- if (typeof v === 'number') baseType = 'number'
299
- return new JsonSchemaEnumBuilder<V>([v], baseType)
300
- },
301
- }
302
-
303
- const TS_2500 = 16725225600 // 2500-01-01
304
- const TS_2500_MILLIS = TS_2500 * 1000
305
- const TS_2000 = 946684800 // 2000-01-01
306
- const TS_2000_MILLIS = TS_2000 * 1000
307
-
308
- /*
309
- Notes for future reference
310
-
311
- Q: Why do we need `Opt` - when `IN` and `OUT` already carries the `| undefined`?
312
- A: Because of objects. Without `Opt`, an optional field would be inferred as `{ foo: string | undefined }`,
313
- which means that the `foo` property would be mandatory, it's just that its value can be `undefined` as well.
314
- With `Opt`, we can infer it as `{ foo?: string | undefined }`.
315
- */
316
-
317
- export class JsonSchemaTerminal<IN, OUT, Opt> {
318
- protected schema: JsonSchema
319
-
320
- constructor(schema: JsonSchema) {
321
- this.schema = schema
322
- }
323
-
324
- getSchema(): JsonSchema {
325
- return this.schema
326
- }
327
-
328
- /**
329
- * Produces a "clean schema object" without methods.
330
- * Same as if it would be JSON.stringified.
331
- */
332
- build(): JsonSchema<IN, OUT> {
333
- _assert(
334
- !(this.schema.optionalField && this.schema.default !== undefined),
335
- '.optional() and .default() should not be used together - the default value makes .optional() redundant and causes incorrect type inference',
336
- )
337
-
338
- const jsonSchema = _sortObject(
339
- deepCopyPreservingFunctions(this.schema) as AnyObject,
340
- JSON_SCHEMA_ORDER,
341
- ) as JsonSchema<IN, OUT>
342
-
343
- delete jsonSchema.optionalField
344
-
345
- return jsonSchema
346
- }
347
-
348
- clone(): this {
349
- const cloned = Object.create(Object.getPrototypeOf(this))
350
- cloned.schema = deepCopyPreservingFunctions(this.schema)
351
- return cloned
352
- }
353
-
354
- cloneAndUpdateSchema(schema: Partial<JsonSchema>): this {
355
- const clone = this.clone()
356
- _objectAssign(clone.schema, schema)
357
- return clone
358
- }
359
-
360
- /**
361
- * @experimental
362
- */
363
- in!: IN
364
- out!: OUT
365
- opt!: Opt
366
- }
367
-
368
- export class JsonSchemaAnyBuilder<IN, OUT, Opt> extends JsonSchemaTerminal<IN, OUT, Opt> {
369
- protected setErrorMessage(ruleName: string, errorMessage: string | undefined): void {
370
- if (_isUndefined(errorMessage)) return
371
-
372
- this.schema.errorMessages ||= {}
373
- this.schema.errorMessages[ruleName] = errorMessage
374
- }
375
-
376
- /**
377
- * A helper function that takes a type parameter and compares it with the type inferred from the schema.
378
- *
379
- * When the type inferred from the schema differs from the passed-in type,
380
- * the schema becomes unusable, by turning its type into `never`.
381
- *
382
- * ```ts
383
- * const schemaGood = j.string().isOfType<string>() // ✅
384
- *
385
- * const schemaBad = j.string().isOfType<number>() // ❌
386
- * schemaBad.build() // TypeError: property "build" does not exist on type "never"
387
- *
388
- * const result = ajvValidateRequest.body(req, schemaBad) // result will have `unknown` type
389
- * ```
390
- */
391
- isOfType<ExpectedType>(): ExactMatch<ExpectedType, OUT> extends true ? this : never {
392
- return this.cloneAndUpdateSchema({ hasIsOfTypeCheck: true }) as any
393
- }
394
-
395
- $schema($schema: string): this {
396
- return this.cloneAndUpdateSchema({ $schema })
397
- }
398
-
399
- $schemaDraft7(): this {
400
- return this.$schema('http://json-schema.org/draft-07/schema#')
401
- }
402
-
403
- $id($id: string): this {
404
- return this.cloneAndUpdateSchema({ $id })
405
- }
406
-
407
- title(title: string): this {
408
- return this.cloneAndUpdateSchema({ title })
409
- }
410
-
411
- description(description: string): this {
412
- return this.cloneAndUpdateSchema({ description })
413
- }
414
-
415
- deprecated(deprecated = true): this {
416
- return this.cloneAndUpdateSchema({ deprecated })
417
- }
418
-
419
- type(type: string): this {
420
- return this.cloneAndUpdateSchema({ type })
421
- }
422
-
423
- default(v: any): this {
424
- return this.cloneAndUpdateSchema({ default: v })
425
- }
426
-
427
- instanceof(of: string): this {
428
- return this.cloneAndUpdateSchema({ type: 'object', instanceof: of })
429
- }
430
-
431
- optional(): JsonSchemaAnyBuilder<IN | undefined, OUT | undefined, true> {
432
- const clone = this.cloneAndUpdateSchema({ optionalField: true })
433
- return clone as unknown as JsonSchemaAnyBuilder<IN | undefined, OUT | undefined, true>
434
- }
435
-
436
- nullable(): JsonSchemaAnyBuilder<IN | null, OUT | null, Opt> {
437
- return new JsonSchemaAnyBuilder({
438
- anyOf: [this.build(), { type: 'null' }],
439
- })
440
- }
441
-
442
- /**
443
- * @deprecated
444
- * The usage of this function is discouraged as it defeats the purpose of having type-safe validation.
445
- */
446
- castAs<T>(): JsonSchemaAnyBuilder<T, T, Opt> {
447
- return this as unknown as JsonSchemaAnyBuilder<T, T, Opt>
448
- }
449
-
450
- /**
451
- * Locks the given schema chain and no other modification can be done to it.
452
- */
453
- final(): JsonSchemaTerminal<IN, OUT, Opt> {
454
- return new JsonSchemaTerminal<IN, OUT, Opt>(this.schema)
455
- }
456
-
457
- /**
458
- *
459
- * @param validator A validator function that returns an error message or undefined.
460
- *
461
- * You may add multiple custom validators and they will be executed in the order you added them.
462
- */
463
- custom<OUT2 = OUT>(validator: CustomValidatorFn): JsonSchemaAnyBuilder<IN, OUT2, Opt> {
464
- const { customValidations = [] } = this.schema
465
- return this.cloneAndUpdateSchema({
466
- customValidations: [...customValidations, validator],
467
- }) as unknown as JsonSchemaAnyBuilder<IN, OUT2, Opt>
468
- }
469
-
470
- /**
471
- *
472
- * @param converter A converter function that returns a new value.
473
- *
474
- * You may add multiple converters and they will be executed in the order you added them,
475
- * each converter receiving the result from the previous one.
476
- *
477
- * This feature only works when the current schema is nested in an object or array schema,
478
- * due to how mutability works in Ajv.
479
- */
480
- convert<OUT2>(converter: CustomConverterFn<OUT2>): JsonSchemaAnyBuilder<IN, OUT2, Opt> {
481
- const { customConversions = [] } = this.schema
482
- return this.cloneAndUpdateSchema({
483
- customConversions: [...customConversions, converter],
484
- }) as unknown as JsonSchemaAnyBuilder<IN, OUT2, Opt>
485
- }
486
- }
487
-
488
- export class JsonSchemaStringBuilder<
489
- IN extends string | undefined = string,
490
- OUT = IN,
491
- Opt extends boolean = false,
492
- > extends JsonSchemaAnyBuilder<IN, OUT, Opt> {
493
- constructor() {
494
- super({
495
- type: 'string',
496
- })
497
- }
498
-
499
- /**
500
- * @param optionalValues List of values that should be considered/converted as `undefined`.
501
- *
502
- * This `optionalValues` feature only works when the current schema is nested in an object or array schema,
503
- * due to how mutability works in Ajv.
504
- *
505
- * Make sure this `optional()` call is at the end of your call chain.
506
- *
507
- * When `null` is included in optionalValues, the return type becomes `JsonSchemaTerminal`
508
- * (no further chaining allowed) because the schema is wrapped in an anyOf structure.
509
- */
510
- override optional<T extends readonly (string | null)[] | undefined = undefined>(
511
- optionalValues?: T,
512
- ): T extends readonly (infer U)[]
513
- ? null extends U
514
- ? JsonSchemaTerminal<IN | undefined, OUT | undefined, true>
515
- : JsonSchemaStringBuilder<IN | undefined, OUT | undefined, true>
516
- : JsonSchemaStringBuilder<IN | undefined, OUT | undefined, true> {
517
- if (!optionalValues) {
518
- return super.optional() as any
519
- }
520
-
521
- _typeCast<(string | null)[]>(optionalValues)
522
-
523
- let newBuilder: JsonSchemaTerminal<IN | undefined, OUT | undefined, true> =
524
- new JsonSchemaStringBuilder<IN, OUT, Opt>().optional()
525
- const alternativesSchema = j.enum(optionalValues)
526
- Object.assign(newBuilder.getSchema(), {
527
- anyOf: [this.build(), alternativesSchema.build()],
528
- optionalValues,
529
- })
530
-
531
- // When `null` is specified, we want `null` to be stripped and the value to become `undefined`,
532
- // so we must allow `null` values to be parsed by Ajv,
533
- // but the typing should not reflect that.
534
- // We also cannot accept more rules attached, since we're not building a StringSchema anymore.
535
- if (optionalValues.includes(null)) {
536
- newBuilder = new JsonSchemaTerminal({
537
- anyOf: [{ type: 'null', optionalValues }, newBuilder.build()],
538
- optionalField: true,
539
- })
540
- }
541
-
542
- return newBuilder as any
543
- }
544
-
545
- regex(pattern: RegExp, opt?: JsonBuilderRuleOpt): this {
546
- _assert(
547
- !pattern.flags,
548
- `Regex flags are not supported by JSON Schema. Received: /${pattern.source}/${pattern.flags}`,
549
- )
550
- return this.pattern(pattern.source, opt)
551
- }
552
-
553
- pattern(pattern: string, opt?: JsonBuilderRuleOpt): this {
554
- const clone = this.cloneAndUpdateSchema({ pattern })
555
- if (opt?.name) clone.setErrorMessage('pattern', `is not a valid ${opt.name}`)
556
- if (opt?.msg) clone.setErrorMessage('pattern', opt.msg)
557
- return clone
558
- }
559
-
560
- minLength(minLength: number): this {
561
- return this.cloneAndUpdateSchema({ minLength })
562
- }
563
-
564
- maxLength(maxLength: number): this {
565
- return this.cloneAndUpdateSchema({ maxLength })
566
- }
567
-
568
- length(exactLength: number): this
569
- length(minLength: number, maxLength: number): this
570
- length(minLengthOrExactLength: number, maxLength?: number): this {
571
- const maxLengthActual = maxLength ?? minLengthOrExactLength
572
- return this.minLength(minLengthOrExactLength).maxLength(maxLengthActual)
573
- }
574
-
575
- email(opt?: Partial<JsonSchemaStringEmailOptions>): this {
576
- const defaultOptions: JsonSchemaStringEmailOptions = { checkTLD: true }
577
- return this.cloneAndUpdateSchema({ email: { ...defaultOptions, ...opt } })
578
- .trim()
579
- .toLowerCase()
580
- }
581
-
582
- trim(): this {
583
- return this.cloneAndUpdateSchema({ transform: { ...this.schema.transform, trim: true } })
584
- }
585
-
586
- toLowerCase(): this {
587
- return this.cloneAndUpdateSchema({
588
- transform: { ...this.schema.transform, toLowerCase: true },
589
- })
590
- }
591
-
592
- toUpperCase(): this {
593
- return this.cloneAndUpdateSchema({
594
- transform: { ...this.schema.transform, toUpperCase: true },
595
- })
596
- }
597
-
598
- truncate(toLength: number): this {
599
- return this.cloneAndUpdateSchema({
600
- transform: { ...this.schema.transform, truncate: toLength },
601
- })
602
- }
603
-
604
- branded<B extends string>(): JsonSchemaStringBuilder<B, B, Opt> {
605
- return this as unknown as JsonSchemaStringBuilder<B, B, Opt>
606
- }
607
-
608
- /**
609
- * Validates that the input is a fully-specified YYYY-MM-DD formatted valid IsoDate value.
610
- *
611
- * All previous expectations in the schema chain are dropped - including `.optional()` -
612
- * because this call effectively starts a new schema chain.
613
- */
614
- isoDate(): JsonSchemaIsoDateBuilder {
615
- return new JsonSchemaIsoDateBuilder()
616
- }
617
-
618
- isoDateTime(): JsonSchemaStringBuilder<IsoDateTime | IN, IsoDateTime, Opt> {
619
- return this.cloneAndUpdateSchema({ IsoDateTime: true }).branded<IsoDateTime>()
620
- }
621
-
622
- isoMonth(): JsonSchemaIsoMonthBuilder {
623
- return new JsonSchemaIsoMonthBuilder()
624
- }
625
-
626
- /**
627
- * Validates the string format to be JWT.
628
- * Expects the JWT to be signed!
629
- */
630
- jwt(): this {
631
- return this.regex(JWT_REGEX, { msg: 'is not a valid JWT format' })
632
- }
633
-
634
- url(): this {
635
- return this.regex(URL_REGEX, { msg: 'is not a valid URL format' })
636
- }
637
-
638
- ipv4(): this {
639
- return this.regex(IPV4_REGEX, { msg: 'is not a valid IPv4 format' })
640
- }
641
-
642
- ipv6(): this {
643
- return this.regex(IPV6_REGEX, { msg: 'is not a valid IPv6 format' })
644
- }
645
-
646
- slug(): this {
647
- return this.regex(SLUG_REGEX, { msg: 'is not a valid slug format' })
648
- }
649
-
650
- semVer(): this {
651
- return this.regex(SEMVER_REGEX, { msg: 'is not a valid semver format' })
652
- }
653
-
654
- languageTag(): this {
655
- return this.regex(LANGUAGE_TAG_REGEX, { msg: 'is not a valid language format' })
656
- }
657
-
658
- countryCode(): this {
659
- return this.regex(COUNTRY_CODE_REGEX, { msg: 'is not a valid country code format' })
660
- }
661
-
662
- currency(): this {
663
- return this.regex(CURRENCY_REGEX, { msg: 'is not a valid currency format' })
664
- }
665
-
666
- /**
667
- * Validates that the input is a valid IANATimzone value.
668
- *
669
- * All previous expectations in the schema chain are dropped - including `.optional()` -
670
- * because this call effectively starts a new schema chain as an `enum` validation.
671
- */
672
- ianaTimezone(): JsonSchemaEnumBuilder<string | IANATimezone, IANATimezone, false> {
673
- // UTC is added to assist unit-testing, which uses UTC by default (not technically a valid Iana timezone identifier)
674
- return j.enum(TIMEZONES, { msg: 'is an invalid IANA timezone' }).branded<IANATimezone>()
675
- }
676
-
677
- base64Url(): this {
678
- return this.regex(BASE64URL_REGEX, {
679
- msg: 'contains characters not allowed in Base64 URL characterset',
680
- })
681
- }
682
-
683
- uuid(): this {
684
- return this.regex(UUID_REGEX, { msg: 'is an invalid UUID' })
685
- }
686
- }
687
-
688
- export interface JsonSchemaStringEmailOptions {
689
- checkTLD: boolean
690
- }
691
-
692
- export class JsonSchemaIsoDateBuilder<Opt extends boolean = false> extends JsonSchemaAnyBuilder<
693
- string | IsoDate,
694
- IsoDate,
695
- Opt
696
- > {
697
- constructor() {
698
- super({
699
- type: 'string',
700
- IsoDate: {},
701
- })
702
- }
703
-
704
- /**
705
- * @param nullValue Pass `null` to have `null` values be considered/converted as `undefined`.
706
- *
707
- * This `null` feature only works when the current schema is nested in an object or array schema,
708
- * due to how mutability works in Ajv.
709
- *
710
- * When `null` is passed, the return type becomes `JsonSchemaTerminal`
711
- * (no further chaining allowed) because the schema is wrapped in an anyOf structure.
712
- */
713
- override optional<N extends null | undefined = undefined>(
714
- nullValue?: N,
715
- ): N extends null
716
- ? JsonSchemaTerminal<string | IsoDate | null | undefined, IsoDate | undefined, true>
717
- : JsonSchemaAnyBuilder<string | IsoDate | undefined, IsoDate | undefined, true> {
718
- if (nullValue === undefined) {
719
- return super.optional()
720
- }
721
-
722
- // When `null` is specified, we want `null` to be stripped and the value to become `undefined`,
723
- // so we must allow `null` values to be parsed by Ajv,
724
- // but the typing should not reflect that.
725
- // We also cannot accept more rules attached, since we're not building an ObjectSchema anymore.
726
- return new JsonSchemaTerminal({
727
- anyOf: [{ type: 'null', optionalValues: [null] }, this.build()],
728
- optionalField: true,
729
- }) as any
730
- }
731
-
732
- before(date: string): this {
733
- return this.cloneAndUpdateSchema({ IsoDate: { before: date } })
734
- }
735
-
736
- sameOrBefore(date: string): this {
737
- return this.cloneAndUpdateSchema({ IsoDate: { sameOrBefore: date } })
738
- }
739
-
740
- after(date: string): this {
741
- return this.cloneAndUpdateSchema({ IsoDate: { after: date } })
742
- }
743
-
744
- sameOrAfter(date: string): this {
745
- return this.cloneAndUpdateSchema({ IsoDate: { sameOrAfter: date } })
746
- }
747
-
748
- between(fromDate: string, toDate: string, incl: Inclusiveness): this {
749
- let schemaPatch: Partial<JsonSchema> = {}
750
-
751
- if (incl === '[)') {
752
- schemaPatch = { IsoDate: { sameOrAfter: fromDate, before: toDate } }
753
- } else if (incl === '[]') {
754
- schemaPatch = { IsoDate: { sameOrAfter: fromDate, sameOrBefore: toDate } }
755
- }
756
-
757
- return this.cloneAndUpdateSchema(schemaPatch)
758
- }
759
- }
760
-
761
- export interface JsonSchemaIsoDateOptions {
762
- before?: string
763
- sameOrBefore?: string
764
- after?: string
765
- sameOrAfter?: string
766
- }
767
-
768
- export class JsonSchemaIsoMonthBuilder<Opt extends boolean = false> extends JsonSchemaAnyBuilder<
769
- string | IsoDate,
770
- IsoMonth,
771
- Opt
772
- > {
773
- constructor() {
774
- super({
775
- type: 'string',
776
- IsoMonth: {},
777
- })
778
- }
779
- }
780
-
781
- export interface JsonSchemaIsoMonthOptions {}
782
-
783
- export class JsonSchemaNumberBuilder<
784
- IN extends number | undefined = number,
785
- OUT = IN,
786
- Opt extends boolean = false,
787
- > extends JsonSchemaAnyBuilder<IN, OUT, Opt> {
788
- constructor() {
789
- super({
790
- type: 'number',
791
- })
792
- }
793
-
794
- /**
795
- * @param optionalValues List of values that should be considered/converted as `undefined`.
796
- *
797
- * This `optionalValues` feature only works when the current schema is nested in an object or array schema,
798
- * due to how mutability works in Ajv.
799
- *
800
- * Make sure this `optional()` call is at the end of your call chain.
801
- *
802
- * When `null` is included in optionalValues, the return type becomes `JsonSchemaTerminal`
803
- * (no further chaining allowed) because the schema is wrapped in an anyOf structure.
804
- */
805
- override optional<T extends readonly (number | null)[] | undefined = undefined>(
806
- optionalValues?: T,
807
- ): T extends readonly (infer U)[]
808
- ? null extends U
809
- ? JsonSchemaTerminal<IN | undefined, OUT | undefined, true>
810
- : JsonSchemaNumberBuilder<IN | undefined, OUT | undefined, true>
811
- : JsonSchemaNumberBuilder<IN | undefined, OUT | undefined, true> {
812
- if (!optionalValues) {
813
- return super.optional() as any
814
- }
815
-
816
- _typeCast<(number | null)[]>(optionalValues)
817
-
818
- let newBuilder: JsonSchemaTerminal<IN | undefined, OUT | undefined, true> =
819
- new JsonSchemaNumberBuilder<IN, OUT, Opt>().optional()
820
- const alternativesSchema = j.enum(optionalValues)
821
- Object.assign(newBuilder.getSchema(), {
822
- anyOf: [this.build(), alternativesSchema.build()],
823
- optionalValues,
824
- })
825
-
826
- // When `null` is specified, we want `null` to be stripped and the value to become `undefined`,
827
- // so we must allow `null` values to be parsed by Ajv,
828
- // but the typing should not reflect that.
829
- // We also cannot accept more rules attached, since we're not building a NumberSchema anymore.
830
- if (optionalValues.includes(null)) {
831
- newBuilder = new JsonSchemaTerminal({
832
- anyOf: [{ type: 'null', optionalValues }, newBuilder.build()],
833
- optionalField: true,
834
- })
835
- }
836
-
837
- return newBuilder as any
838
- }
839
-
840
- integer(): this {
841
- return this.cloneAndUpdateSchema({ type: 'integer' })
842
- }
843
-
844
- branded<B extends number>(): JsonSchemaNumberBuilder<B, B, Opt> {
845
- return this as unknown as JsonSchemaNumberBuilder<B, B, Opt>
846
- }
847
-
848
- multipleOf(multipleOf: number): this {
849
- return this.cloneAndUpdateSchema({ multipleOf })
850
- }
851
-
852
- min(minimum: number): this {
853
- return this.cloneAndUpdateSchema({ minimum })
854
- }
855
-
856
- exclusiveMin(exclusiveMinimum: number): this {
857
- return this.cloneAndUpdateSchema({ exclusiveMinimum })
858
- }
859
-
860
- max(maximum: number): this {
861
- return this.cloneAndUpdateSchema({ maximum })
862
- }
863
-
864
- exclusiveMax(exclusiveMaximum: number): this {
865
- return this.cloneAndUpdateSchema({ exclusiveMaximum })
866
- }
867
-
868
- lessThan(value: number): this {
869
- return this.exclusiveMax(value)
870
- }
871
-
872
- lessThanOrEqual(value: number): this {
873
- return this.max(value)
874
- }
875
-
876
- moreThan(value: number): this {
877
- return this.exclusiveMin(value)
878
- }
879
-
880
- moreThanOrEqual(value: number): this {
881
- return this.min(value)
882
- }
883
-
884
- equal(value: number): this {
885
- return this.min(value).max(value)
886
- }
887
-
888
- range(minimum: number, maximum: number, incl: Inclusiveness): this {
889
- if (incl === '[)') {
890
- return this.moreThanOrEqual(minimum).lessThan(maximum)
891
- }
892
- return this.moreThanOrEqual(minimum).lessThanOrEqual(maximum)
893
- }
894
-
895
- int32(): this {
896
- const MIN_INT32 = -(2 ** 31)
897
- const MAX_INT32 = 2 ** 31 - 1
898
- const currentMin = this.schema.minimum ?? Number.MIN_SAFE_INTEGER
899
- const currentMax = this.schema.maximum ?? Number.MAX_SAFE_INTEGER
900
- const newMin = Math.max(MIN_INT32, currentMin)
901
- const newMax = Math.min(MAX_INT32, currentMax)
902
- return this.integer().min(newMin).max(newMax)
903
- }
904
-
905
- int64(): this {
906
- const currentMin = this.schema.minimum ?? Number.MIN_SAFE_INTEGER
907
- const currentMax = this.schema.maximum ?? Number.MAX_SAFE_INTEGER
908
- const newMin = Math.max(Number.MIN_SAFE_INTEGER, currentMin)
909
- const newMax = Math.min(Number.MAX_SAFE_INTEGER, currentMax)
910
- return this.integer().min(newMin).max(newMax)
911
- }
912
-
913
- float(): this {
914
- return this
915
- }
916
-
917
- double(): this {
918
- return this
919
- }
920
-
921
- unixTimestamp(): JsonSchemaNumberBuilder<UnixTimestamp, UnixTimestamp, Opt> {
922
- return this.integer().min(0).max(TS_2500).branded<UnixTimestamp>()
923
- }
924
-
925
- unixTimestamp2000(): JsonSchemaNumberBuilder<UnixTimestamp, UnixTimestamp, Opt> {
926
- return this.integer().min(TS_2000).max(TS_2500).branded<UnixTimestamp>()
927
- }
928
-
929
- unixTimestampMillis(): JsonSchemaNumberBuilder<UnixTimestampMillis, UnixTimestampMillis, Opt> {
930
- return this.integer().min(0).max(TS_2500_MILLIS).branded<UnixTimestampMillis>()
931
- }
932
-
933
- unixTimestamp2000Millis(): JsonSchemaNumberBuilder<
934
- UnixTimestampMillis,
935
- UnixTimestampMillis,
936
- Opt
937
- > {
938
- return this.integer().min(TS_2000_MILLIS).max(TS_2500_MILLIS).branded<UnixTimestampMillis>()
939
- }
940
-
941
- utcOffset(): this {
942
- return this.integer()
943
- .multipleOf(15)
944
- .min(-12 * 60)
945
- .max(14 * 60)
946
- }
947
-
948
- utcOffsetHour(): this {
949
- return this.integer().min(-12).max(14)
950
- }
951
-
952
- /**
953
- * Specify the precision of the floating point numbers by the number of digits after the ".".
954
- * Excess digits will be cut-off when the current schema is nested in an object or array schema,
955
- * due to how mutability works in Ajv.
956
- */
957
- precision(numberOfDigits: number): this {
958
- return this.cloneAndUpdateSchema({ precision: numberOfDigits })
959
- }
960
- }
961
-
962
- export class JsonSchemaBooleanBuilder<
963
- IN extends boolean | undefined = boolean,
964
- OUT = IN,
965
- Opt extends boolean = false,
966
- > extends JsonSchemaAnyBuilder<IN, OUT, Opt> {
967
- constructor() {
968
- super({
969
- type: 'boolean',
970
- })
971
- }
972
-
973
- /**
974
- * @param optionalValue One of the two possible boolean values that should be considered/converted as `undefined`.
975
- *
976
- * This `optionalValue` feature only works when the current schema is nested in an object or array schema,
977
- * due to how mutability works in Ajv.
978
- */
979
- override optional(
980
- optionalValue?: boolean,
981
- ): JsonSchemaBooleanBuilder<IN | undefined, OUT | undefined, true> {
982
- if (typeof optionalValue === 'undefined') {
983
- return super.optional() as unknown as JsonSchemaBooleanBuilder<
984
- IN | undefined,
985
- OUT | undefined,
986
- true
987
- >
988
- }
989
-
990
- const newBuilder = new JsonSchemaBooleanBuilder<IN, OUT, Opt>().optional()
991
- const alternativesSchema = j.enum([optionalValue])
992
- Object.assign(newBuilder.getSchema(), {
993
- anyOf: [this.build(), alternativesSchema.build()],
994
- optionalValues: [optionalValue],
995
- })
996
-
997
- return newBuilder
998
- }
999
- }
1000
-
1001
- export class JsonSchemaObjectBuilder<
1002
- IN extends AnyObject,
1003
- OUT extends AnyObject,
1004
- Opt extends boolean = false,
1005
- > extends JsonSchemaAnyBuilder<IN, OUT, Opt> {
1006
- constructor(props?: AnyObject, opt?: JsonSchemaObjectBuilderOpts) {
1007
- super({
1008
- type: 'object',
1009
- properties: {},
1010
- required: [],
1011
- additionalProperties: false,
1012
- hasIsOfTypeCheck: opt?.hasIsOfTypeCheck ?? true,
1013
- patternProperties: opt?.patternProperties ?? undefined,
1014
- keySchema: opt?.keySchema ?? undefined,
1015
- })
1016
-
1017
- if (props) this.addProperties(props)
1018
- }
1019
-
1020
- addProperties(props: AnyObject): this {
1021
- const properties: Record<string, JsonSchema> = {}
1022
- const required: string[] = []
1023
-
1024
- for (const [key, builder] of Object.entries(props)) {
1025
- const isOptional = (builder as JsonSchemaTerminal<any, any, any>).getSchema().optionalField
1026
- if (!isOptional) {
1027
- required.push(key)
1028
- }
1029
-
1030
- const schema = builder.build()
1031
- properties[key] = schema
1032
- }
1033
-
1034
- this.schema.properties = properties
1035
- this.schema.required = _uniq(required).sort()
1036
-
1037
- return this
1038
- }
1039
-
1040
- /**
1041
- * @param nullValue Pass `null` to have `null` values be considered/converted as `undefined`.
1042
- *
1043
- * This `null` feature only works when the current schema is nested in an object or array schema,
1044
- * due to how mutability works in Ajv.
1045
- *
1046
- * When `null` is passed, the return type becomes `JsonSchemaTerminal`
1047
- * (no further chaining allowed) because the schema is wrapped in an anyOf structure.
1048
- */
1049
- override optional<N extends null | undefined = undefined>(
1050
- nullValue?: N,
1051
- ): N extends null
1052
- ? JsonSchemaTerminal<IN | null | undefined, OUT | undefined, true>
1053
- : JsonSchemaAnyBuilder<IN | undefined, OUT | undefined, true> {
1054
- if (nullValue === undefined) {
1055
- return super.optional()
1056
- }
1057
-
1058
- // When `null` is specified, we want `null` to be stripped and the value to become `undefined`,
1059
- // so we must allow `null` values to be parsed by Ajv,
1060
- // but the typing should not reflect that.
1061
- // We also cannot accept more rules attached, since we're not building an ObjectSchema anymore.
1062
- return new JsonSchemaTerminal({
1063
- anyOf: [{ type: 'null', optionalValues: [null] }, this.build()],
1064
- optionalField: true,
1065
- }) as any
1066
- }
1067
-
1068
- /**
1069
- * When set, the validation will not strip away properties that are not specified explicitly in the schema.
1070
- */
1071
-
1072
- allowAdditionalProperties(): this {
1073
- return this.cloneAndUpdateSchema({ additionalProperties: true })
1074
- }
1075
-
1076
- extend<P extends Record<string, JsonSchemaAnyBuilder<any, any, any>>>(
1077
- props: P,
1078
- ): JsonSchemaObjectBuilder<
1079
- RelaxIndexSignature<
1080
- OptionalDbEntityFields<
1081
- Override<
1082
- IN,
1083
- {
1084
- [K in keyof P]?: P[K] extends JsonSchemaAnyBuilder<infer IN2, any, any> ? IN2 : never
1085
- }
1086
- >
1087
- >
1088
- >,
1089
- Override<
1090
- OUT,
1091
- {
1092
- // required keys
1093
- [K in keyof P as P[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1094
- ? IsOpt extends true
1095
- ? never
1096
- : K
1097
- : never]: P[K] extends JsonSchemaAnyBuilder<any, infer OUT2, any> ? OUT2 : never
1098
- } & {
1099
- // optional keys
1100
- [K in keyof P as P[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1101
- ? IsOpt extends true
1102
- ? K
1103
- : never
1104
- : never]?: P[K] extends JsonSchemaAnyBuilder<any, infer OUT2, any> ? OUT2 : never
1105
- }
1106
- >,
1107
- false
1108
- > {
1109
- const newBuilder = new JsonSchemaObjectBuilder()
1110
- _objectAssign(newBuilder.schema, deepCopyPreservingFunctions(this.schema))
1111
-
1112
- const incomingSchemaBuilder = new JsonSchemaObjectBuilder(props)
1113
- mergeJsonSchemaObjects(newBuilder.schema as any, incomingSchemaBuilder.schema as any)
1114
-
1115
- _objectAssign(newBuilder.schema, { hasIsOfTypeCheck: false })
1116
-
1117
- return newBuilder as any
1118
- }
1119
-
1120
- /**
1121
- * Concatenates another schema to the current schema.
1122
- *
1123
- * It expects you to use `isOfType<T>()` in the chain,
1124
- * otherwise the validation will throw. This is to ensure
1125
- * that the schemas you concatenated match the intended final type.
1126
- *
1127
- * ```ts
1128
- * interface Foo { foo: string }
1129
- * const fooSchema = j.object<Foo>({ foo: j.string() })
1130
- *
1131
- * interface Bar { bar: number }
1132
- * const barSchema = j.object<Bar>({ bar: j.number() })
1133
- *
1134
- * interface Shu { foo: string, bar: number }
1135
- * const shuSchema = fooSchema.concat(barSchema).isOfType<Shu>() // important
1136
- * ```
1137
- */
1138
- concat<IN2 extends AnyObject, OUT2 extends AnyObject>(
1139
- other: JsonSchemaObjectBuilder<IN2, OUT2, any>,
1140
- ): JsonSchemaObjectBuilder<IN & IN2, OUT & OUT2, false> {
1141
- const clone = this.clone()
1142
- mergeJsonSchemaObjects(clone.schema as any, other.schema as any)
1143
- _objectAssign(clone.schema, { hasIsOfTypeCheck: false })
1144
- return clone as unknown as JsonSchemaObjectBuilder<IN & IN2, OUT & OUT2, false>
1145
- }
1146
-
1147
- /**
1148
- * Extends the current schema with `id`, `created` and `updated` according to NC DB conventions.
1149
- */
1150
- // oxlint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/explicit-module-boundary-types
1151
- dbEntity() {
1152
- return this.extend({
1153
- id: j.string(),
1154
- created: j.number().unixTimestamp2000(),
1155
- updated: j.number().unixTimestamp2000(),
1156
- })
1157
- }
1158
-
1159
- minProperties(minProperties: number): this {
1160
- return this.cloneAndUpdateSchema({ minProperties, minProperties2: minProperties })
1161
- }
1162
-
1163
- maxProperties(maxProperties: number): this {
1164
- return this.cloneAndUpdateSchema({ maxProperties })
1165
- }
1166
-
1167
- exclusiveProperties(propNames: readonly (keyof IN & string)[]): this {
1168
- const exclusiveProperties = this.schema.exclusiveProperties ?? []
1169
- return this.cloneAndUpdateSchema({ exclusiveProperties: [...exclusiveProperties, propNames] })
1170
- }
1171
- }
1172
-
1173
- interface JsonSchemaObjectBuilderOpts {
1174
- hasIsOfTypeCheck?: false
1175
- patternProperties?: StringMap<JsonSchema<any, any>>
1176
- keySchema?: JsonSchema
1177
- }
1178
-
1179
- export class JsonSchemaObjectInferringBuilder<
1180
- PROPS extends Record<string, JsonSchemaAnyBuilder<any, any, any>>,
1181
- Opt extends boolean = false,
1182
- > extends JsonSchemaAnyBuilder<
1183
- Expand<
1184
- {
1185
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1186
- ? IsOpt extends true
1187
- ? never
1188
- : K
1189
- : never]: PROPS[K] extends JsonSchemaAnyBuilder<infer IN, any, any> ? IN : never
1190
- } & {
1191
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1192
- ? IsOpt extends true
1193
- ? K
1194
- : never
1195
- : never]?: PROPS[K] extends JsonSchemaAnyBuilder<infer IN, any, any> ? IN : never
1196
- }
1197
- >,
1198
- Expand<
1199
- {
1200
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1201
- ? IsOpt extends true
1202
- ? never
1203
- : K
1204
- : never]: PROPS[K] extends JsonSchemaAnyBuilder<any, infer OUT, any> ? OUT : never
1205
- } & {
1206
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1207
- ? IsOpt extends true
1208
- ? K
1209
- : never
1210
- : never]?: PROPS[K] extends JsonSchemaAnyBuilder<any, infer OUT, any> ? OUT : never
1211
- }
1212
- >,
1213
- Opt
1214
- > {
1215
- constructor(props?: PROPS) {
1216
- super({
1217
- type: 'object',
1218
- properties: {},
1219
- required: [],
1220
- additionalProperties: false,
1221
- })
1222
-
1223
- if (props) this.addProperties(props)
1224
- }
1225
-
1226
- addProperties(props: PROPS): this {
1227
- const properties: Record<string, JsonSchema> = {}
1228
- const required: string[] = []
1229
-
1230
- for (const [key, builder] of Object.entries(props)) {
1231
- const isOptional = (builder as JsonSchemaTerminal<any, any, any>).getSchema().optionalField
1232
- if (!isOptional) {
1233
- required.push(key)
1234
- }
1235
-
1236
- const schema = builder.build()
1237
- properties[key] = schema
1238
- }
1239
-
1240
- this.schema.properties = properties
1241
- this.schema.required = _uniq(required).sort()
1242
-
1243
- return this
1244
- }
1245
-
1246
- /**
1247
- * @param nullValue Pass `null` to have `null` values be considered/converted as `undefined`.
1248
- *
1249
- * This `null` feature only works when the current schema is nested in an object or array schema,
1250
- * due to how mutability works in Ajv.
1251
- *
1252
- * When `null` is passed, the return type becomes `JsonSchemaTerminal`
1253
- * (no further chaining allowed) because the schema is wrapped in an anyOf structure.
1254
- */
1255
- // @ts-expect-error override adds optional parameter which is compatible but TS can't verify complex mapped types
1256
- override optional<N extends null | undefined = undefined>(
1257
- nullValue?: N,
1258
- ): N extends null
1259
- ? JsonSchemaTerminal<
1260
- | Expand<
1261
- {
1262
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1263
- ? IsOpt extends true
1264
- ? never
1265
- : K
1266
- : never]: PROPS[K] extends JsonSchemaAnyBuilder<infer IN, any, any> ? IN : never
1267
- } & {
1268
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1269
- ? IsOpt extends true
1270
- ? K
1271
- : never
1272
- : never]?: PROPS[K] extends JsonSchemaAnyBuilder<infer IN, any, any> ? IN : never
1273
- }
1274
- >
1275
- | undefined,
1276
- | Expand<
1277
- {
1278
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1279
- ? IsOpt extends true
1280
- ? never
1281
- : K
1282
- : never]: PROPS[K] extends JsonSchemaAnyBuilder<any, infer OUT, any> ? OUT : never
1283
- } & {
1284
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1285
- ? IsOpt extends true
1286
- ? K
1287
- : never
1288
- : never]?: PROPS[K] extends JsonSchemaAnyBuilder<any, infer OUT, any> ? OUT : never
1289
- }
1290
- >
1291
- | undefined,
1292
- true
1293
- >
1294
- : JsonSchemaAnyBuilder<
1295
- | Expand<
1296
- {
1297
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1298
- ? IsOpt extends true
1299
- ? never
1300
- : K
1301
- : never]: PROPS[K] extends JsonSchemaAnyBuilder<infer IN, any, any> ? IN : never
1302
- } & {
1303
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1304
- ? IsOpt extends true
1305
- ? K
1306
- : never
1307
- : never]?: PROPS[K] extends JsonSchemaAnyBuilder<infer IN, any, any> ? IN : never
1308
- }
1309
- >
1310
- | undefined,
1311
- | Expand<
1312
- {
1313
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1314
- ? IsOpt extends true
1315
- ? never
1316
- : K
1317
- : never]: PROPS[K] extends JsonSchemaAnyBuilder<any, infer OUT, any> ? OUT : never
1318
- } & {
1319
- [K in keyof PROPS as PROPS[K] extends JsonSchemaAnyBuilder<any, any, infer IsOpt>
1320
- ? IsOpt extends true
1321
- ? K
1322
- : never
1323
- : never]?: PROPS[K] extends JsonSchemaAnyBuilder<any, infer OUT, any> ? OUT : never
1324
- }
1325
- >
1326
- | undefined,
1327
- true
1328
- > {
1329
- if (nullValue === undefined) {
1330
- return super.optional() as any
1331
- }
1332
-
1333
- // When `null` is specified, we want `null` to be stripped and the value to become `undefined`,
1334
- // so we must allow `null` values to be parsed by Ajv,
1335
- // but the typing should not reflect that.
1336
- // We also cannot accept more rules attached, since we're not building an ObjectSchema anymore.
1337
- return new JsonSchemaTerminal({
1338
- anyOf: [{ type: 'null', optionalValues: [null] }, this.build()],
1339
- optionalField: true,
1340
- }) as any
1341
- }
1342
-
1343
- /**
1344
- * When set, the validation will not strip away properties that are not specified explicitly in the schema.
1345
- */
1346
-
1347
- allowAdditionalProperties(): this {
1348
- return this.cloneAndUpdateSchema({ additionalProperties: true })
1349
- }
1350
-
1351
- extend<NEW_PROPS extends Record<string, JsonSchemaAnyBuilder<any, any, any>>>(
1352
- props: NEW_PROPS,
1353
- ): JsonSchemaObjectInferringBuilder<
1354
- {
1355
- [K in keyof PROPS | keyof NEW_PROPS]: K extends keyof NEW_PROPS
1356
- ? NEW_PROPS[K]
1357
- : K extends keyof PROPS
1358
- ? PROPS[K]
1359
- : never
1360
- },
1361
- Opt
1362
- > {
1363
- const newBuilder = new JsonSchemaObjectInferringBuilder<PROPS, Opt>()
1364
- _objectAssign(newBuilder.schema, deepCopyPreservingFunctions(this.schema))
1365
-
1366
- const incomingSchemaBuilder = new JsonSchemaObjectInferringBuilder<NEW_PROPS, false>(props)
1367
- mergeJsonSchemaObjects(newBuilder.schema as any, incomingSchemaBuilder.schema as any)
1368
-
1369
- // This extend function is not type-safe as it is inferring,
1370
- // so even if the base schema was already type-checked,
1371
- // the new schema loses that quality.
1372
- _objectAssign(newBuilder.schema, { hasIsOfTypeCheck: false })
1373
-
1374
- return newBuilder as JsonSchemaObjectInferringBuilder<
1375
- {
1376
- [K in keyof PROPS | keyof NEW_PROPS]: K extends keyof NEW_PROPS
1377
- ? NEW_PROPS[K]
1378
- : K extends keyof PROPS
1379
- ? PROPS[K]
1380
- : never
1381
- },
1382
- Opt
1383
- >
1384
- }
1385
-
1386
- /**
1387
- * Extends the current schema with `id`, `created` and `updated` according to NC DB conventions.
1388
- */
1389
- // oxlint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/explicit-module-boundary-types
1390
- dbEntity() {
1391
- return this.extend({
1392
- id: j.string(),
1393
- created: j.number().unixTimestamp2000(),
1394
- updated: j.number().unixTimestamp2000(),
1395
- })
1396
- }
1397
- }
1398
-
1399
- export class JsonSchemaArrayBuilder<IN, OUT, Opt> extends JsonSchemaAnyBuilder<IN[], OUT[], Opt> {
1400
- constructor(itemsSchema: JsonSchemaAnyBuilder<IN, OUT, Opt>) {
1401
- super({
1402
- type: 'array',
1403
- items: itemsSchema.build(),
1404
- })
1405
- }
1406
-
1407
- minLength(minItems: number): this {
1408
- return this.cloneAndUpdateSchema({ minItems })
1409
- }
1410
-
1411
- maxLength(maxItems: number): this {
1412
- return this.cloneAndUpdateSchema({ maxItems })
1413
- }
1414
-
1415
- length(exactLength: number): this
1416
- length(minItems: number, maxItems: number): this
1417
- length(minItemsOrExact: number, maxItems?: number): this {
1418
- const maxItemsActual = maxItems ?? minItemsOrExact
1419
- return this.minLength(minItemsOrExact).maxLength(maxItemsActual)
1420
- }
1421
-
1422
- exactLength(length: number): this {
1423
- return this.minLength(length).maxLength(length)
1424
- }
1425
-
1426
- unique(): this {
1427
- return this.cloneAndUpdateSchema({ uniqueItems: true })
1428
- }
1429
- }
1430
-
1431
- export class JsonSchemaSet2Builder<IN, OUT, Opt> extends JsonSchemaAnyBuilder<
1432
- Iterable<IN>,
1433
- Set2<OUT>,
1434
- Opt
1435
- > {
1436
- constructor(itemsSchema: JsonSchemaAnyBuilder<IN, OUT, Opt>) {
1437
- super({
1438
- type: ['array', 'object'],
1439
- Set2: itemsSchema.build(),
1440
- })
1441
- }
1442
-
1443
- min(minItems: number): this {
1444
- return this.cloneAndUpdateSchema({ minItems })
1445
- }
1446
-
1447
- max(maxItems: number): this {
1448
- return this.cloneAndUpdateSchema({ maxItems })
1449
- }
1450
- }
1451
-
1452
- export class JsonSchemaBufferBuilder extends JsonSchemaAnyBuilder<
1453
- string | any[] | ArrayBuffer | Buffer,
1454
- Buffer,
1455
- false
1456
- > {
1457
- constructor() {
1458
- super({
1459
- Buffer: true,
1460
- })
1461
- }
1462
- }
1463
-
1464
- export class JsonSchemaEnumBuilder<
1465
- IN extends string | number | boolean | null,
1466
- OUT extends IN = IN,
1467
- Opt extends boolean = false,
1468
- > extends JsonSchemaAnyBuilder<IN, OUT, Opt> {
1469
- constructor(enumValues: readonly IN[], baseType: EnumBaseType, opt?: JsonBuilderRuleOpt) {
1470
- const jsonSchema: JsonSchema = { enum: enumValues }
1471
- // Specifying the base type helps in cases when we ask Ajv to coerce the types.
1472
- // Having only the `enum` in the schema does not trigger a coercion in Ajv.
1473
- if (baseType === 'string') jsonSchema.type = 'string'
1474
- if (baseType === 'number') jsonSchema.type = 'number'
1475
-
1476
- super(jsonSchema)
1477
-
1478
- if (opt?.name) this.setErrorMessage('pattern', `is not a valid ${opt.name}`)
1479
- if (opt?.msg) this.setErrorMessage('enum', opt.msg)
1480
- }
1481
-
1482
- branded<B extends IN>(): JsonSchemaEnumBuilder<B | IN, B, Opt> {
1483
- return this as unknown as JsonSchemaEnumBuilder<B | IN, B, Opt>
1484
- }
1485
- }
1486
-
1487
- export class JsonSchemaTupleBuilder<
1488
- ITEMS extends JsonSchemaAnyBuilder<any, any, any>[],
1489
- > extends JsonSchemaAnyBuilder<TupleIn<ITEMS>, TupleOut<ITEMS>, false> {
1490
- private readonly _items: ITEMS
1491
-
1492
- constructor(items: ITEMS) {
1493
- super({
1494
- type: 'array',
1495
- prefixItems: items.map(i => i.build()),
1496
- minItems: items.length,
1497
- maxItems: items.length,
1498
- })
1499
-
1500
- this._items = items
1501
- }
1502
- }
1503
-
1504
- export class JsonSchemaAnyOfByBuilder<
1505
- IN,
1506
- OUT,
1507
- // eslint-disable-next-line @typescript-eslint/naming-convention
1508
- _P extends string = string,
1509
- > extends JsonSchemaAnyBuilder<AnyOfByInput<IN, _P> | IN, OUT, false> {
1510
- declare in: IN
1511
-
1512
- constructor(
1513
- propertyName: string,
1514
- schemaDictionary: Record<PropertyKey, JsonSchemaTerminal<any, any, any>>,
1515
- ) {
1516
- const builtSchemaDictionary: Record<string, JsonSchema> = {}
1517
- for (const [key, schema] of Object.entries(schemaDictionary)) {
1518
- builtSchemaDictionary[key] = schema.build()
1519
- }
1520
-
1521
- super({
1522
- type: 'object',
1523
- hasIsOfTypeCheck: true,
1524
- anyOfBy: {
1525
- propertyName,
1526
- schemaDictionary: builtSchemaDictionary,
1527
- },
1528
- })
1529
- }
1530
- }
1531
-
1532
- export class JsonSchemaAnyOfTheseBuilder<
1533
- IN,
1534
- OUT,
1535
- // eslint-disable-next-line @typescript-eslint/naming-convention
1536
- _P extends string = string,
1537
- > extends JsonSchemaAnyBuilder<AnyOfByInput<IN, _P> | IN, OUT, false> {
1538
- declare in: IN
1539
-
1540
- constructor(
1541
- propertyName: string,
1542
- schemaDictionary: Record<PropertyKey, JsonSchemaTerminal<any, any, any>>,
1543
- ) {
1544
- const builtSchemaDictionary: Record<string, JsonSchema> = {}
1545
- for (const [key, schema] of Object.entries(schemaDictionary)) {
1546
- builtSchemaDictionary[key] = schema.build()
1547
- }
1548
-
1549
- super({
1550
- type: 'object',
1551
- hasIsOfTypeCheck: true,
1552
- anyOfBy: {
1553
- propertyName,
1554
- schemaDictionary: builtSchemaDictionary,
1555
- },
1556
- })
1557
- }
1558
- }
1559
-
1560
- type EnumBaseType = 'string' | 'number' | 'other'
1561
-
1562
- export interface JsonSchema<IN = unknown, OUT = IN> {
1563
- readonly in?: IN
1564
- readonly out?: OUT
1565
-
1566
- $schema?: string
1567
- $id?: string
1568
- title?: string
1569
- description?: string
1570
- // $comment?: string
1571
- deprecated?: boolean
1572
- readOnly?: boolean
1573
- writeOnly?: boolean
1574
-
1575
- type?: string | string[]
1576
- items?: JsonSchema
1577
- prefixItems?: JsonSchema[]
1578
- properties?: {
1579
- [K in keyof IN & keyof OUT]: JsonSchema<IN[K], OUT[K]>
1580
- }
1581
- patternProperties?: StringMap<JsonSchema<any, any>>
1582
- required?: string[]
1583
- additionalProperties?: boolean
1584
- minProperties?: number
1585
- maxProperties?: number
1586
-
1587
- default?: IN
1588
-
1589
- // https://json-schema.org/understanding-json-schema/reference/conditionals.html#id6
1590
- if?: JsonSchema
1591
- then?: JsonSchema
1592
- else?: JsonSchema
1593
-
1594
- anyOf?: JsonSchema[]
1595
- oneOf?: JsonSchema[]
1596
-
1597
- /**
1598
- * This is a temporary "intermediate AST" field that is used inside the parser.
1599
- * In the final schema this field will NOT be present.
1600
- */
1601
- optionalField?: true
1602
-
1603
- pattern?: string
1604
- minLength?: number
1605
- maxLength?: number
1606
- format?: string
1607
-
1608
- contentMediaType?: string
1609
- contentEncoding?: string // e.g 'base64'
1610
-
1611
- multipleOf?: number
1612
- minimum?: number
1613
- exclusiveMinimum?: number
1614
- maximum?: number
1615
- exclusiveMaximum?: number
1616
- minItems?: number
1617
- maxItems?: number
1618
- uniqueItems?: boolean
1619
-
1620
- enum?: any
1621
-
1622
- hasIsOfTypeCheck?: boolean
1623
-
1624
- // Below we add custom Ajv keywords
1625
-
1626
- email?: JsonSchemaStringEmailOptions
1627
- Set2?: JsonSchema
1628
- Buffer?: true
1629
- IsoDate?: JsonSchemaIsoDateOptions
1630
- IsoDateTime?: true
1631
- IsoMonth?: JsonSchemaIsoMonthOptions
1632
- instanceof?: string | string[]
1633
- transform?: { trim?: true; toLowerCase?: true; toUpperCase?: true; truncate?: number }
1634
- errorMessages?: StringMap<string>
1635
- optionalValues?: (string | number | boolean | null)[]
1636
- keySchema?: JsonSchema
1637
- isUndefined?: true
1638
- minProperties2?: number
1639
- exclusiveProperties?: (readonly string[])[]
1640
- anyOfBy?: {
1641
- propertyName: string
1642
- schemaDictionary: Record<string, JsonSchema>
1643
- }
1644
- anyOfThese?: JsonSchema[]
1645
- precision?: number
1646
- customValidations?: CustomValidatorFn[]
1647
- customConversions?: CustomConverterFn<any>[]
1648
- }
1649
-
1650
- function object(props: AnyObject): never
1651
- function object<IN extends AnyObject>(props: {
1652
- [K in keyof Required<IN>]-?: JsonSchemaTerminal<any, IN[K], any>
1653
- }): JsonSchemaObjectBuilder<IN, IN, false>
1654
-
1655
- function object<IN extends AnyObject>(props: {
1656
- [key in keyof IN]: JsonSchemaTerminal<any, IN[key], any>
1657
- }): JsonSchemaObjectBuilder<IN, IN, false> {
1658
- return new JsonSchemaObjectBuilder<IN, IN, false>(props)
1659
- }
1660
-
1661
- function objectInfer<P extends Record<string, JsonSchemaAnyBuilder<any, any, any>>>(
1662
- props: P,
1663
- ): JsonSchemaObjectInferringBuilder<P, false> {
1664
- return new JsonSchemaObjectInferringBuilder<P, false>(props)
1665
- }
1666
-
1667
- function objectDbEntity(props: AnyObject): never
1668
- function objectDbEntity<
1669
- IN extends BaseDBEntity,
1670
- EXTRA_KEYS extends Exclude<keyof IN, keyof BaseDBEntity> = Exclude<keyof IN, keyof BaseDBEntity>,
1671
- >(
1672
- props: {
1673
- // ✅ all non-system fields must be explicitly provided
1674
- [K in EXTRA_KEYS]-?: BuilderFor<IN[K]>
1675
- } &
1676
- // ✅ if `id` differs, it’s required
1677
- (ExactMatch<IN['id'], BaseDBEntity['id']> extends true
1678
- ? { id?: BuilderFor<BaseDBEntity['id']> }
1679
- : { id: BuilderFor<IN['id']> }) &
1680
- (ExactMatch<IN['created'], BaseDBEntity['created']> extends true
1681
- ? { created?: BuilderFor<BaseDBEntity['created']> }
1682
- : { created: BuilderFor<IN['created']> }) &
1683
- (ExactMatch<IN['updated'], BaseDBEntity['updated']> extends true
1684
- ? { updated?: BuilderFor<BaseDBEntity['updated']> }
1685
- : { updated: BuilderFor<IN['updated']> }),
1686
- ): JsonSchemaObjectBuilder<IN, IN, false>
1687
-
1688
- function objectDbEntity(props: AnyObject): any {
1689
- return j.object({
1690
- id: j.string(),
1691
- created: j.number().unixTimestamp2000(),
1692
- updated: j.number().unixTimestamp2000(),
1693
- ...props,
1694
- })
1695
- }
1696
-
1697
- function record<
1698
- KS extends JsonSchemaAnyBuilder<any, any, any>,
1699
- VS extends JsonSchemaAnyBuilder<any, any, any>,
1700
- Opt extends boolean = SchemaOpt<VS>,
1701
- >(
1702
- keySchema: KS,
1703
- valueSchema: VS,
1704
- ): JsonSchemaObjectBuilder<
1705
- Opt extends true
1706
- ? Partial<Record<SchemaIn<KS>, SchemaIn<VS>>>
1707
- : Record<SchemaIn<KS>, SchemaIn<VS>>,
1708
- Opt extends true
1709
- ? Partial<Record<SchemaOut<KS>, SchemaOut<VS>>>
1710
- : Record<SchemaOut<KS>, SchemaOut<VS>>,
1711
- false
1712
- > {
1713
- const keyJsonSchema = keySchema.build()
1714
- // Check if value schema is optional before build() strips the optionalField flag
1715
- const isValueOptional = (valueSchema as JsonSchemaTerminal<any, any, any>).getSchema()
1716
- .optionalField
1717
- const valueJsonSchema = valueSchema.build()
1718
-
1719
- // When value schema is optional, wrap in anyOf to allow undefined values
1720
- const finalValueSchema: JsonSchema = isValueOptional
1721
- ? { anyOf: [{ isUndefined: true }, valueJsonSchema] }
1722
- : valueJsonSchema
1723
-
1724
- return new JsonSchemaObjectBuilder<
1725
- Opt extends true
1726
- ? Partial<Record<SchemaIn<KS>, SchemaIn<VS>>>
1727
- : Record<SchemaIn<KS>, SchemaIn<VS>>,
1728
- Opt extends true
1729
- ? Partial<Record<SchemaOut<KS>, SchemaOut<VS>>>
1730
- : Record<SchemaOut<KS>, SchemaOut<VS>>,
1731
- false
1732
- >([], {
1733
- hasIsOfTypeCheck: false,
1734
- keySchema: keyJsonSchema,
1735
- patternProperties: {
1736
- ['^.*$']: finalValueSchema,
1737
- },
1738
- })
1739
- }
1740
-
1741
- function withRegexKeys<
1742
- S extends JsonSchemaAnyBuilder<any, any, any>,
1743
- Opt extends boolean = SchemaOpt<S>,
1744
- >(
1745
- keyRegex: RegExp | string,
1746
- schema: S,
1747
- ): JsonSchemaObjectBuilder<
1748
- Opt extends true ? StringMap<SchemaIn<S>> : StringMap<SchemaIn<S>>,
1749
- Opt extends true ? StringMap<SchemaOut<S>> : StringMap<SchemaOut<S>>,
1750
- false
1751
- > {
1752
- if (keyRegex instanceof RegExp) {
1753
- _assert(
1754
- !keyRegex.flags,
1755
- `Regex flags are not supported by JSON Schema. Received: /${keyRegex.source}/${keyRegex.flags}`,
1756
- )
1757
- }
1758
- const pattern = keyRegex instanceof RegExp ? keyRegex.source : keyRegex
1759
- const jsonSchema = schema.build()
1760
-
1761
- return new JsonSchemaObjectBuilder<
1762
- Opt extends true ? StringMap<SchemaIn<S>> : StringMap<SchemaIn<S>>,
1763
- Opt extends true ? StringMap<SchemaOut<S>> : StringMap<SchemaOut<S>>,
1764
- false
1765
- >([], {
1766
- hasIsOfTypeCheck: false,
1767
- patternProperties: {
1768
- [pattern]: jsonSchema,
1769
- },
1770
- })
1771
- }
1772
-
1773
- /**
1774
- * Builds the object schema with the indicated `keys` and uses the `schema` for their validation.
1775
- */
1776
- function withEnumKeys<
1777
- const T extends readonly (string | number)[] | StringEnum | NumberEnum,
1778
- S extends JsonSchemaAnyBuilder<any, any, any>,
1779
- K extends string | number = EnumKeyUnion<T>,
1780
- Opt extends boolean = SchemaOpt<S>,
1781
- >(
1782
- keys: T,
1783
- schema: S,
1784
- ): JsonSchemaObjectBuilder<
1785
- Opt extends true ? { [P in K]?: SchemaIn<S> } : { [P in K]: SchemaIn<S> },
1786
- Opt extends true ? { [P in K]?: SchemaOut<S> } : { [P in K]: SchemaOut<S> },
1787
- false
1788
- > {
1789
- let enumValues: readonly (string | number)[] | undefined
1790
- if (Array.isArray(keys)) {
1791
- _assert(
1792
- isEveryItemPrimitive(keys),
1793
- 'Every item in the key list should be string, number or symbol',
1794
- )
1795
- enumValues = keys
1796
- } else if (typeof keys === 'object') {
1797
- const enumType = getEnumType(keys)
1798
- _assert(
1799
- enumType === 'NumberEnum' || enumType === 'StringEnum',
1800
- 'The key list should be StringEnum or NumberEnum',
1801
- )
1802
- if (enumType === 'NumberEnum') {
1803
- enumValues = _numberEnumValues(keys as NumberEnum)
1804
- } else if (enumType === 'StringEnum') {
1805
- enumValues = _stringEnumValues(keys as StringEnum)
1806
- }
1807
- }
1808
-
1809
- _assert(enumValues, 'The key list should be an array of values, NumberEnum or a StringEnum')
1810
-
1811
- const typedValues = enumValues as readonly K[]
1812
- const props = Object.fromEntries(typedValues.map(key => [key, schema])) as any
1813
-
1814
- return new JsonSchemaObjectBuilder<
1815
- Opt extends true ? { [P in K]?: SchemaIn<S> } : { [P in K]: SchemaIn<S> },
1816
- Opt extends true ? { [P in K]?: SchemaOut<S> } : { [P in K]: SchemaOut<S> },
1817
- false
1818
- >(props, { hasIsOfTypeCheck: false })
1819
- }
1820
-
1821
- function hasNoObjectSchemas(schema: JsonSchema): boolean {
1822
- if (Array.isArray(schema.type)) {
1823
- schema.type.every(type => ['string', 'number', 'integer', 'boolean', 'null'].includes(type))
1824
- } else if (schema.anyOf) {
1825
- return schema.anyOf.every(hasNoObjectSchemas)
1826
- } else if (schema.oneOf) {
1827
- return schema.oneOf.every(hasNoObjectSchemas)
1828
- } else if (schema.enum) {
1829
- return true
1830
- } else if (schema.type === 'array') {
1831
- return !schema.items || hasNoObjectSchemas(schema.items)
1832
- } else {
1833
- return !!schema.type && ['string', 'number', 'integer', 'boolean', 'null'].includes(schema.type)
1834
- }
1835
-
1836
- return false
1837
- }
1838
-
1839
- type Expand<T> = { [K in keyof T]: T[K] }
1840
-
1841
- type StripIndexSignatureDeep<T> = T extends readonly unknown[]
1842
- ? T
1843
- : T extends Record<string, any>
1844
- ? {
1845
- [K in keyof T as string extends K
1846
- ? never
1847
- : number extends K
1848
- ? never
1849
- : symbol extends K
1850
- ? never
1851
- : K]: StripIndexSignatureDeep<T[K]>
1852
- }
1853
- : T
1854
-
1855
- type RelaxIndexSignature<T> = T extends readonly unknown[]
1856
- ? T
1857
- : T extends AnyObject
1858
- ? { [K in keyof T]: RelaxIndexSignature<T[K]> }
1859
- : T
1860
-
1861
- type Override<T, U> = Omit<T, keyof U> & U
1862
-
1863
- declare const allowExtraKeysSymbol: unique symbol
1864
-
1865
- type HasAllowExtraKeys<T> = T extends { readonly [allowExtraKeysSymbol]?: true } ? true : false
1866
-
1867
- type IsAny<T> = 0 extends 1 & T ? true : false
1868
-
1869
- type IsAssignableRelaxed<A, B> =
1870
- IsAny<RelaxIndexSignature<A>> extends true
1871
- ? true
1872
- : [RelaxIndexSignature<A>] extends [B]
1873
- ? true
1874
- : false
1875
-
1876
- type OptionalDbEntityFields<T> = T extends BaseDBEntity
1877
- ? Omit<T, keyof BaseDBEntity> & Partial<Pick<T, keyof BaseDBEntity>>
1878
- : T
1879
-
1880
- type ExactMatchBase<A, B> =
1881
- (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2
1882
- ? (<T>() => T extends B ? 1 : 2) extends <T>() => T extends A ? 1 : 2
1883
- ? true
1884
- : false
1885
- : false
1886
-
1887
- type ExactMatch<A, B> =
1888
- HasAllowExtraKeys<B> extends true
1889
- ? IsAssignableRelaxed<B, A>
1890
- : ExactMatchBase<Expand<A>, Expand<B>> extends true
1891
- ? true
1892
- : ExactMatchBase<Expand<StripIndexSignatureDeep<A>>, Expand<StripIndexSignatureDeep<B>>>
1893
-
1894
- type BuilderOutUnion<B extends readonly JsonSchemaAnyBuilder<any, any, any>[]> = {
1895
- [K in keyof B]: B[K] extends JsonSchemaAnyBuilder<any, infer O, any> ? O : never
1896
- }[number]
1897
-
1898
- type BuilderInUnion<B extends readonly JsonSchemaAnyBuilder<any, any, any>[]> = {
1899
- [K in keyof B]: B[K] extends JsonSchemaAnyBuilder<infer I, any, any> ? I : never
1900
- }[number]
1901
-
1902
- type AnyOfByIn<D extends Record<PropertyKey, JsonSchemaTerminal<any, any, any>>> = {
1903
- [K in keyof D]: D[K] extends JsonSchemaTerminal<infer I, any, any> ? I : never
1904
- }[keyof D]
1905
-
1906
- type AnyOfByOut<D extends Record<PropertyKey, JsonSchemaTerminal<any, any, any>>> = {
1907
- [K in keyof D]: D[K] extends JsonSchemaTerminal<any, infer O, any> ? O : never
1908
- }[keyof D]
1909
-
1910
- type AnyOfByDiscriminant<IN, P extends string> = IN extends { [K in P]: infer V } ? V : never
1911
-
1912
- type AnyOfByInput<IN, P extends string, D = AnyOfByDiscriminant<IN, P>> = IN extends unknown
1913
- ? Omit<Partial<IN>, P> & { [K in P]?: D }
1914
- : never
1915
-
1916
- type BuilderFor<T> = JsonSchemaAnyBuilder<any, T, any>
1917
-
1918
- interface JsonBuilderRuleOpt {
1919
- /**
1920
- * Text of error message to return when the validation fails for the given rule:
1921
- *
1922
- * `{ msg: "is not a valid Oompa-loompa" } => "Object.property is not a valid Oompa-loompa"`
1923
- */
1924
- msg?: string
1925
- /**
1926
- * A friendly name for what we are validating, that will be used in error messages:
1927
- *
1928
- * `{ name: "Oompa-loompa" } => "Object.property is not a valid Oompa-loompa"`
1929
- */
1930
- name?: string
1931
- }
1932
-
1933
- type EnumKeyUnion<T> =
1934
- // array of literals -> union of its elements
1935
- T extends readonly (infer U)[]
1936
- ? U
1937
- : // enum object -> union of its values
1938
- T extends StringEnum | NumberEnum
1939
- ? T[keyof T]
1940
- : never
1941
-
1942
- type SchemaIn<S> = S extends JsonSchemaAnyBuilder<infer IN, any, any> ? IN : never
1943
- type SchemaOut<S> = S extends JsonSchemaAnyBuilder<any, infer OUT, any> ? OUT : never
1944
- type SchemaOpt<S> =
1945
- S extends JsonSchemaAnyBuilder<any, any, infer Opt> ? (Opt extends true ? true : false) : false
1946
-
1947
- type TupleIn<T extends readonly JsonSchemaAnyBuilder<any, any, any>[]> = {
1948
- [K in keyof T]: T[K] extends JsonSchemaAnyBuilder<infer I, any, any> ? I : never
1949
- }
1950
-
1951
- type TupleOut<T extends readonly JsonSchemaAnyBuilder<any, any, any>[]> = {
1952
- [K in keyof T]: T[K] extends JsonSchemaAnyBuilder<any, infer O, any> ? O : never
1953
- }
1954
-
1955
- export type CustomValidatorFn = (v: any) => string | undefined
1956
- export type CustomConverterFn<OUT> = (v: any) => OUT
1957
-
1958
- /**
1959
- * Deep copy that preserves functions in customValidations/customConversions.
1960
- * Unlike structuredClone, this handles function references (which only exist in those two properties).
1961
- */
1962
- function deepCopyPreservingFunctions<T>(obj: T): T {
1963
- if (obj === null || typeof obj !== 'object') return obj
1964
- if (Array.isArray(obj)) return obj.map(deepCopyPreservingFunctions) as T
1965
- const copy = {} as T
1966
- for (const key of Object.keys(obj)) {
1967
- const value = (obj as any)[key]
1968
- // customValidations/customConversions are arrays of functions - shallow copy the array
1969
- ;(copy as any)[key] =
1970
- (key === 'customValidations' || key === 'customConversions') && Array.isArray(value)
1971
- ? [...value]
1972
- : deepCopyPreservingFunctions(value)
1973
- }
1974
- return copy
1975
- }