-
Notifications
You must be signed in to change notification settings - Fork 152
/
typebox.ts
2773 lines (2762 loc) · 133 KB
/
typebox.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*--------------------------------------------------------------------------
@sinclair/typebox
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
// --------------------------------------------------------------------------
// Symbols
// --------------------------------------------------------------------------
export const Modifier = Symbol.for('TypeBox.Modifier')
export const Hint = Symbol.for('TypeBox.Hint')
export const Kind = Symbol.for('TypeBox.Kind')
// --------------------------------------------------------------------------
// Patterns
// --------------------------------------------------------------------------
export const PatternBoolean = '(true|false)'
export const PatternNumber = '(0|[1-9][0-9]*)'
export const PatternString = '(.*)'
export const PatternBooleanExact = `^${PatternBoolean}$`
export const PatternNumberExact = `^${PatternNumber}$`
export const PatternStringExact = `^${PatternString}$`
// --------------------------------------------------------------------------
// Helpers
// --------------------------------------------------------------------------
export type TupleToIntersect<T extends any[]> = T extends [infer I] ? I : T extends [infer I, ...infer R] ? I & TupleToIntersect<R> : never
export type TupleToUnion<T extends any[]> = { [K in keyof T]: T[K] }[number]
export type UnionToIntersect<U> = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never
export type UnionLast<U> = UnionToIntersect<U extends unknown ? (x: U) => 0 : never> extends (x: infer L) => 0 ? L : never
export type UnionToTuple<U, L = UnionLast<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, L>>, L]
export type Assert<T, E> = T extends E ? T : never
export type Evaluate<T> = T extends infer O ? { [K in keyof O]: O[K] } : never
export type Ensure<T> = T extends infer U ? U : never
// --------------------------------------------------------------------------
// Type Assertions
// --------------------------------------------------------------------------
export type AssertProperties<T> = T extends TProperties ? T : TProperties
export type AssertRest<T, E extends TSchema[] = TSchema[]> = T extends E ? T : []
export type AssertType<T, E extends TSchema = TSchema> = T extends E ? T : TNever
// --------------------------------------------------------------------------
// Type Normalization
// --------------------------------------------------------------------------
export type IntersectType<T extends TSchema[]> = T extends [] ? TNever : T extends [TSchema] ? AssertType<T[0]> : TIntersect<T>
export type UnionType<T extends TSchema[]> = T extends [] ? TNever : T extends [TSchema] ? AssertType<T[0]> : TUnion<T>
// --------------------------------------------------------------------------
// Modifiers
// --------------------------------------------------------------------------
export type TModifier = TReadonlyOptional<TSchema> | TOptional<TSchema> | TReadonly<TSchema>
export type TReadonly<T extends TSchema> = T & { [Modifier]: 'Readonly' }
export type TOptional<T extends TSchema> = T & { [Modifier]: 'Optional' }
export type TReadonlyOptional<T extends TSchema> = T & { [Modifier]: 'ReadonlyOptional' }
// --------------------------------------------------------------------------
// Key
// --------------------------------------------------------------------------
export type Key = string | number
// --------------------------------------------------------------------------
// TSchema
// --------------------------------------------------------------------------
export interface SchemaOptions {
$schema?: string
/** Id for this schema */
$id?: string
/** Title of this schema */
title?: string
/** Description of this schema */
description?: string
/** Default value for this schema */
default?: any
/** Example values matching this schema */
examples?: any
[prop: string]: any
}
export interface TKind {
[Kind]: string
}
export interface TSchema extends SchemaOptions, TKind {
[Modifier]?: string
[Hint]?: string
params: unknown[]
static: unknown
}
// --------------------------------------------------------------------------
// TAnySchema
// --------------------------------------------------------------------------
export type TAnySchema =
| TSchema
| TAny
| TArray
| TBigInt
| TBoolean
| TConstructor
| TDate
| TEnum
| TFunction
| TInteger
| TIntersect
| TLiteral
| TNot
| TNull
| TNumber
| TObject
| TPromise
| TRecord
| TRef
| TString
| TSymbol
| TTemplateLiteral
| TThis
| TTuple
| TUndefined
| TUnion
| TUint8Array
| TUnknown
| TVoid
// --------------------------------------------------------------------------
// TNumeric
// --------------------------------------------------------------------------
export interface NumericOptions<N extends number | bigint> extends SchemaOptions {
exclusiveMaximum?: N
exclusiveMinimum?: N
maximum?: N
minimum?: N
multipleOf?: N
}
// --------------------------------------------------------------------------
// TAny
// --------------------------------------------------------------------------
export interface TAny extends TSchema {
[Kind]: 'Any'
static: any
}
// --------------------------------------------------------------------------
// TArray
// --------------------------------------------------------------------------
export interface ArrayOptions extends SchemaOptions {
uniqueItems?: boolean
minItems?: number
maxItems?: number
}
export interface TArray<T extends TSchema = TSchema> extends TSchema, ArrayOptions {
[Kind]: 'Array'
static: Static<T, this['params']>[]
type: 'array'
items: T
}
// --------------------------------------------------------------------------
// TBigInt
// --------------------------------------------------------------------------
export interface TBigInt extends TSchema, NumericOptions<bigint> {
[Kind]: 'BigInt'
static: bigint
type: 'null'
typeOf: 'BigInt'
}
// --------------------------------------------------------------------------
// TBoolean
// --------------------------------------------------------------------------
export interface TBoolean extends TSchema {
[Kind]: 'Boolean'
static: boolean
type: 'boolean'
}
// --------------------------------------------------------------------------
// TConstructorParameters
// --------------------------------------------------------------------------
export type TConstructorParameters<T extends TConstructor<TSchema[], TSchema>> = TTuple<T['parameters']>
// --------------------------------------------------------------------------
// TInstanceType
// --------------------------------------------------------------------------
export type TInstanceType<T extends TConstructor<TSchema[], TSchema>> = T['returns']
// --------------------------------------------------------------------------
// TComposite
// --------------------------------------------------------------------------
export type TCompositeIsOptional<T extends TSchema> = T extends TOptional<T> | TReadonlyOptional<T> ? true : false
// prettier-ignore
export type TCompositeOptional<T extends TSchema[]> = T extends [infer L, ...infer R]
? TCompositeIsOptional<AssertType<L>> extends false ? false
: TCompositeOptional<AssertRest<R>> : true
export type TCompositeKeyOfUnion1<T extends TObject> = keyof T['properties']
// prettier-ignore
export type TCompositeKeyOfUnion2<T extends TObject[]> = T extends [infer L, ...infer R]
? TCompositeKeyOfUnion1<Assert<L, TObject>> | TCompositeKeyOfUnion2<Assert<R, TObject[]>>
: never
export type TCompositeKeyOf<T extends TObject[]> = UnionToTuple<TCompositeKeyOfUnion2<T>>
export type TCompositePropertiesWithKey1<T extends TObject, K extends Key> = K extends keyof T['properties'] ? [T['properties'][K]] : []
// prettier-ignore
export type TCompositePropertiesWithKey2<T extends TObject[], K extends Key> = T extends [infer L, ...infer R]
? [...TCompositePropertiesWithKey1<Assert<L, TObject>, K>, ...TCompositePropertiesWithKey2<Assert<R, TObject[]>, K>]
: []
// prettier-ignore
export type TCompositeObjectProperty<T extends TObject[], K extends Key> = TCompositePropertiesWithKey2<T, K> extends infer S ?
TCompositeOptional<AssertRest<S>> extends true
? { [_ in K]: TOptional<IntersectType<AssertRest<S>>> }
: { [_ in K]: IntersectType<AssertRest<S>> }
: {}
// prettier-ignore
export type TCompositeObjectsWithKeys<T extends TObject[], K extends Key[]> = K extends [infer L, ...infer R] ? L extends Key
? TCompositeObjectProperty<T, L> & TCompositeObjectsWithKeys<T, Assert<R, Key[]>>
: {}
: {}
export type TComposite<T extends TObject[]> = Ensure<TObject<Evaluate<TCompositeObjectsWithKeys<T, Assert<TCompositeKeyOf<T>, Key[]>>>>>
// --------------------------------------------------------------------------
// TConstructor
// --------------------------------------------------------------------------
export type TConstructorParameterArray<T extends readonly TSchema[], P extends unknown[]> = [...{ [K in keyof T]: Static<AssertType<T[K]>, P> }]
export interface TConstructor<T extends TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Constructor'
static: new (...param: TConstructorParameterArray<T, this['params']>) => Static<U, this['params']>
type: 'object'
instanceOf: 'Constructor'
parameters: T
returns: U
}
// --------------------------------------------------------------------------
// TDate
// --------------------------------------------------------------------------
export interface DateOptions extends SchemaOptions {
exclusiveMaximumTimestamp?: number
exclusiveMinimumTimestamp?: number
maximumTimestamp?: number
minimumTimestamp?: number
}
export interface TDate extends TSchema, DateOptions {
[Kind]: 'Date'
static: Date
type: 'object'
instanceOf: 'Date'
}
// --------------------------------------------------------------------------
// TEnum
// --------------------------------------------------------------------------
export interface TEnumOption<T> {
type: 'number' | 'string'
const: T
}
export interface TEnum<T extends Record<string, string | number> = Record<string, string | number>> extends TSchema {
[Kind]: 'Union'
static: T[keyof T]
anyOf: TLiteral<string | number>[]
}
// --------------------------------------------------------------------------
// TExtends
// --------------------------------------------------------------------------
// prettier-ignore
export type TExtends<L extends TSchema, R extends TSchema, T extends TSchema, U extends TSchema> =
(Static<L> extends Static<R> ? T : U) extends infer O ?
UnionToTuple<O> extends [infer X, infer Y] ? TUnion<[AssertType<X>, AssertType<Y>]> : AssertType<O>
: never
// --------------------------------------------------------------------------
// TExclude
// --------------------------------------------------------------------------
export type TExcludeTemplateLiteralResult<T extends string> = UnionType<AssertRest<UnionToTuple<{ [K in T]: TLiteral<K> }[T]>>>
export type TExcludeTemplateLiteral<T extends TTemplateLiteral, U extends TSchema> = Exclude<Static<T>, Static<U>> extends infer S ? TExcludeTemplateLiteralResult<Assert<S, string>> : never
// prettier-ignore
export type TExcludeArray<T extends TSchema[], U extends TSchema> = AssertRest<UnionToTuple<{
[K in keyof T]: Static<AssertType<T[K]>> extends Static<U> ? never : T[K]
}[number]>> extends infer R ? UnionType<AssertRest<R>> : never
// prettier-ignore
export type TExclude<T extends TSchema, U extends TSchema> =
T extends TTemplateLiteral ? TExcludeTemplateLiteral<T, U> :
T extends TUnion<infer S> ? TExcludeArray<S, U> :
T extends U ? TNever : T
// --------------------------------------------------------------------------
// TExtract
// --------------------------------------------------------------------------
export type TExtractTemplateLiteralResult<T extends string> = UnionType<AssertRest<UnionToTuple<{ [K in T]: TLiteral<K> }[T]>>>
export type TExtractTemplateLiteral<T extends TTemplateLiteral, U extends TSchema> = Extract<Static<T>, Static<U>> extends infer S ? TExtractTemplateLiteralResult<Assert<S, string>> : never
// prettier-ignore
export type TExtractArray<T extends TSchema[], U extends TSchema> = AssertRest<UnionToTuple<
{[K in keyof T]: Static<AssertType<T[K]>> extends Static<U> ? T[K] : never
}[number]>> extends infer R ? UnionType<AssertRest<R>> : never
// prettier-ignore
export type TExtract<T extends TSchema, U extends TSchema> =
T extends TTemplateLiteral ? TExtractTemplateLiteral<T, U> :
T extends TUnion<infer S> ? TExtractArray<S, U> :
T extends U ? T : T
// --------------------------------------------------------------------------
// TFunction
// --------------------------------------------------------------------------
export type TFunctionParameters<T extends readonly TSchema[], P extends unknown[]> = [...{ [K in keyof T]: Static<AssertType<T[K]>, P> }]
export interface TFunction<T extends readonly TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Function'
static: (...param: TFunctionParameters<T, this['params']>) => Static<U, this['params']>
type: 'object'
instanceOf: 'Function'
parameters: T
returns: U
}
// --------------------------------------------------------------------------
// TIndex
// --------------------------------------------------------------------------
// prettier-ignore
export type TIndexProperty<T extends TProperties, K extends Key> =
T[K] extends infer R ? [R] :
[]
// prettier-ignore
export type TIndexTuple<T extends TSchema[], K extends Key> =
K extends keyof T ? [T[K]] :
[]
// prettier-ignore
export type TIndexComposite<T extends TSchema[], K extends Key> =
T extends [infer L, ...infer R] ? [...TIndexKey<AssertType<L>, K>, ...TIndexComposite<AssertRest<R>, K>] :
[]
// prettier-ignore
export type TIndexKey<T extends TSchema, K extends Key> =
T extends TRecursive<infer S> ? TIndexKey<S, K> :
T extends TIntersect<infer S> ? TIndexComposite<S, K> :
T extends TUnion<infer S> ? TIndexComposite<S, K> :
T extends TObject<infer S> ? TIndexProperty<S, K> :
T extends TTuple<infer S> ? TIndexTuple<S, K> :
T extends TArray<infer S> ? S :
[]
// prettier-ignore
export type TIndexKeys<T extends TSchema, K extends Key[]> =
K extends [infer L, ...infer R] ?
[...TIndexKey<T, Assert<L, Key>>, ...TIndexKeys<T, Assert<R, Key[]>>] :
[]
// prettier-ignore
export type TIndex<T extends TSchema, K extends Key[]> =
TIndexKeys<T, K> extends infer R ?
T extends TRecursive<infer S> ? TIndex<S, K> :
T extends TTuple ? UnionType<AssertRest<R>> :
T extends TIntersect ? UnionType<AssertRest<R>> :
T extends TUnion ? UnionType<AssertRest<R>> :
T extends TObject ? UnionType<AssertRest<R>> :
T extends TArray ? UnionType<AssertRest<R>> :
TNever :
TNever
// --------------------------------------------------------------------------
// TInteger
// --------------------------------------------------------------------------
export interface TInteger extends TSchema, NumericOptions<number> {
[Kind]: 'Integer'
static: number
type: 'integer'
}
// --------------------------------------------------------------------------
// TIntersect
// --------------------------------------------------------------------------
export type TUnevaluatedProperties = undefined | TSchema | boolean
export interface IntersectOptions extends SchemaOptions {
unevaluatedProperties?: TUnevaluatedProperties
}
export interface TIntersect<T extends TSchema[] = TSchema[]> extends TSchema, IntersectOptions {
[Kind]: 'Intersect'
static: TupleToIntersect<{ [K in keyof T]: Static<AssertType<T[K]>, this['params']> }>
type?: 'object'
allOf: [...T]
}
// --------------------------------------------------------------------------
// TKeyOf
// --------------------------------------------------------------------------
export type TKeyOfProperties<T extends TSchema> = Static<T> extends infer S
? UnionToTuple<
{
[K in keyof S]: TLiteral<`${Assert<K, TLiteralValue>}`>
}[keyof S]
>
: []
// prettier-ignore
export type TKeyOfIndicesArray<T extends TSchema[]> = UnionToTuple<keyof T & `${number}`>
// prettier-ignore
export type TKeyOfIndices<T extends TSchema[]> = AssertRest<TKeyOfIndicesArray<T> extends infer R ? {
[K in keyof R] : TLiteral<Assert<R[K], TLiteralValue>>
}: []>
// prettier-ignore
export type TKeyOf<T extends TSchema = TSchema> = (
T extends TRecursive<infer S> ? TKeyOfProperties<S> :
T extends TIntersect ? TKeyOfProperties<T> :
T extends TUnion ? TKeyOfProperties<T> :
T extends TObject ? TKeyOfProperties<T> :
T extends TTuple<infer K> ? TKeyOfIndices<K> :
T extends TArray ? [TNumber] :
T extends TRecord<infer K> ? [K] :
[]
) extends infer R ? UnionType<AssertRest<R>> : never
// --------------------------------------------------------------------------
// TLiteral
// --------------------------------------------------------------------------
export type TLiteralValue = string | number | boolean // | bigint - supported but variant disable due to potential numeric type conflicts
export interface TLiteral<T extends TLiteralValue = TLiteralValue> extends TSchema {
[Kind]: 'Literal'
static: T
const: T
}
// --------------------------------------------------------------------------
// TNever
// --------------------------------------------------------------------------
export interface TNever extends TSchema {
[Kind]: 'Never'
static: never
not: {}
}
// --------------------------------------------------------------------------
// TNot
// --------------------------------------------------------------------------
export interface TNot<Not extends TSchema = TSchema, T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Not'
static: Static<T>
allOf: [{ not: Not }, T]
}
// --------------------------------------------------------------------------
// TNull
// --------------------------------------------------------------------------
export interface TNull extends TSchema {
[Kind]: 'Null'
static: null
type: 'null'
}
// --------------------------------------------------------------------------
// TNumber
// --------------------------------------------------------------------------
export interface TNumber extends TSchema, NumericOptions<number> {
[Kind]: 'Number'
static: number
type: 'number'
}
// --------------------------------------------------------------------------
// TObject
// --------------------------------------------------------------------------
export type ReadonlyOptionalPropertyKeys<T extends TProperties> = { [K in keyof T]: T[K] extends TReadonlyOptional<TSchema> ? K : never }[keyof T]
export type ReadonlyPropertyKeys<T extends TProperties> = { [K in keyof T]: T[K] extends TReadonly<TSchema> ? K : never }[keyof T]
export type OptionalPropertyKeys<T extends TProperties> = { [K in keyof T]: T[K] extends TOptional<TSchema> ? K : never }[keyof T]
export type RequiredPropertyKeys<T extends TProperties> = keyof Omit<T, ReadonlyOptionalPropertyKeys<T> | ReadonlyPropertyKeys<T> | OptionalPropertyKeys<T>>
// prettier-ignore
export type PropertiesReducer<T extends TProperties, R extends Record<keyof any, unknown>> = Evaluate<(
Readonly<Partial<Pick<R, ReadonlyOptionalPropertyKeys<T>>>> &
Readonly<Pick<R, ReadonlyPropertyKeys<T>>> &
Partial<Pick<R, OptionalPropertyKeys<T>>> &
Required<Pick<R, RequiredPropertyKeys<T>>>
)>
// prettier-ignore
export type PropertiesReduce<T extends TProperties, P extends unknown[]> = PropertiesReducer<T, {
[K in keyof T]: Static<T[K], P>
}>
export type TProperties = Record<keyof any, TSchema>
export type ObjectProperties<T> = T extends TObject<infer U> ? U : never
export type ObjectPropertyKeys<T> = T extends TObject<infer U> ? keyof U : never
export type TAdditionalProperties = undefined | TSchema | boolean
export interface ObjectOptions extends SchemaOptions {
additionalProperties?: TAdditionalProperties
minProperties?: number
maxProperties?: number
}
export interface TObject<T extends TProperties = TProperties> extends TSchema, ObjectOptions {
[Kind]: 'Object'
static: PropertiesReduce<T, this['params']>
additionalProperties?: TAdditionalProperties
type: 'object'
properties: T
required?: string[]
}
// --------------------------------------------------------------------------
// TOmit
// --------------------------------------------------------------------------
export type TOmitArray<T extends TSchema[], K extends keyof any> = AssertRest<{ [K2 in keyof T]: TOmit<AssertType<T[K2]>, K> }>
export type TOmitProperties<T extends TProperties, K extends keyof any> = Evaluate<AssertProperties<Omit<T, K>>>
// prettier-ignore
export type TOmit<T extends TSchema = TSchema, K extends keyof any = keyof any> =
T extends TRecursive<infer S> ? TRecursive<TOmit<S, K>> :
T extends TIntersect<infer S> ? TIntersect<TOmitArray<S, K>> :
T extends TUnion<infer S> ? TUnion<TOmitArray<S, K>> :
T extends TObject<infer S> ? TObject<TOmitProperties<S, K>> :
T
// --------------------------------------------------------------------------
// TParameters
// --------------------------------------------------------------------------
export type TParameters<T extends TFunction> = Ensure<TTuple<T['parameters']>>
// --------------------------------------------------------------------------
// TPartial
// --------------------------------------------------------------------------
export type TPartialObjectArray<T extends TObject[]> = AssertRest<{ [K in keyof T]: TPartial<AssertType<T[K], TObject>> }, TObject[]>
export type TPartialArray<T extends TSchema[]> = AssertRest<{ [K in keyof T]: TPartial<AssertType<T[K]>> }>
// prettier-ignore
export type TPartialProperties<T extends TProperties> = Evaluate<AssertProperties<{
[K in keyof T]:
T[K] extends TReadonlyOptional<infer U> ? TReadonlyOptional<U> :
T[K] extends TReadonly<infer U> ? TReadonlyOptional<U> :
T[K] extends TOptional<infer U> ? TOptional<U> :
TOptional<T[K]>
}>>
// prettier-ignore
export type TPartial<T extends TSchema> =
T extends TRecursive<infer S> ? TRecursive<TPartial<S>> :
T extends TIntersect<infer S> ? TIntersect<TPartialArray<S>> :
T extends TUnion<infer S> ? TUnion<TPartialArray<S>> :
T extends TObject<infer S> ? TObject<TPartialProperties<S>> :
T
// --------------------------------------------------------------------------
// TPick
// --------------------------------------------------------------------------
export type TPickArray<T extends TSchema[], K extends keyof any> = { [K2 in keyof T]: TPick<AssertType<T[K2]>, K> }
// Note the key K will overlap for varying TProperties gathered via recursive union and intersect traversal. Because of this,
// we need to extract only keys assignable to T on K2. This behavior is only required for Pick only.
// prettier-ignore
export type TPickProperties<T extends TProperties, K extends keyof any> =
Pick<T, Assert<Extract<K, keyof T>, keyof T>> extends infer R ? ({
[K in keyof R]: AssertType<R[K]> extends TSchema ? R[K] : never
}): never
// prettier-ignore
export type TPick<T extends TSchema = TSchema, K extends keyof any = keyof any> =
T extends TRecursive<infer S> ? TRecursive<TPick<S, K>> :
T extends TIntersect<infer S> ? TIntersect<TPickArray<S, K>> :
T extends TUnion<infer S> ? TUnion<TPickArray<S, K>> :
T extends TObject<infer S> ? TObject<TPickProperties<S, K>> :
T
// --------------------------------------------------------------------------
// TPromise
// --------------------------------------------------------------------------
export interface TPromise<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Promise'
static: Promise<Static<T, this['params']>>
type: 'object'
instanceOf: 'Promise'
item: TSchema
}
// --------------------------------------------------------------------------
// TRecord
// --------------------------------------------------------------------------
export type RecordTemplateLiteralObjectType<K extends TTemplateLiteral, T extends TSchema> = Ensure<TObject<Evaluate<{ [_ in Static<K>]: T }>>>
export type RecordTemplateLiteralType<K extends TTemplateLiteral, T extends TSchema> = IsTemplateLiteralFinite<K> extends true ? RecordTemplateLiteralObjectType<K, T> : TRecord<K, T>
export type RecordUnionLiteralType<K extends TUnion, T extends TSchema> = Static<K> extends string ? Ensure<TObject<{ [X in Static<K>]: T }>> : never
export type RecordLiteralType<K extends TLiteral<string | number>, T extends TSchema> = Ensure<TObject<{ [K2 in K['const']]: T }>>
export type RecordNumberType<K extends TInteger | TNumber, T extends TSchema> = Ensure<TRecord<K, T>>
export type RecordStringType<K extends TString, T extends TSchema> = Ensure<TRecord<K, T>>
export type RecordKey = TUnion<TLiteral<string | number>[]> | TLiteral<string | number> | TTemplateLiteral | TInteger | TNumber | TString
export interface TRecord<K extends RecordKey = RecordKey, T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Record'
static: Record<Static<K>, Static<T, this['params']>>
type: 'object'
patternProperties: { [pattern: string]: T }
additionalProperties: TAdditionalProperties
}
// --------------------------------------------------------------------------
// TRecursive
// --------------------------------------------------------------------------
export interface TThis extends TSchema {
[Kind]: 'This'
static: this['params'][0]
$ref: string
}
export type TRecursiveReduce<T extends TSchema> = Static<T, [TRecursiveReduce<T>]>
export interface TRecursive<T extends TSchema> extends TSchema {
[Hint]: 'Recursive'
static: TRecursiveReduce<T>
}
// --------------------------------------------------------------------------
// TRef
// --------------------------------------------------------------------------
export interface TRef<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Ref'
static: Static<T, this['params']>
$ref: string
}
// --------------------------------------------------------------------------
// TRest
// --------------------------------------------------------------------------
export type TRest<T extends TSchema> = T extends TTuple<infer R> ? Assert<R, TSchema[]> : Assert<[T], TSchema[]>
// --------------------------------------------------------------------------
// TReturnType
// --------------------------------------------------------------------------
export type TReturnType<T extends TFunction> = T['returns']
// --------------------------------------------------------------------------
// TRequired
// --------------------------------------------------------------------------
export type TRequiredArray<T extends TSchema[]> = AssertRest<{ [K in keyof T]: TRequired<AssertType<T[K]>> }>
// prettier-ignore
export type TRequiredProperties<T extends TProperties> = Evaluate<AssertProperties<{
[K in keyof T]:
T[K] extends TReadonlyOptional<infer U> ? TReadonly<U> :
T[K] extends TReadonly<infer U> ? TReadonly<U> :
T[K] extends TOptional<infer U> ? U :
T[K]
}>>
// prettier-ignore
export type TRequired<T extends TSchema> =
T extends TRecursive<infer S> ? TRecursive<TRequired<S>> :
T extends TIntersect<infer S> ? TIntersect<TRequiredArray<S>> :
T extends TUnion<infer S> ? TUnion<TRequiredArray<S>> :
T extends TObject<infer S> ? TObject<TRequiredProperties<S>> :
T
// --------------------------------------------------------------------------
// TString
// --------------------------------------------------------------------------
export type StringFormatOption =
| 'date-time'
| 'time'
| 'date'
| 'email'
| 'idn-email'
| 'hostname'
| 'idn-hostname'
| 'ipv4'
| 'ipv6'
| 'uri'
| 'uri-reference'
| 'iri'
| 'uuid'
| 'iri-reference'
| 'uri-template'
| 'json-pointer'
| 'relative-json-pointer'
| 'regex'
export interface StringOptions extends SchemaOptions {
minLength?: number
maxLength?: number
pattern?: string
format?: string
contentEncoding?: '7bit' | '8bit' | 'binary' | 'quoted-printable' | 'base64'
contentMediaType?: string
}
export interface TString extends TSchema, StringOptions {
[Kind]: 'String'
static: string
type: 'string'
}
// --------------------------------------------------------------------------
// TSymbol
// --------------------------------------------------------------------------
export type SymbolValue = string | number | undefined
export interface TSymbol extends TSchema, SchemaOptions {
[Kind]: 'Symbol'
static: symbol
type: 'null'
typeOf: 'Symbol'
}
// --------------------------------------------------------------------------
// TTemplateLiteral
// --------------------------------------------------------------------------
// prettier-ignore
export type IsTemplateLiteralFiniteCheck<T> =
T extends TTemplateLiteral<infer U> ? IsTemplateLiteralFiniteArray<Assert<U, TTemplateLiteralKind[]>> :
T extends TUnion<infer U> ? IsTemplateLiteralFiniteArray<Assert<U, TTemplateLiteralKind[]>> :
T extends TString ? false :
T extends TBoolean ? false :
T extends TNumber ? false :
T extends TInteger ? false :
T extends TBigInt ? false :
T extends TLiteral ? true :
false
// prettier-ignore
export type IsTemplateLiteralFiniteArray<T extends TTemplateLiteralKind[]> =
T extends [infer L, ...infer R] ? IsTemplateLiteralFiniteCheck<L> extends false ? false : IsTemplateLiteralFiniteArray<Assert<R, TTemplateLiteralKind[]>> :
true
export type IsTemplateLiteralFinite<T> = T extends TTemplateLiteral<infer U> ? IsTemplateLiteralFiniteArray<U> : false
export type TTemplateLiteralKind = TUnion | TLiteral | TInteger | TTemplateLiteral | TNumber | TBigInt | TString | TBoolean | TNever
// prettier-ignore
export type TTemplateLiteralConst<T, Acc extends string> =
T extends TUnion<infer U> ? { [K in keyof U]: TTemplateLiteralUnion<Assert<[U[K]], TTemplateLiteralKind[]>, Acc> }[number] :
T extends TTemplateLiteral ? `${Static<T>}` :
T extends TLiteral<infer U> ? `${U}` :
T extends TString ? `${string}` :
T extends TNumber ? `${number}` :
T extends TBigInt ? `${bigint}` :
T extends TBoolean ? `${boolean}` :
never
// prettier-ignore
export type TTemplateLiteralUnion<T extends TTemplateLiteralKind[], Acc extends string = ''> =
T extends [infer L, ...infer R] ? `${TTemplateLiteralConst<L, Acc>}${TTemplateLiteralUnion<Assert<R, TTemplateLiteralKind[]>, Acc>}` :
Acc
export type TTemplateLiteralKeyArray<T extends TTemplateLiteral> = Assert<UnionToTuple<Static<T>>, Key[]>
export interface TTemplateLiteral<T extends TTemplateLiteralKind[] = TTemplateLiteralKind[]> extends TSchema {
[Kind]: 'TemplateLiteral'
static: TTemplateLiteralUnion<T>
type: 'string'
pattern: string // todo: it may be possible to infer this pattern
}
// --------------------------------------------------------------------------
// TTuple
// --------------------------------------------------------------------------
export type TTupleIntoArray<T extends TTuple<TSchema[]>> = T extends TTuple<infer R> ? AssertRest<R> : never
export interface TTuple<T extends TSchema[] = TSchema[]> extends TSchema {
[Kind]: 'Tuple'
static: { [K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : T[K] }
type: 'array'
items?: T
additionalItems?: false
minItems: number
maxItems: number
}
// --------------------------------------------------------------------------
// TUndefined
// --------------------------------------------------------------------------
export interface TUndefined extends TSchema {
[Kind]: 'Undefined'
static: undefined
type: 'null'
typeOf: 'Undefined'
}
// --------------------------------------------------------------------------
// TUnionOfLiteral
// --------------------------------------------------------------------------
// prettier-ignore
export type TLiteralUnionReduce<T extends TLiteral<string | number>[]> =
T extends [infer L, ...infer R] ? [Assert<L, TLiteral<string | number>>['const'], ...TLiteralUnionReduce<Assert<R, TLiteral<string | number>[]>>] :
[]
// prettier-ignore
export type TLiteralUnion<T extends TUnion<TLiteral<string | number>[]>> =
T extends TUnion<infer S> ? TLiteralUnionReduce<Assert<S, TLiteral<string | number>[]>> : []
// --------------------------------------------------------------------------
// TUnion
// --------------------------------------------------------------------------
// prettier-ignore
export type TUnionTemplateLiteral<T extends TTemplateLiteral, S extends string = Static<T>> = Ensure<UnionType<Assert<UnionToTuple<{[K in S]: TLiteral<K>}[S]>,TLiteral[]>>>
export interface TUnion<T extends TSchema[] = TSchema[]> extends TSchema {
[Kind]: 'Union'
static: { [K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : never }[number]
anyOf: T
}
// --------------------------------------------------------------------------
// TUint8Array
// --------------------------------------------------------------------------
export interface Uint8ArrayOptions extends SchemaOptions {
maxByteLength?: number
minByteLength?: number
}
export interface TUint8Array extends TSchema, Uint8ArrayOptions {
[Kind]: 'Uint8Array'
static: Uint8Array
instanceOf: 'Uint8Array'
type: 'object'
}
// --------------------------------------------------------------------------
// TUnknown
// --------------------------------------------------------------------------
export interface TUnknown extends TSchema {
[Kind]: 'Unknown'
static: unknown
}
// --------------------------------------------------------------------------
// TUnsafe
// --------------------------------------------------------------------------
export interface UnsafeOptions extends SchemaOptions {
[Kind]?: string
}
export interface TUnsafe<T> extends TSchema {
[Kind]: string
static: T
}
// --------------------------------------------------------------------------
// TVoid
// --------------------------------------------------------------------------
export interface TVoid extends TSchema {
[Kind]: 'Void'
static: void
type: 'null'
typeOf: 'Void'
}
// --------------------------------------------------------------------------
// Static<T>
// --------------------------------------------------------------------------
/** Creates a TypeScript static type from a TypeBox type */
export type Static<T extends TSchema, P extends unknown[] = []> = (T & { params: P })['static']
// --------------------------------------------------------------------------
// TypeRegistry
// --------------------------------------------------------------------------
export type TypeRegistryValidationFunction<TSchema> = (schema: TSchema, value: unknown) => boolean
/** A registry for user defined types */
export namespace TypeRegistry {
const map = new Map<string, TypeRegistryValidationFunction<any>>()
/** Returns the entries in this registry */
export function Entries() {
return new Map(map)
}
/** Clears all user defined types */
export function Clear() {
return map.clear()
}
/** Returns true if this registry contains this kind */
export function Has(kind: string) {
return map.has(kind)
}
/** Sets a validation function for a user defined type */
export function Set<TSchema = unknown>(kind: string, func: TypeRegistryValidationFunction<TSchema>) {
map.set(kind, func)
}
/** Gets a custom validation function for a user defined type */
export function Get(kind: string) {
return map.get(kind)
}
}
// --------------------------------------------------------------------------
// TypeRegistry
// --------------------------------------------------------------------------
export type FormatRegistryValidationFunction = (value: string) => boolean
/** A registry for user defined string formats */
export namespace FormatRegistry {
const map = new Map<string, FormatRegistryValidationFunction>()
/** Returns the entries in this registry */
export function Entries() {
return new Map(map)
}
/** Clears all user defined string formats */
export function Clear() {
return map.clear()
}
/** Returns true if the user defined string format exists */
export function Has(format: string) {
return map.has(format)
}
/** Sets a validation function for a user defined string format */
export function Set(format: string, func: FormatRegistryValidationFunction) {
map.set(format, func)
}
/** Gets a validation function for a user defined string format */
export function Get(format: string) {
return map.get(format)
}
}
// --------------------------------------------------------------------------
// TypeGuard
// --------------------------------------------------------------------------
export class TypeGuardUnknownTypeError extends Error {
constructor(public readonly schema: unknown) {
super('TypeGuard: Unknown type')
}
}
/** Provides functions to test if JavaScript values are TypeBox types */
export namespace TypeGuard {
function IsObject(value: unknown): value is Record<string | symbol, any> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function IsArray(value: unknown): value is any[] {
return typeof value === 'object' && value !== null && Array.isArray(value)
}
function IsPattern(value: unknown): value is string {
try {
new RegExp(value as string)
return true
} catch {
return false
}
}
function IsControlCharacterFree(value: unknown): value is string {
if (typeof value !== 'string') return false
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i)
if ((code >= 7 && code <= 13) || code === 27 || code === 127) {
return false
}
}
return true
}
function IsAdditionalProperties(value: unknown): value is TAdditionalProperties {
return IsOptionalBoolean(value) || TSchema(value)
}
function IsBigInt(value: unknown): value is bigint {
return typeof value === 'bigint'
}
function IsString(value: unknown): value is string {
return typeof value === 'string'
}
function IsNumber(value: unknown): value is number {
return typeof value === 'number' && globalThis.Number.isFinite(value)
}
function IsBoolean(value: unknown): value is boolean {
return typeof value === 'boolean'
}
function IsOptionalBigInt(value: unknown): value is bigint | undefined {
return value === undefined || (value !== undefined && IsBigInt(value))
}
function IsOptionalNumber(value: unknown): value is number | undefined {
return value === undefined || (value !== undefined && IsNumber(value))
}
function IsOptionalBoolean(value: unknown): value is boolean | undefined {
return value === undefined || (value !== undefined && IsBoolean(value))
}
function IsOptionalString(value: unknown): value is string | undefined {
return value === undefined || (value !== undefined && IsString(value))
}
function IsOptionalPattern(value: unknown): value is string | undefined {
return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value) && IsPattern(value))
}
function IsOptionalFormat(value: unknown): value is string | undefined {
return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value))
}
function IsOptionalSchema(value: unknown): value is boolean | undefined {
return value === undefined || TSchema(value)
}
/** Returns true if the given schema is TAny */
export function TAny(schema: unknown): schema is TAny {
return TKind(schema) && schema[Kind] === 'Any' && IsOptionalString(schema.$id)
}
/** Returns true if the given schema is TArray */
export function TArray(schema: unknown): schema is TArray {
return (
TKind(schema) &&
schema[Kind] === 'Array' &&
schema.type === 'array' &&
IsOptionalString(schema.$id) &&
TSchema(schema.items) &&
IsOptionalNumber(schema.minItems) &&
IsOptionalNumber(schema.maxItems) &&
IsOptionalBoolean(schema.uniqueItems)
)
}
/** Returns true if the given schema is TBigInt */
export function TBigInt(schema: unknown): schema is TBigInt {
// prettier-ignore
return (
TKind(schema) &&
schema[Kind] === 'BigInt' &&
schema.type === 'null' &&
schema.typeOf === 'BigInt' &&
IsOptionalString(schema.$id) &&
IsOptionalBigInt(schema.multipleOf) &&
IsOptionalBigInt(schema.minimum) &&
IsOptionalBigInt(schema.maximum) &&
IsOptionalBigInt(schema.exclusiveMinimum) &&
IsOptionalBigInt(schema.exclusiveMaximum)
)
}
/** Returns true if the given schema is TBoolean */
export function TBoolean(schema: unknown): schema is TBoolean {
// prettier-ignore
return (
TKind(schema) &&
schema[Kind] === 'Boolean' &&
schema.type === 'boolean' &&
IsOptionalString(schema.$id)
)
}
/** Returns true if the given schema is TConstructor */
export function TConstructor(schema: unknown): schema is TConstructor {
// prettier-ignore
if (!(
TKind(schema) &&
schema[Kind] === 'Constructor' &&
schema.type === 'object' &&
schema.instanceOf === 'Constructor' &&
IsOptionalString(schema.$id) &&
IsArray(schema.parameters) &&
TSchema(schema.returns))
) {
return false
}
for (const parameter of schema.parameters) {
if (!TSchema(parameter)) return false
}
return true
}
/** Returns true if the given schema is TDate */
export function TDate(schema: unknown): schema is TDate {
return (
TKind(schema) &&
schema[Kind] === 'Date' &&
schema.type === 'object' &&
schema.instanceOf === 'Date' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.minimumTimestamp) &&
IsOptionalNumber(schema.maximumTimestamp) &&
IsOptionalNumber(schema.exclusiveMinimumTimestamp) &&
IsOptionalNumber(schema.exclusiveMaximumTimestamp)
)
}
/** Returns true if the given schema is TFunction */
export function TFunction(schema: unknown): schema is TFunction {
// prettier-ignore
if (!(
TKind(schema) &&
schema[Kind] === 'Function' &&
schema.type === 'object' &&
schema.instanceOf === 'Function' &&
IsOptionalString(schema.$id) &&
IsArray(schema.parameters) &&
TSchema(schema.returns))
) {
return false
}
for (const parameter of schema.parameters) {
if (!TSchema(parameter)) return false
}
return true
}
/** Returns true if the given schema is TInteger */
export function TInteger(schema: unknown): schema is TInteger {
return (
TKind(schema) &&