-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSchema.mjs
1014 lines (924 loc) · 27.9 KB
/
Schema.mjs
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
import Tuple from './Tuple.mjs';
import Group from './Group.mjs';
import Record from './Record.mjs';
import Dict from './Dict.mjs';
/**
* @callback SchemaMapper
*/
const Schema = {
/**
* Map one or more values to a Tuple.
* Will append additional properties as unmapped values if more values are provided than appear in the schema.
* @param {...SchemaMapper} schema A list of SchemaMappers
*/
tuple(...schema)
{
return (args = [], path = '') => {
return Tuple(...args.map(
(arg, index) => schema[index] ? schema[index](arg, `${path || 'root'}[${index}]`): arg
));
}
},
/**
* Map one or more values to a Group.
* Will append additional properties as unmapped values if more values are provided than appear in the schema.
* @param {...SchemaMapper} schema A list of SchemaMappers
*/
group(...schema)
{
return (args = [], path = '') => {
return Group(...args.map(
(arg, index) => schema[index] ? schema[index](arg, `${path || 'root'}[${index}]`): arg
));
}
},
/**
* Map an object to a Record.
* Will append additional properties as unmapped values if more values are provided than appear in the schema.
* @param {Object.<string, SchemaMapper>} schema - An Object holding SchemaMappers
*/
record(schema = {})
{
return (arg, path = '') => {
const entries = Object.entries(schema);
return Record(Object.assign(
{},
arg,
Object.fromEntries(
entries.map(([key, schema]) => [key, schema(arg[key], `${path || 'root'}[${key}]`)])
)
));
}
},
/**
* Map an object to a Record.
* Will append additional properties as unmapped values if more values are provided than appear in the schema.
* @param {Object.<string, SchemaMapper>} schema - An Object holding SchemaMappers
*/
dict(schema = {})
{
return (arg, path = '') => {
const entries = Object.entries(arg);
return Dict(Object.fromEntries(
entries.map(([key, value]) => [key, schema[key] ? schema[key](value, `${path || 'root'}[${key}]`) : value])
));
}
},
/**
* Map n values to a Tuple.
* Will append each value in the input to the Tuple using the same mapper.
* @param {SchemaMapper} schema - A SchemaMapper
*/
nTuple(schema)
{
return (args, path) => {
if(!Array.isArray(args))
{
args = [args]
}
return Tuple(...args.map((arg, index) => schema ? schema(arg, `${path || 'root'}[${index}]`) : arg));
}
},
/**
* Map n values to a Group.
* Will append each value in the input to the Group using the same mapper.
* @param {SchemaMapper} schema - A list of SchemaMappers
*/
nGroup(schema)
{
return (args, path = '') => {
if(!Array.isArray(args))
{
args = [args]
}
return Group(...args.map((arg, index) => schema ? schema(arg, `${path || 'root'}[${index}]`) : arg));
}
},
/**
* Map n keys to a Record.
* @param {Object.<string, SchemaMapper>} schema - An Object holding SchemaMappers
*/
nRecord(schema)
{
return (arg, path = '') => {
const entries = Object.entries(arg);
return Record(Object.fromEntries(
entries.map(([key, value]) => [key, schema[key] ? schema[key](value, `${path || 'root'}[${key}]`) : value])
));
}
},
/**
* Map n keys to a Dict.
* @param {Object.<string, SchemaMapper>} schema - An Object holding SchemaMappers
*/
nDict(schema)
{
/**
* @type SchemaMapper
*/
return (arg, path = '') => {
const entries = Object.entries(arg);
return Dict(Object.fromEntries(
entries.map(([key, value]) => [key, schema[key] ? schema[key](value, `${path || 'root'}[${key}]`) : value])
));
}
},
/**
* Strictly map values to a Tuple.
* @throws {TypeError} Will throw if the number of values does not match the number of SchemaMappers
* @param {...SchemaMapper} schema A list of SchemaMappers
*/
sTuple(...schema)
{
return (args, path = '') => {
if(schema.length !== args.length)
{
throw new TypeError(`Expected ${schema.length} elements, got ${args.length} elements at ${path || 'root'}.`);
}
return Tuple(...args.map(
(arg, index) => schema[index] ? schema[index](arg, `${path || 'root'}[${index}]`): arg
));
}
},
/**
* Strictly map values to a Group.
* @throws {TypeError} Will throw if the number of values does not match the number of SchemaMappers
* @param {...SchemaMapper} schema A list of SchemaMappers
*/
sGroup(...schema)
{
return (args, path = '') => {
if(schema.length !== args.length)
{
throw new TypeError(`Expected ${schema.length} elements, got ${args.length} elements at ${path || 'root'}.`);
}
return Group(...args.map(
(arg, index) => schema[index] ? schema[index](arg, `${path || 'root'}[${index}]`): arg
));
}
},
/**
* Strictly map an object to a Record.
* @throws {TypeError} Will throw if the properties provided do not match the keys of the SchemaMappers.
* @param {Object.<string, SchemaMapper>} schema - An Object holding SchemaMappers
*/
sRecord(schema = {})
{
return (arg, path = '') => {
const entries = Object.entries(arg);
const schemaLength = Object.keys(schema).length;
if(schemaLength > entries.length)
{
throw new TypeError(`Expected ${schemaLength} elements, got ${entries.length} elements at ${path || 'root'}.`);
}
return Record(Object.fromEntries(
entries.map(([key, value]) => {
if(!(key in schema))
{
throw new TypeError(`Extra key "${key}" not found in schema at ` + (path ? `${path}[${key}]` : key));
}
return [key, schema[key](value, path ? `${path}[${key}]` : key)]
})
));
}
},
/**
* Strictly map an object to a Dict.
* @throws {TypeError} Will throw if the properties provided do not match the keys of the SchemaMappers.
* @param {Object.<string, SchemaMapper>} schema - An Object holding SchemaMappers
*/
sDict(schema = {})
{
return (arg, path = '') => {
const entries = Object.entries(arg);
const schemaLength = Object.keys(schema).length;
if(schemaLength > entries.length)
{
throw new TypeError(`Expected ${schemaLength} elements, got ${entries.length} elements at ${path || 'root'}.`);
}
return Dict(Object.fromEntries(
entries.map(([key, value]) => {
if(!(key in schema))
{
throw new TypeError(`Extra key "${key}" not found in schema at ` + (path ? `${path}[${key}]` : key));
}
return [key, schema[key](value, path ? `${path}[${key}]` : key)]
})
));
}
},
/**
* Exclusively map values to a Tuple.
* Will drop any keys not present in the schema.
* @param {...SchemaMapper} schema A list of SchemaMappers
*/
xTuple(...schema)
{
return (args, path = '') => {
if(schema.length > args.length)
{
throw new TypeError(`Expected ${schema.length} elements, got ${args.length} elements at ${path || 'root'}.`);
}
return Tuple(...schema.map(
(schema, index) => schema(args[index], `${path || 'root'}[${index}]`)
));
}
},
/**
* Exclusively map values to a Group.
* Will drop any keys not present in the schema.
* @param {...SchemaMapper} schema A list of SchemaMappers
*/
xGroup(...schema)
{
return (args, path = '') => {
if(schema.length > args.length)
{
throw new TypeError(`Expected ${schema.length} elements, got ${args.length} elements at ${path || 'root'}.`);
}
return Group(...schema.map(
(schema, index) => schema(args[index], `${path || 'root'}[${index}]`)
));
}
},
/**
* Exclusively map an object to a Record.
* Will drop any keys not present in the schema.
* @param {Object.<string, SchemaMapper>} schema - An Object holding SchemaMappers
*/
xRecord(schema)
{
return (arg, path = '') => {
const schemaEntries = Object.entries(schema);
return Record(Object.fromEntries(
schemaEntries.map(([key, schema]) => [key, schema(arg[key], `${path || 'root'}[${key}]`)])
));
}
},
/**
* Exclusively map an object to a Dict.
* Will drop any keys not present in the schema.
* @param {Object.<string, SchemaMapper>} schema - An Object holding SchemaMappers
*/
xDict(schema)
{
return (arg, path = '') => {
const schemaKeys = Object.keys(schema);
return Dict(Object.fromEntries(
schemaKeys.map((key) => [key, schema[key](arg[key], `${path || 'root'}[${key}]`)])
));
}
},
/**
* Validate a boolean
* @param {Object} options
* @param {function(any):any} options.map Transform the value after its been validated.
*/
boolean(options = {})
{
return (value, path = '') => {
if(typeof value !== 'boolean')
{
throw new TypeError(`Expected boolean, got ${typeof value} at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
return value;
};
},
/**
* Validate a number
* @param {Object} options
* @param {number} options.max Max value
* @param {number} options.min Min value
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
number(options = {})
{
return (value, path = '') => {
if(typeof value !== 'number')
{
throw new TypeError(`Expected number, got ${typeof value} at ${path || 'root'}`);
}
if(options.check && !options.check(value))
{
throw new TypeError(`Validation failed! got ${value} at ${path || 'root'}`);
}
if('max' in options && options.max < value)
{
throw new TypeError(`Expected max ${options.max}, got ${value} at ${path || 'root'}`);
}
if('min' in options && options.min > value)
{
throw new TypeError(`Expected min ${options.min}, got ${value} at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
return value;
};
},
/**
* Validate an integer
* @param {Object} options
* @param {number} options.max Max value
* @param {number} options.min Min value
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
integer(options = {})
{
const _options = {...options};
const checks = [Number.isInteger];
if(options.check)
{
checks.push(options.check);
}
_options.check = v => checks.map(c => c(v)).reduce((a, b) => a && b, true);
return Schema.number(_options);
},
/**
* Validate a float
* @param {Object} options
* @param {number} options.max Max value
* @param {number} options.min Min value
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
float(options = {})
{
const _options = {...options};
const checks = [Number.isFinite];
if(options.check)
{
checks.push(options.check);
}
_options.check = v => checks.map(c => c(v)).reduce((a, b) => a && b, true);
return Schema.number(_options);
},
/**
* Validate a NaN
* @param {Object} options
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
NaN(options = {})
{
const _options = {...options};
const checks = [Number.isNaN];
if(options.check)
{
checks.push(options.check);
}
_options.check = v => checks.map(c => c(v)).reduce((a, b) => a && b, true);
return Schema.number(_options);
},
/**
* Validate an infinite value
* @param {Object} options
* @param {number} options.max Max value
* @param {number} options.min Min value
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
infinity(options = {})
{
const checks = [n => !Number.isFinite(n) && !Number.isNaN(n)];
if(options.check)
{
checks.push(options.check);
}
const check = v => checks.map(c => c(v)).reduce((a, b) => a && b, true);
return Schema.number({...options, check});
},
/**
* Validate a bigint
* @param {Object} options
* @param {number} options.max Max value
* @param {number} options.min Min value
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
bigint(options = {})
{
return (value, path = '') => {
if(typeof value !== 'bigint')
{
throw new TypeError(`Expected bigint, got ${typeof value} at ${path || 'root'}`);
}
if(options.check && !options.check(value))
{
throw new TypeError(`Validation failed! got ${value} at ${path || 'root'}`);
}
if('max' in options && options.max < value)
{
throw new TypeError(`Expected max ${options.max}, got ${value} at ${path || 'root'}`);
}
if('min' in options && options.min > value)
{
throw new TypeError(`Expected min ${options.min}, got ${value} at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
return value;
};
},
/**
* Validate a string
* @param {Object} options
* @param {number} options.max Max length
* @param {number} options.min Min length
* @param {Regex} options.match Throw a TypeError if this does NOT match
* @param {Regex} options.noMatch Throw a TypeError if this DOES match
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
string(options = {})
{
return (value, path = '') => {
if(typeof value !== 'string')
{
throw new TypeError(`Expected string, got ${typeof value} at ${path || 'root'}`);
}
if(options.check && !options.check(value))
{
throw new TypeError(`Validation failed! got ${value} at ${path || 'root'}`);
}
if('max' in options && options.max < value.length)
{
throw new TypeError(`Expected max length ${options.max}, got "${value}" at ${path || 'root'}`);
}
if('min' in options && options.min > value.length)
{
throw new TypeError(`Expected min length ${options.min}, got "${value}" at ${path || 'root'}`);
}
if('prefix' in options && options.prefix !== value.substr(0, options.prefix.length))
{
throw new TypeError(`Expected prefix ${options.prefix}, got "${value}" at ${path || 'root'}`);
}
if('suffix' in options && options.suffix !== value.substr(value.length - options.suffix.length))
{
throw new TypeError(`Expected suffix ${options.suffix}, got "${value}" at ${path || 'root'}`);
}
if('infix' in options && value.indexOf(options.infix) === -1)
{
throw new TypeError(`Expected infix ${options.infix}, got "${value}" at ${path || 'root'}`);
}
if(options.match && !value.match(options.match))
{
throw new TypeError(`Expected string to match ${options.match}, got "${value}" at ${path || 'root'}`);
}
if(options.noMatch && value.noMatch(options.noMatch))
{
throw new TypeError(`Expected string NOT to match ${options.noMatch}, got "${value}" at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
return value;
};
},
/**
* Validate a numeric string
* @param {Object} options
* @param {number} options.max Max value
* @param {number} options.min Min value
* @param {Regex} options.match Throw a TypeError if this does NOT match
* @param {Regex} options.noMatch Throw a TypeError if this DOES match
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
numericString(options = {})
{
return (value, path = '') => {
if(isNaN(value) || value === null || value != Number(value))
{
throw new TypeError(`Expected numeric, got "${value}" at ${path || 'root'}`);
}
if('max' in options && options.max < Number(value))
{
throw new TypeError(`Expected max ${options.max}, got "${value}" at ${path || 'root'}`);
}
if('min' in options && options.min > Number(value))
{
throw new TypeError(`Expected min ${options.min}, got "${value}" at ${path || 'root'}`);
}
const {min, max, ...newOptions} = options;
return Schema.string(newOptions)(value);
};
},
/**
* Validate a date string
* @param {Object} options
* @param {number} options.max Max length
* @param {number} options.min Min length
* @param {Regex} options.match Throw a TypeError if this does NOT match
* @param {Regex} options.noMatch Throw a TypeError if this DOES match
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
dateString(options = {})
{
return (value, path = '') => {
if(isNaN(Date.parse(value)))
{
throw new TypeError(`Expected dateString, got "${value}" at ${path || 'root'}`);
}
if('max' in options && options.max < value)
{
throw new TypeError(`Expected max ${options.max}, got "${value}" at ${path || 'root'}`);
}
if('min' in options && options.min > value)
{
throw new TypeError(`Expected min ${options.min}, got "${value}" at ${path || 'root'}`);
}
const {min, max, ...newOptions} = options;
return Schema.string(newOptions)(value);
};
},
uuidString(options = {})
{
const checks = [ value => String(value).match(/^[a-z,0-9]{8}-[a-z,0-9]{4}-[a-z,0-9]{4}-[a-z,0-9]{4}-[a-z,0-9]{12}$/i) ];
if(options.check)
{
checks.push(options.check);
}
const check = v => checks.map(c => c(v)).reduce((a, b) => a && b, true);
return Schema.string({...options, check});
},
/**
* Validate a url string
* @param {Object} options
* @param {number} options.max Max length
* @param {number} options.min Min length
* @param {Regex} options.match Throw a TypeError if this does NOT match
* @param {Regex} options.noMatch Throw a TypeError if this DOES match
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
urlString(options = {})
{
const checks = [ URL.canParse ? value => URL.canParse(value) : value => { try { new URL(value); return true; } catch { return false; } } ];
if(options.check)
{
checks.push(options.check);
}
const check = v => checks.map(c => c(v)).reduce((a, b) => a && b, true);
return Schema.string({...options, check});
},
/**
* Validate a regex string
* @param {Object} options
* @param {number} options.max Max length
* @param {number} options.min Min length
* @param {Regex} options.match Throw a TypeError if this does NOT match
* @param {Regex} options.noMatch Throw a TypeError if this DOES match
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
emailString(options = {})
{
const checks = [ value => {
const atPos = value.indexOf('@');
const atPos2 = value.indexOf('@', atPos + 1);
const dotPos = value.indexOf('.', atPos);
return (atPos > 0) && (atPos2 === -1) && (dotPos - atPos > 0) && (value.length - dotPos > 2);
} ];
if(options.check)
{
checks.push(options.check);
}
const check = v => checks.map(c => c(v)).reduce((a, b) => a && b, true);
return Schema.string({...options, check});
},
regexString(options = {})
{
const checks = [ value => { try { RegExp(value); return !!value; } catch { return false; } } ];
if(options.check)
{
checks.push(options.check);
}
const check = v => checks.map(c => c(v)).reduce((a, b) => a && b, true);
return Schema.string({...options, check});
},
/**
* Validate a base64 string
* @param {Object} options
* @param {number} options.max Max length
* @param {number} options.min Min length
* @param {Regex} options.match Throw a TypeError if this does NOT match
* @param {Regex} options.noMatch Throw a TypeError if this DOES match
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
base64String(options = {})
{
const checks = [ value => value !== '' && value.trim() !== '' && btoa(atob(value)) === value];
if(options.check)
{
checks.push(options.check);
}
const check = v => checks.map(c => c(v)).reduce((a, b) => a && b, true);
return Schema.string({...options, check});
},
/**
* Validate a JSON string
* @param {Object} options
* @param {number} options.max Max length
* @param {number} options.min Min length
* @param {Regex} options.match Throw a TypeError if this does NOT match
* @param {Regex} options.noMatch Throw a TypeError if this DOES match
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
jsonString(options = {})
{
const checks = [ value => { try { JSON.parse(value); return true; } catch { return false; } } ];
if(options.check)
{
checks.push(options.check);
}
const check = v => checks.map(c => c(v)).reduce((a, b) => a && b, true);
return Schema.string({...options, check});
},
/**
* Validate an array
* @param {Object} options
* @param {number} options.max Max length
* @param {number} options.min Min length
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
* @param {function(any):each} options.each Transform each value in the array, after its been validated..
*/
array(options = {})
{
return (value, path = '') => {
if(!Array.isArray(value))
{
throw new TypeError(`Expected Array, got ${typeof value} at ${path || 'root'}`);
}
if(options.check && !options.check(value))
{
throw new TypeError(`Validation failed! got ${value} at ${path || 'root'}`);
}
if('max' in options && options.max < value.length)
{
throw new TypeError(`Expected max length ${options.max}, got "${value.length}" at ${path || 'root'}`);
}
if('min' in options && options.min > value.length)
{
throw new TypeError(`Expected min length ${options.min}, got "${value.length}" at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
if(options.each)
{
value = value.map(options.each);
}
return value;
};
},
/**
* Validate an object
* @param {Object} options
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):class} options.class Throw a TypeError if the class does not match.
* @param {function(any):any} options.map Transform the object after its been validated.
* @param {function(any):each} options.each Transform each entry in the object, after its been validated.
*/
object(options = {})
{
return (value, path = '') => {
if(typeof value !== 'object')
{
throw new TypeError(`Expected object, got ${typeof value} at ${path || 'root'}`);
}
if(options.check && !options.check(value))
{
throw new TypeError(`Validation failed! got ${value} at ${path || 'root'}`);
}
if(options.class && !(value instanceof options.class))
{
throw new TypeError(`Expected object of type ${options.class.name}, got Object of type ${value.constructor ? value.constructor.name : 'null'} at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
if(options.each)
{
value = Object.fromEntries(Object.entries(value).map(options.each));
}
return value;
};
},
date(options = {})
{
return (value, path = '') => {
if(!(value instanceof Date))
{
throw new TypeError(`Expected Date, got "${value}" at ${path || 'root'}`);
}
if('max' in options && options.max < value)
{
throw new TypeError(`Expected max ${options.max}, got "${value}" at ${path || 'root'}`);
}
if('min' in options && options.min > value)
{
throw new TypeError(`Expected min ${options.min}, got "${value}" at ${path || 'root'}`);
}
return Schema.object({...options, class: Date})(value);
};
},
/**
* Validate a function
* @param {Object} options
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
function(options = {})
{
return (value, path = '') => {
if(typeof value !== 'function')
{
throw new TypeError(`Expected function, got ${typeof value} at ${path || 'root'}`);
}
if(options.check && !options.check(value))
{
throw new TypeError(`Validation failed! got ${value} at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
return value;
};
},
/**
* Validate a symbol
* @param {Object} options
* @param {function(any):boolean} options.check Throw a TypeError if this returns false.
* @param {function(any):any} options.map Transform the value after its been validated.
*/
symbol(options = {})
{
return (value, path = '') => {
if(typeof value !== 'symbol')
{
throw new TypeError(`Expected symbol, got ${typeof value} at ${path || 'root'}`);
}
if(options.check && !options.check(value))
{
throw new TypeError(`Validation failed! got ${value} at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
return value;
};
},
/**
* Validate a null
* @param {Object} options
* @param {function(any):any} options.map Transform the value after its been validated.
*/
null(options = {})
{
return (value, path = '') => {
if(value !== null)
{
throw new TypeError(`Expected null, got ${typeof value} at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
return value;
};
},
/**
* Validate an undefined
* @param {Object} options
* @param {function(any):any} options.map Transform the value after its been validated.
*/
undefined(options = {})
{
return (value, path = '') => {
if(value !== undefined)
{
throw new TypeError(`Expected undefined, got ${typeof value} at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
return value;
};
},
/**
* Return the value
* @param {Object} options
* @param {function(any):any} options.map Transform the value.
*/
value(options = {})
{
return (value, path = '') => {
if(options.map)
{
value = options.map(value);
}
return value;
};
},
/**
* Match the value to a set of literals with strict-equals comparison.
* @param {...any} literals Value must be strictly equal to one of these.
* @param {function(any):any} options.map Transform the value after its been validated.
* @returns
*/
oneOf(literals = [], options = {})
{
return (value, path = '') => {
if(!literals.includes(value))
{
throw new TypeError(`Expected oneOf ${values.join(', ')}, got ${value} at ${path || 'root'}`);
}
if(options.map)
{
value = options.map(value);
}
return value;
};
},
/**
* Drop the value (always maps to `undefined`)
*/
drop()
{
return () => undefined;
},
/**
* Map the value with the first matching SchemaMapper
* @param {...function(options):value} mappers
*/
or(...mappers)
{
return (value, path) => {
const errors = [];
for(const mapper of mappers)
{
try
{
return mapper(value, path);
}
catch(error)
{
errors.push(error);
}
}
const multi = new Error(errors.map(e => e.message).join(', '));
multi.errors = errors;
throw multi;
};
},
/**
* Repeat a SchemaMapper n times
* @param {number} n The number of times to repeat.
* @param {SchemaMapper} schema The SchemaMapper to repeat.
*/
repeat(n, schema)
{
return Array(n).fill(schema);
},
/**
* Safely parse a Schema into an immutable structure.
* Returns NaN on error. This is helpful because `NaN !== NaN`, and its falsey.
* @param {SchemaMapper} schema The Schema to parse by.
* @param {values} any The values to parse.
* @returns {object|NaN}
*/
parse(schema, values)
{
try