forked from 418sec/js-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSchema.ts
1296 lines (1230 loc) · 43.4 KB
/
Schema.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
import utils from './utils'
import Component from './Component'
import { TsDataError } from './TsDataError'
const DOMAIN = 'Schema'
/**
* A function map for each of the seven primitive JSON types defined by the core specification.
* Each function will check a given value and return true or false if the value is an instance of that type.
* ```
* types.integer(1) // returns true
* types.string({}) // returns false
* ```
* http://json-schema.org/latest/json-schema-core.html#anchor8
* @name Schema.types
* @type {object}
*/
const types = {
array: utils.isArray,
boolean: utils.isBoolean,
integer: utils.isInteger,
null: utils.isNull,
number: utils.isNumber,
object: utils.isObject,
string: utils.isString
}
/**
* @ignore
*/
function segmentToString (segment, prev) {
let str = ''
if (segment) {
if (utils.isNumber(segment)) {
str += `[${segment}]`
} else if (prev) {
str += `.${segment}`
} else {
str += `${segment}`
}
}
return str
}
/**
* @ignore
*/
function makePath (opts: any = {}) {
let path = ''
const segments = opts.path || []
segments.forEach(segment => {
path += segmentToString(segment, path)
})
path += segmentToString(opts.prop, path)
return path
}
/**
* @ignore
*/
function makeError (actual, expected, opts) {
return {
expected,
actual: '' + actual,
path: makePath(opts)
}
}
/**
* @ignore
*/
function addError (actual, expected, opts, errors) {
errors.push(makeError(actual, expected, opts))
}
/**
* @ignore
*/
function maxLengthCommon (keyword, value, schema, opts) {
const max = schema[keyword]
if (value.length > max) {
return makeError(value.length, `length no more than ${max}`, opts)
}
}
/**
* @ignore
*/
function minLengthCommon (keyword, value, schema, opts) {
const min = schema[keyword]
if (value.length < min) {
return makeError(value.length, `length no less than ${min}`, opts)
}
}
/**
* A map of all object member validation functions for each keyword defined in the JSON Schema.
* @name Schema.validationKeywords
* @type {object}
*/
const validationKeywords = {
/**
* Validates the provided value against all schemas defined in the Schemas `allOf` keyword.
* The instance is valid against if and only if it is valid against all the schemas declared in the Schema's value.
*
* The value of this keyword MUST be an array. This array MUST have at least one element.
* Each element of this array MUST be a valid JSON Schema.
*
* see http://json-schema.org/latest/json-schema-validation.html#anchor82
*
* @name Schema.validationKeywords.allOf
* @method
* @param {*} value Value to be validated.
* @param {object} schema Schema containing the `allOf` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
allOf (value, schema, opts) {
let allErrors = []
schema.allOf.forEach(_schema => {
allErrors = allErrors.concat(validate(value, _schema, opts) || [])
})
return allErrors.length ? allErrors : undefined
},
/**
* Validates the provided value against all schemas defined in the Schemas `anyOf` keyword.
* The instance is valid against this keyword if and only if it is valid against
* at least one of the schemas in this keyword's value.
*
* The value of this keyword MUST be an array. This array MUST have at least one element.
* Each element of this array MUST be an object, and each object MUST be a valid JSON Schema.
* see http://json-schema.org/latest/json-schema-validation.html#anchor85
*
* @name Schema.validationKeywords.anyOf
* @method
* @param {*} value Value to be validated.
* @param {object} schema Schema containing the `anyOf` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
anyOf (value, schema, opts) {
let validated = false
let allErrors = []
schema.anyOf.forEach(_schema => {
const errors = validate(value, _schema, opts)
if (errors) {
allErrors = allErrors.concat(errors)
} else {
validated = true
}
})
return validated ? undefined : allErrors
},
/**
* http://json-schema.org/latest/json-schema-validation.html#anchor70
*
* @name Schema.validationKeywords.dependencies
* @method
* @param {*} value TODO
* @param {object} schema TODO
* @param {object} opts TODO
*/
dependencies (value, schema, opts) {
// TODO
},
/**
* Validates the provided value against an array of possible values defined by the Schema's `enum` keyword
* Validation succeeds if the value is deeply equal to one of the values in the array.
* see http://json-schema.org/latest/json-schema-validation.html#anchor76
*
* @name Schema.validationKeywords.enum
* @method
* @param {*} value Value to validate
* @param {object} schema Schema containing the `enum` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
enum (value, schema, opts) {
const possibleValues = schema.enum
if (utils.findIndex(possibleValues, item => utils.deepEqual(item, value)) === -1) {
return makeError(value, `one of (${possibleValues.join(', ')})`, opts)
}
},
/**
* Validates each of the provided array values against a schema or an array of schemas defined by the Schema's
* `items` keyword
* see http://json-schema.org/latest/json-schema-validation.html#anchor37 for validation rules.
*
* @name Schema.validationKeywords.items
* @method
* @param {*} value Array to be validated.
* @param {object} schema Schema containing the items keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
items (value, schema, opts: any = {}) {
// TODO: additionalItems
let items = schema.items
let errors = []
const checkingTuple = utils.isArray(items)
const length = value.length
for (let prop = 0; prop < length; prop++) {
if (checkingTuple) {
// Validating a tuple, instead of just checking each item against the
// same schema
items = schema.items[prop]
}
opts.prop = prop
errors = errors.concat(validate(value[prop], items, opts) || [])
}
return errors.length ? errors : undefined
},
/**
* Validates the provided number against a maximum value defined by the Schema's `maximum` keyword
* Validation succeeds if the value is a number, and is less than, or equal to, the value of this keyword.
* http://json-schema.org/latest/json-schema-validation.html#anchor17
*
* @name Schema.validationKeywords.maximum
* @method
* @param {*} value Number to validate against the keyword.
* @param {object} schema Schema containing the `maximum` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
maximum (value, schema, opts) {
// Must be a number
const maximum = schema.maximum
// Must be a boolean
// Depends on maximum
// default: false
const exclusiveMaximum = schema.exclusiveMaximum
if (typeof value === typeof maximum && !(exclusiveMaximum ? maximum > value : maximum >= value)) {
return exclusiveMaximum
? makeError(value, `no more than nor equal to ${maximum}`, opts)
: makeError(value, `no more than ${maximum}`, opts)
}
},
/**
* Validates the length of the provided array against a maximum value defined by the Schema's `maxItems` keyword.
* Validation succeeds if the length of the array is less than, or equal to the value of this keyword.
* see http://json-schema.org/latest/json-schema-validation.html#anchor42
*
* @name Schema.validationKeywords.maxItems
* @method
* @param {*} value Array to be validated.
* @param {object} schema Schema containing the `maxItems` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
maxItems (value, schema, opts) {
if (utils.isArray(value)) {
return maxLengthCommon('maxItems', value, schema, opts)
}
},
/**
* Validates the length of the provided string against a maximum value defined in the Schema's `maxLength` keyword.
* Validation succeeds if the length of the string is less than, or equal to the value of this keyword.
* see http://json-schema.org/latest/json-schema-validation.html#anchor26
*
* @name Schema.validationKeywords.maxLength
* @method
* @param {*} value String to be validated.
* @param {object} schema Schema containing the `maxLength` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
maxLength (value, schema, opts) {
return maxLengthCommon('maxLength', value, schema, opts)
},
/**
* Validates the count of the provided object's properties against a maximum value defined in the Schema's
* `maxProperties` keyword.
* Validation succeeds if the object's property count is less than, or equal to the value of this keyword.
* see http://json-schema.org/latest/json-schema-validation.html#anchor54
*
* @name Schema.validationKeywords.maxProperties
* @method
* @param {*} value Object to be validated.
* @param {object} schema Schema containing the `maxProperties` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
maxProperties (value, schema, opts) {
// validate only objects
if (!utils.isObject(value)) return
const maxProperties = schema.maxProperties
const length = Object.keys(value).length
if (length > maxProperties) {
return makeError(length, `no more than ${maxProperties} properties`, opts)
}
},
/**
* Validates the provided value against a minimum value defined by the Schema's `minimum` keyword
* Validation succeeds if the value is a number and is greater than, or equal to, the value of this keyword.
* http://json-schema.org/latest/json-schema-validation.html#anchor21
*
* @name Schema.validationKeywords.minimum
* @method
* @param {*} value Number to validate against the keyword.
* @param {object} schema Schema containing the `minimum` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
minimum (value, schema, opts) {
// Must be a number
const minimum = schema.minimum
// Must be a boolean
// Depends on minimum
// default: false
const exclusiveMinimum = schema.exclusiveMinimum
if (typeof value === typeof minimum && !(exclusiveMinimum ? value > minimum : value >= minimum)) {
return exclusiveMinimum
? makeError(value, `no less than nor equal to ${minimum}`, opts)
: makeError(value, `no less than ${minimum}`, opts)
}
},
/**
* Validates the length of the provided array against a minimum value defined by the Schema's `minItems` keyword.
* Validation succeeds if the length of the array is greater than, or equal to the value of this keyword.
* see http://json-schema.org/latest/json-schema-validation.html#anchor45
*
* @name Schema.validationKeywords.minItems
* @method
* @param {*} value Array to be validated.
* @param {object} schema Schema containing the `minItems` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
minItems (value, schema, opts) {
if (utils.isArray(value)) {
return minLengthCommon('minItems', value, schema, opts)
}
},
/**
* Validates the length of the provided string against a minimum value defined in the Schema's `minLength` keyword.
* Validation succeeds if the length of the string is greater than, or equal to the value of this keyword.
* see http://json-schema.org/latest/json-schema-validation.html#anchor29
*
* @name Schema.validationKeywords.minLength
* @method
* @param {*} value String to be validated.
* @param {object} schema Schema containing the `minLength` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
minLength (value, schema, opts) {
return minLengthCommon('minLength', value, schema, opts)
},
/**
* Validates the count of the provided object's properties against a minimum value defined in the Schema's
* `minProperties` keyword.
* Validation succeeds if the object's property count is greater than, or equal to the value of this keyword.
* see http://json-schema.org/latest/json-schema-validation.html#anchor57
*
* @name Schema.validationKeywords.minProperties
* @method
* @param {*} value Object to be validated.
* @param {object} schema Schema containing the `minProperties` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
minProperties (value, schema, opts) {
// validate only objects
if (!utils.isObject(value)) return
const minProperties = schema.minProperties
const length = Object.keys(value).length
if (length < minProperties) {
return makeError(length, `no more than ${minProperties} properties`, opts)
}
},
/**
* Validates the provided number is a multiple of the number defined in the Schema's `multipleOf` keyword.
* Validation succeeds if the number can be divided equally into the value of this keyword.
* see http://json-schema.org/latest/json-schema-validation.html#anchor14
*
* @name Schema.validationKeywords.multipleOf
* @method
* @param {*} value Number to be validated.
* @param {object} schema Schema containing the `multipleOf` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
multipleOf (value, schema, opts) {
const multipleOf = schema.multipleOf
if (utils.isNumber(value)) {
if ((value / multipleOf) % 1 !== 0) {
return makeError(value, `multipleOf ${multipleOf}`, opts)
}
}
},
/**
* Validates the provided value is not valid with any of the schemas defined in the Schema's `not` keyword.
* An instance is valid against this keyword if and only if it is NOT valid against the schemas in this keyword's
* value.
*
* see http://json-schema.org/latest/json-schema-validation.html#anchor91
* @name Schema.validationKeywords.not
* @method
* @param {*} value to be checked.
* @param {object} schema Schema containing the not keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
not (value, schema, opts) {
if (!validate(value, schema.not, opts)) {
// TODO: better messaging
return makeError('succeeded', 'should have failed', opts)
}
},
/**
* Validates the provided value is valid with one and only one of the schemas defined in the Schema's `oneOf` keyword.
* An instance is valid against this keyword if and only if it is valid against a single schemas in this keyword's
* value.
*
* see http://json-schema.org/latest/json-schema-validation.html#anchor88
* @name Schema.validationKeywords.oneOf
* @method
* @param {*} value to be checked.
* @param {object} schema Schema containing the `oneOf` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
oneOf (value, schema, opts) {
let validated = false
let allErrors = []
schema.oneOf.forEach(_schema => {
const errors = validate(value, _schema, opts)
if (errors) {
allErrors = allErrors.concat(errors)
} else if (validated) {
allErrors = [makeError('valid against more than one', 'valid against only one', opts)]
validated = false
return false
} else {
validated = true
}
})
return validated ? undefined : allErrors
},
/**
* Validates the provided string matches a pattern defined in the Schema's `pattern` keyword.
* Validation succeeds if the string is a match of the regex value of this keyword.
*
* see http://json-schema.org/latest/json-schema-validation.html#anchor33
* @name Schema.validationKeywords.pattern
* @method
* @param {*} value String to be validated.
* @param {object} schema Schema containing the `pattern` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
pattern (value, schema, opts) {
const pattern = schema.pattern
if (utils.isString(value) && !value.match(pattern)) {
return makeError(value, pattern, opts)
}
},
/**
* Validates the provided object's properties against a map of values defined in the Schema's `properties` keyword.
* Validation succeeds if the object's property are valid with each of the schema's in the provided map.
* Validation also depends on the additionalProperties and or patternProperties.
*
* see http://json-schema.org/latest/json-schema-validation.html#anchor64 for more info.
*
* @name Schema.validationKeywords.properties
* @method
* @param {*} value Object to be validated.
* @param {object} schema Schema containing the `properties` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
properties (value, schema, opts: any = {}) {
if (utils.isArray(value)) {
return
}
// Can be a boolean or an object
// Technically the default is an "empty schema", but here "true" is
// functionally the same
const additionalProperties = schema.additionalProperties === undefined ? true : schema.additionalProperties
const validated = []
// "p": The property set from "properties".
// Default is an object
const properties = schema.properties || {}
// "pp": The property set from "patternProperties".
// Default is an object
const patternProperties = schema.patternProperties || {}
let errors = []
utils.forOwn(properties, (_schema, prop) => {
opts.prop = prop
errors = errors.concat(validate(value[prop], _schema, opts) || [])
validated.push(prop)
})
const toValidate = utils.omit(value, validated)
utils.forOwn(patternProperties, (_schema, pattern) => {
utils.forOwn(toValidate, (undef, prop) => {
if (prop.match(pattern)) {
opts.prop = prop
errors = errors.concat(validate(value[prop], _schema, opts) || [])
validated.push(prop)
}
})
})
const keys = Object.keys(utils.omit(value, validated))
// If "s" is not empty, validation fails
if (additionalProperties === false) {
if (keys.length) {
const origProp = opts.prop
opts.prop = ''
addError(`extra fields: ${keys.join(', ')}`, 'no extra fields', opts, errors)
opts.prop = origProp
}
} else if (utils.isObject(additionalProperties)) {
// Otherwise, validate according to provided schema
keys.forEach(prop => {
opts.prop = prop
errors = errors.concat(validate(value[prop], additionalProperties, opts) || [])
})
}
return errors.length ? errors : undefined
},
/**
* Validates the provided object's has all properties listed in the Schema's `properties` keyword array.
* Validation succeeds if the object contains all properties provided in the array value of this keyword.
* see http://json-schema.org/latest/json-schema-validation.html#anchor61
*
* @name Schema.validationKeywords.required
* @method
* @param {*} value Object to be validated.
* @param {object} schema Schema containing the `required` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
required (value, schema, opts: any = {}) {
const required = schema.required
const errors = []
if (!opts.existingOnly) {
required.forEach(prop => {
if (utils.get(value, prop) === undefined) {
const prevProp = opts.prop
opts.prop = prop
addError(undefined, 'a value', opts, errors)
opts.prop = prevProp
}
})
}
return errors.length ? errors : undefined
},
/**
* Validates the provided value's type is equal to the type, or array of types, defined in the Schema's `type`
* keyword.
* see http://json-schema.org/latest/json-schema-validation.html#anchor79
*
* @name Schema.validationKeywords.type
* @method
* @param {*} value Value to be validated.
* @param {object} schema Schema containing the `type` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
type (value, schema, opts) {
let type = schema.type
let validType
// Can be one of several types
if (utils.isString(type)) {
type = [type]
}
// Try to match the value against an expected type
type.forEach(_type => {
// TODO: throw an error if type is not defined
if (types[_type](value, schema, opts)) {
// Matched a type
validType = _type
return false
}
})
// Value did not match any expected type
if (!validType) {
return makeError(
value !== undefined && value !== null ? typeof value : '' + value,
`one of (${type.join(', ')})`,
opts
)
}
// Run keyword validators for matched type
// http://json-schema.org/latest/json-schema-validation.html#anchor12
const validator = typeGroupValidators[validType]
if (validator) {
return validator(value, schema, opts)
}
},
/**
* Validates the provided array values are unique.
* Validation succeeds if the items in the array are unique, but only if the value of this keyword is true
* see http://json-schema.org/latest/json-schema-validation.html#anchor49
*
* @name Schema.validationKeywords.uniqueItems
* @method
* @param {*} value Array to be validated.
* @param {object} schema Schema containing the `uniqueItems` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
uniqueItems (value, schema, opts) {
if (value?.length && schema.uniqueItems) {
const length = value.length
let item, i, j
// Check n - 1 items
for (i = length - 1; i > 0; i--) {
item = value[i]
// Only compare against unchecked items
for (j = i - 1; j >= 0; j--) {
// Found a duplicate
if (utils.deepEqual(item, value[j])) {
return makeError(item, 'no duplicates', opts)
}
}
}
}
}
}
/**
* @ignore
*/
function runOps (ops, value, schema, opts) {
let errors = []
ops.forEach(op => {
if (schema[op] !== undefined) {
errors = errors.concat(validationKeywords[op](value, schema, opts) || [])
}
})
return errors.length ? errors : undefined
}
/**
* Validation keywords validated for any type:
*
* - `enum`
* - `type`
* - `allOf`
* - `anyOf`
* - `oneOf`
* - `not`
*
* @name Schema.ANY_OPS
* @type {string[]}
*/
const ANY_OPS = ['enum', 'type', 'allOf', 'anyOf', 'oneOf', 'not']
/**
* Validation keywords validated for array types:
*
* - `items`
* - `maxItems`
* - `minItems`
* - `uniqueItems`
*
* @name Schema.ARRAY_OPS
* @type {string[]}
*/
const ARRAY_OPS = ['items', 'maxItems', 'minItems', 'uniqueItems']
/**
* Validation keywords validated for numeric (number and integer) types:
*
* - `multipleOf`
* - `maximum`
* - `minimum`
*
* @name Schema.NUMERIC_OPS
* @type {string[]}
*/
const NUMERIC_OPS = ['multipleOf', 'maximum', 'minimum']
/**
* Validation keywords validated for object types:
*
* - `maxProperties`
* - `minProperties`
* - `required`
* - `properties`
* - `dependencies`
*
* @name Schema.OBJECT_OPS
* @type {string[]}
*/
const OBJECT_OPS = ['maxProperties', 'minProperties', 'required', 'properties', 'dependencies']
/**
* Validation keywords validated for string types:
*
* - `maxLength`
* - `minLength`
* - `pattern`
*
* @name Schema.STRING_OPS
* @type {string[]}
*/
const STRING_OPS = ['maxLength', 'minLength', 'pattern']
/**
* http://json-schema.org/latest/json-schema-validation.html#anchor75
* @ignore
*/
const validateAny = (value, schema, opts) => runOps(ANY_OPS, value, schema, opts)
/**
* Validates the provided value against a given Schema according to the http://json-schema.org/ v4 specification.
*
* @name Schema.validate
* @method
* @param {*} value Value to be validated.
* @param {object} schema Valid Schema according to the http://json-schema.org/ v4 specification.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
const validate = (value, schema, opts: any = {}) => {
let errors = []
opts.ctx = opts.ctx || { value, schema }
let shouldPop
const prevProp = opts.prop
if (schema === undefined) {
return
}
if (!utils.isObject(schema)) {
throw utils.err(`${DOMAIN}#validate`)(500, `Invalid schema at path: "${opts.path}"`)
}
if (opts.path === undefined) {
opts.path = []
}
// Track our location as we recurse
if (opts.prop !== undefined) {
shouldPop = true
opts.path.push(opts.prop)
opts.prop = undefined
}
// Validate against parent schema
if (schema.extends) {
// opts.path = path
// opts.prop = prop
if (utils.isFunction(schema.extends.validate)) {
errors = errors.concat(schema.extends.validate(value, opts) || [])
} else {
errors = errors.concat(validate(value, schema.extends, opts) || [])
}
}
if (value === undefined) {
// Check if property is required
if (schema.required === true && !opts.existingOnly) {
addError(value, 'a value', opts, errors)
}
if (shouldPop) {
opts.path.pop()
opts.prop = prevProp
}
return errors.length ? errors : undefined
}
errors = errors.concat(validateAny(value, schema, opts) || [])
if (shouldPop) {
opts.path.pop()
opts.prop = prevProp
}
return errors.length ? errors : undefined
}
// These strings are cached for optimal performance of the change detection
// boolean - Whether a Record is changing in the current execution frame
const changingPath = 'changing'
// string[] - Properties that have changed in the current execution frame
const changedPath = 'changed'
// Object[] - History of change records
const changeHistoryPath = 'history'
// boolean - Whether a Record is currently being instantiated
const creatingPath = 'creating'
// number - The setTimeout change event id of a Record, if any
const eventIdPath = 'eventId'
// boolean - Whether to skip validation for a Record's currently changing property
const noValidatePath = 'noValidate'
// boolean - Whether to preserve Change History for a Record
const keepChangeHistoryPath = 'keepChangeHistory'
// boolean - Whether to skip change notification for a Record's currently
// changing property
const silentPath = 'silent'
const validationFailureMsg = 'validation failed'
/**
* A map of validation functions grouped by type.
*
* @name Schema.typeGroupValidators
* @type {object}
*/
const typeGroupValidators = {
/**
* Validates the provided value against the schema using all of the validation keywords specific to instances of an
* array.
* The validation keywords for the type `array` are:
* ```
* ['items', 'maxItems', 'minItems', 'uniqueItems']
* ```
* see http://json-schema.org/latest/json-schema-validation.html#anchor25
*
* @name Schema.typeGroupValidators.array
* @method
* @param {*} value Array to be validated.
* @param {object} schema Schema containing at least one array keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
array: (value, schema, opts?) => runOps(ARRAY_OPS, value, schema, opts),
/**
* Validates the provided value against the schema using all of the validation keywords specific to instances of an
* integer.
* The validation keywords for the type `integer` are:
* ```
* ['multipleOf', 'maximum', 'minimum']
* ```
* @name Schema.typeGroupValidators.integer
* @method
* @param {*} value Number to be validated.
* @param {object} schema Schema containing at least one `integer` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
integer: (value, schema, opts) =>
// Additional validations for numerics are the same
typeGroupValidators.numeric(value, schema, opts),
/**
* Validates the provided value against the schema using all of the validation keywords specific to instances of an
* number.
* The validation keywords for the type `number` are:
* ```
* ['multipleOf', 'maximum', 'minimum']
* ```
* @name Schema.typeGroupValidators.number
* @method
* @param {*} value Number to be validated.
* @param {object} schema Schema containing at least one `number` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
number: (value, schema, opts) =>
// Additional validations for numerics are the same
typeGroupValidators.numeric(value, schema, opts),
/**
* Validates the provided value against the schema using all of the validation keywords specific to instances of a
* number or integer.
* The validation keywords for the type `numeric` are:
* ```
* ['multipleOf', 'maximum', 'minimum']
* ```
* See http://json-schema.org/latest/json-schema-validation.html#anchor13.
*
* @name Schema.typeGroupValidators.numeric
* @method
* @param {*} value Number to be validated.
* @param {object} schema Schema containing at least one `numeric` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
numeric: (value, schema, opts) => runOps(NUMERIC_OPS, value, schema, opts),
/**
* Validates the provided value against the schema using all of the validation keywords specific to instances of an
* object.
* The validation keywords for the type `object` are:
* ```
* ['maxProperties', 'minProperties', 'required', 'properties', 'dependencies']
* ```
* See http://json-schema.org/latest/json-schema-validation.html#anchor53.
*
* @name Schema.typeGroupValidators.object
* @method
* @param {*} value Object to be validated.
* @param {object} schema Schema containing at least one `object` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
object: (value, schema, opts) => runOps(OBJECT_OPS, value, schema, opts),
/**
* Validates the provided value against the schema using all of the validation keywords specific to instances of an
* string.
* The validation keywords for the type `string` are:
* ```
* ['maxLength', 'minLength', 'pattern']
* ```
* See http://json-schema.org/latest/json-schema-validation.html#anchor25.
*
* @name Schema.typeGroupValidators.string
* @method
* @param {*} value String to be validated.
* @param {object} schema Schema containing at least one `string` keyword.
* @param {object} [opts] Configuration options.
* @returns {(array|undefined)} Array of errors or `undefined` if valid.
*/
string: (value, schema, opts?) => runOps(STRING_OPS, value, schema, opts)
}
export interface PropertyDefinition {
type: string | string[]
track?: boolean
description?: string
indexed?: boolean
items?: PropertyDefinition
minItems?: number
uniqueItems?: boolean
extends?: Schema
get?: Function
properties?: { [name: string]: PropertyDefinition }
required?: string[] | boolean
maximum?: number
exclusiveMaximum?: boolean
minimum?: number
exclusiveMinimum?: boolean
additionalProperties?: boolean
}
export interface SchemaDefinition {
type?: string
description?: string
$schema?: string
title?: string
properties?: { [name: string]: PropertyDefinition | any }
extends?: SchemaDefinition | Schema
items?: SchemaDefinition | Schema
track?: boolean
additionalProperties?
required?: string[]
}
/**
* js-data's Schema class.
*
* @example <caption>Schema#constructor</caption>
* const JSData = require('js-data');
* const { Schema } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* const PostSchema = new Schema({
* type: 'object',
* properties: {
* title: { type: 'string' }
* }
* });
* PostSchema.validate({ title: 1234 });
*
* @example
* const JSData = require('js-data');
* const { Schema } = JSData;
* console.log('Using JSData v' + JSData.version.full);
*
* class CustomSchemaClass extends Schema {
* foo () { return 'bar'; }
* static beep () { return 'boop'; }
* }
* const customSchema = new CustomSchemaClass();
* console.log(customSchema.foo());
* console.log(CustomSchemaClass.beep());
*
* @class Schema
* @extends Component
* @param {object} definition Schema definition according to json-schema.org
*/
export default class Schema extends Component {
type: string;
properties: any;
private readonly extends: Schema;
private readonly items: Schema;
private readonly track: any;
private readonly additionalProperties: any;
constructor (definition: SchemaDefinition = {}) {
super()