-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
793 lines (596 loc) · 16.6 KB
/
index.js
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
'use strict';
const describers = {
ascii: require('./describers/ascii'),
csv: require('./describers/csv'),
js: require('./describers/js')
};
const deepCopy = require('deep-copy');
function getType(value) {
if (value === null) {
return 'null';
}
if (Array.isArray(value)) {
return 'array';
}
return typeof value;
}
function getLength(value) {
if (value && typeof value === 'object') {
return Object.keys(value).length;
}
if (!value || !value.hasOwnProperty('length')) {
return 'undefined';
}
return value.length;
}
class MyTypeError extends TypeError {
constructor(message, value, code) {
super(message);
this.name = 'MyTypeError';
this.value = value;
this.code = code;
this._baseMessage = message;
this._valueName = '';
this.updateMessage();
}
addParentProperty(name) {
if (typeof name === 'number') {
// array index
this._valueName = `[${name}]${this._valueName}`;
} else {
// object property name
this._valueName = `.${name}${this._valueName}`;
}
this.updateMessage();
}
updateMessage() {
this.message = this._baseMessage.
replace('%type', getType(this.value)).
replace('%name', this._valueName || 'Value').
replace('%value', this.value).
replace('%length', getLength(this.value));
}
}
class Test {
constructor(failure, message, code) {
if (code && typeof code !== 'number' && typeof code !== 'string') {
throw new MyTypeError('The given error code must be a string or number (found: %type)', code);
}
this.failure = failure;
this.message = JSON.stringify(message);
this.code = code ? JSON.stringify(code) : 'undefined';
}
toString() {
return ` if (${this.failure}) { throw new MyTypeError(${this.message}, value, ${this.code}); }`;
}
}
class Type {
constructor() {
this.tests = [];
this.assertFn = undefined;
this.isOptional = false;
this.defaultValue = undefined;
}
optional() {
this.isOptional = true;
this.assertFn = undefined;
this.assertDefaultValue();
return this;
}
addTest(failure, message, code) {
this.tests.push(new Test(failure, message, code));
this.assertFn = undefined;
}
assertDefaultValue() {
if (this.defaultValue !== undefined) {
// we don't invoke functions because of possible side-effects during setup
if (typeof this.defaultValue !== 'function') {
this.assert(this.defaultValue);
}
}
}
getTests() {
const optionalTest = this.isOptional ?
' if (value === undefined || value === null) { return; }\n' :
new Test('value === undefined || value === null', '%name is not optional');
return [optionalTest].concat(this.tests);
}
assert(value) {
if (!this.assertFn) {
const tests = this.getTests();
this.assertFn = new Function('value', 'MyTypeError', tests.join('\n'));
}
this.assertFn(value, MyTypeError);
}
describe(path, output, options) {
const tests = this.getTests();
for (const test of tests) {
if (test instanceof Test) {
const code = test.code === 'undefined' ? null : JSON.parse(test.code);
let message = JSON.parse(test.message);
if (path.length === 0) {
message = message.replace('%name', 'Value');
} else {
message = message.replace('%name', path[path.length - 1]);
}
const entry = {
path,
failureCondition: test.failure,
message,
code
};
if (options) {
if (options.filter) {
if (!options.filter(entry)) {
// skip this entry
continue;
}
}
if (options.transform) {
options.transform(entry);
}
}
output.push(entry);
}
}
}
}
class ScalarType extends Type {
values(values, code) {
if (!Array.isArray(values)) {
throw new MyTypeError('The given values are not in an array (found: %type)', values);
}
if (values.length === 0) {
throw new MyTypeError('The given values are an empty array', values);
}
for (const value of values) {
this.assert(value);
}
values = JSON.stringify(values);
this.addTest(`!${values}.includes(value)`, `%name must be one of ${values}`, code);
this.assertDefaultValue();
return this;
}
default(value) {
if (value !== null && typeof value === 'object') {
throw new MyTypeError('The default value is not a scalar type (found: %type)', value);
}
this.defaultValue = value;
this.assertDefaultValue();
return this;
}
_createDefaultValue() {
if (typeof this.defaultValue === 'function') {
return this.defaultValue();
}
return this.defaultValue;
}
}
class StringType extends ScalarType {
constructor(code) {
super();
this.addTest("typeof value !== 'string'", '%name is not a string (found: %type)', code);
}
length(min, max, code) {
if (min !== null && min !== undefined && min !== 0) {
this.min(min, code);
}
if (max !== null && max !== undefined && max !== Infinity) {
this.max(max, code);
}
return this;
}
min(min, code) {
if (!Number.isInteger(min)) {
throw new MyTypeError('The min-length is not an integer (found: %type "%value")', min);
}
this.addTest(`value.length < ${min}`, `%name string length must be >= ${min} (found: %length)`, code);
this.assertDefaultValue();
return this;
}
max(max, code) {
if (!Number.isInteger(max)) {
throw new MyTypeError('The max-length is not an integer (found: %type "%value")', max);
}
this.addTest(`value.length > ${max}`, `%name string length must be <= ${max} (found: %length)`, code);
this.assertDefaultValue();
return this;
}
regexp(re, code) {
if (!(re instanceof RegExp)) {
throw new MyTypeError('The value provided is not a regular expression (found: %type "%value")', re);
}
re = re.toString();
this.addTest(`!${re}.test(value)`, `%name does not match regular expression: ${re}`, code);
this.assertDefaultValue();
return this;
}
}
class NumberType extends ScalarType {
constructor(code) {
super();
this.addTest("typeof value !== 'number'", '%name is not a number (found: %type))', code);
this.addTest('value !== value', '%name is NaN', code);
}
range(min, max, code) {
if (min !== null && min !== undefined && min !== -Infinity) {
this.min(min, code);
}
if (max !== null && max !== undefined && max !== Infinity) {
this.max(max, code);
}
return this;
}
min(min, code) {
if (typeof min !== 'number' || min !== min) { // eslint-disable-line no-self-compare
throw new MyTypeError('The min-value is not a number (found: %type "%value")', min);
}
this.addTest(`value < ${min}`, `%name must be >= ${min} (found: %value)`, code);
this.assertDefaultValue();
return this;
}
max(max, code) {
if (typeof max !== 'number' || max !== max) { // eslint-disable-line no-self-compare
throw new MyTypeError('The max-value is not a number (found: %type "%value")', max);
}
this.addTest(`value > ${max}`, `%name must be <= ${max} (found: %value)`, code);
this.assertDefaultValue();
return this;
}
}
class IntType extends ScalarType {
constructor(code) {
super();
this.addTest('!Number.isInteger(value)', '%name is not an integer (found: %type)', code);
}
range(min, max, code) {
if (min !== null && min !== undefined && min !== -Infinity) {
this.min(min, code);
}
if (max !== null && max !== undefined && max !== Infinity) {
this.max(max, code);
}
return this;
}
min(min, code) {
if (!Number.isInteger(min)) {
throw new MyTypeError('The min-value is not an integer (found: %type "%value")', min);
}
this.addTest(`value < ${min}`, `%name must be >= ${min} (found: %value)`, code);
this.assertDefaultValue();
return this;
}
max(max, code) {
if (!Number.isInteger(max)) {
throw new MyTypeError('The max-value is not an integer (found: %type "%value")', max);
}
this.addTest(`value > ${max}`, `%name must be <= ${max} (found: %value)`, code);
this.assertDefaultValue();
return this;
}
}
class BooleanType extends ScalarType {
constructor(code) {
super();
this.addTest("typeof value !== 'boolean'", '%name is not a boolean (found: %type)', code);
}
}
class AnyType extends Type {
_createDefaultValue() {
return undefined;
}
}
class MixedType extends Type {
constructor(types) {
super();
this.subTypes = types || [];
for (const type of this.subTypes) {
if (!(type instanceof Type)) {
throw new MyTypeError(`Type is not a real type`, type);
}
}
}
_createDefaultValue() {
for (const type of this.subTypes) {
const defaultValue = type._createDefaultValue();
if (defaultValue !== undefined) {
return defaultValue;
}
}
return undefined;
}
assert(value) {
super.assert(value);
if (value !== undefined) {
let lastError;
for (const type of this.subTypes) {
try {
type.assert(value);
return; // success!
} catch (error) {
lastError = error;
}
}
if (lastError) {
throw lastError;
}
}
}
}
class ArrayType extends Type {
constructor(elementType, code) {
super();
this.elementType = elementType;
this.createFn = undefined;
this.addTest('!Array.isArray(value)', '%name is not an array (found: %type)', code);
if (!(elementType instanceof Type)) {
throw new MyTypeError(`Type for elements is not a real type`, elementType);
}
}
default(value) {
if (typeof value === 'function') {
this.defaultValue = value;
} else if (Array.isArray(value)) {
this.defaultValue = deepCopy(value);
} else {
throw new MyTypeError('The default value is not an array (found: %type)', value);
}
this.assertDefaultValue();
return this;
}
_createDefaultValueFactory() {
if (typeof this.defaultValue === 'function') {
this.createFn = this.defaultValue;
} else {
this.createFn = new Function(`return ${JSON.stringify(this.defaultValue)};`);
}
}
_createDefaultValue() {
if (!this.createFn) {
this._createDefaultValueFactory();
}
return this.createFn();
}
length(min, max, code) {
if (min !== null && min !== undefined && min !== 0) {
this.min(min, code);
}
if (max !== null && max !== undefined && max !== Infinity) {
this.max(max, code);
}
return this;
}
min(min, code) {
if (!Number.isInteger(min)) {
throw new MyTypeError('The min-length is not an integer (found: %type "%value")', min);
}
this.addTest(`value.length < ${min}`, `%name array length must be >= ${min} (found: %length)`, code);
this.assertDefaultValue();
return this;
}
max(max, code) {
if (!Number.isInteger(max)) {
throw new MyTypeError('The max-length is not an integer (found: %type "%value")', max);
}
this.addTest(`value.length > ${max}`, `%name array length must be <= ${max} (found: %length)`, code);
this.assertDefaultValue();
return this;
}
assert(value) {
super.assert(value);
if (this.isOptional && (value === undefined || value === null)) {
return;
}
for (let i = 0; i < value.length; i += 1) {
try {
this.elementType.assert(value[i]);
} catch (error) {
if (error.addParentProperty) {
error.addParentProperty(i);
}
throw error;
}
}
}
describe(path, output, options) {
super.describe(path, output, options);
path = path.slice();
if (path.length > 0) {
path[path.length - 1] += '[index]';
}
this.elementType.describe(path, output, options);
}
}
class ObjectType extends Type {
constructor(propTypes, code) {
super();
this.addTest("value === null || typeof value !== 'object' || Array.isArray(value)", '%name is not an object (found: %type)', code);
if (!propTypes || typeof propTypes !== 'object') {
throw new MyTypeError('Expected an object for properties (found: %type)', propTypes);
}
if (Array.isArray(propTypes)) {
throw new MyTypeError('Expected an object for properties (found: array)');
}
this.propTypes = propTypes;
this.propNames = Object.keys(propTypes);
this.dict = null;
for (const prop of this.propNames) {
const type = propTypes[prop];
if (!(type instanceof Type)) {
throw new MyTypeError(`Type for property "${prop}" is not a real type`, type);
}
}
this.createFn = undefined;
}
dictionary(propertyType, valueType) {
if (!(propertyType instanceof Type)) {
throw new MyTypeError(`Property-type is not a real type`, propertyType);
}
if (!(valueType instanceof Type)) {
throw new MyTypeError(`Value-type is not a real type`, valueType);
}
this.dict = { propertyType, valueType };
return this;
}
length(min, max, code) {
if (min !== null && min !== undefined && min !== 0) {
this.min(min, code);
}
if (max !== null && max !== undefined && max !== Infinity) {
this.max(max, code);
}
return this;
}
min(min, code) {
if (!Number.isInteger(min)) {
throw new MyTypeError('The min-length is not an integer (found: %type "%value")', min);
}
const test = `Object.keys(value).length < ${min}`;
const msg = `%name property count must be >= ${min} (found: %length)`;
this.addTest(test, msg, code);
return this;
}
max(max, code) {
if (!Number.isInteger(max)) {
throw new MyTypeError('The max-length is not an integer (found: %type "%value")', max);
}
const test = `Object.keys(value).length > ${max}`;
const msg = `%name property count must be <= ${max} (found: %length)`;
this.addTest(test, msg, code);
return this;
}
_assertProperty(value, name) {
const type = this.propTypes[name];
if (type) {
type.assert(value[name]);
} else {
if (!this.dict) {
throw new MyTypeError(`Unknown property "${name}"`, value[name]);
}
this.dict.propertyType.assert(name);
this.dict.valueType.assert(value[name]);
}
}
assert(value) {
super.assert(value);
if (this.isOptional && (value === undefined || value === null)) {
return;
}
// test provided properties
const propNames = Object.keys(value);
for (const prop of propNames) {
try {
this._assertProperty(value, prop);
} catch (error) {
if (error.addParentProperty) {
error.addParentProperty(prop);
}
throw error;
}
}
// test properties that should exist but were not present in the given value
for (const prop of this.propNames) {
if (!value.hasOwnProperty(prop)) {
const type = this.propTypes[prop];
try {
type.assert(value[prop]);
} catch (error) {
if (error.addParentProperty) {
error.addParentProperty(prop);
}
throw error;
}
}
}
}
_createDefaultValueFactory() {
if (this.isOptional) {
return new Function('return undefined;');
}
const body = [];
for (const prop of this.propNames) {
const propName = JSON.stringify(prop);
body.push(` ${propName}: types[${propName}]._createDefaultValue()`);
}
return new Function('types', `return {\n${body.join(',\n ')}\n};`);
}
_createDefaultValue() {
if (!this.createFn) {
this.createFn = this._createDefaultValueFactory();
}
return this.createFn(this.propTypes);
}
create(data) {
const obj = this._createDefaultValue();
return this.update(obj, data);
}
update(obj, data) {
if (!obj || typeof obj !== 'object') {
// allow the not-an-object assertion failure to kick in
this.assert(obj);
}
if (!data || typeof data !== 'object') {
// allow the not-an-object assertion failure to kick in
this.assert(data);
}
obj = this._merge(obj, data);
this.assert(obj);
return obj;
}
_merge(oldValue, newValue) {
if (!newValue || typeof newValue !== 'object' || Array.isArray(newValue)) {
return newValue;
}
if (!oldValue || typeof oldValue !== 'object') {
return newValue;
}
// merge oldValue with newValue and return oldValue
const propNames = Object.keys(newValue);
for (const prop of propNames) {
oldValue[prop] = this._merge(oldValue[prop], newValue[prop]);
}
return oldValue;
}
describe(path, output, options) {
super.describe(path, output, options);
for (const prop of this.propNames) {
const type = this.propTypes[prop];
type.describe(path.concat(prop), output, options);
}
}
}
exports.MyTypeError = MyTypeError;
exports.string = function (code) {
return new StringType(code);
};
exports.number = function (code) {
return new NumberType(code);
};
exports.int = function (code) {
return new IntType(code);
};
exports.bool = function (code) {
return new BooleanType(code);
};
exports.any = function () {
return new AnyType();
};
exports.mixed = function (types) {
return new MixedType(types);
};
exports.object = function (propTypes, code) {
return new ObjectType(propTypes, code);
};
exports.array = function (elementType, code) {
return new ArrayType(elementType, code);
};
exports.describe = function (schema, style, fields, options) {
const describer = describers[style];
if (!describer) {
throw new Error(`No describer "${style}" found`);
}
fields = fields || ['path', 'code', 'message', 'failureCondition'];
const entries = [];
schema.describe([], entries, options);
return describer(entries, fields, options || {});
};