-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathxschema.js
5964 lines (5000 loc) · 163 KB
/
xschema.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
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
// xschema.js <https://github.com/jsstuff/xschema>
(function($export, $as, $xex) {
"use strict";
function throwTypeError(msg) { throw new TypeError(msg); }
const xex = $xex;
if (!xex) throwTypeError("'xschema' requires 'xex' library");
const isArray = Array.isArray;
const freeze = Object.freeze;
const hasOwn = Object.prototype.hasOwnProperty;
const toString = Object.prototype.toString;
/**
* The xschema namespace.
*
* @namespace
* @alias xschema
*/
const xschema = $export[$as] = {};
/**
* Version information in a "major.minor.patch" form.
*
* @alias xmodel.VERSION
*/
xschema.VERSION = "1.1.0";
/**
* Private object that is used to check whether an object is an xschema's
* environment (xschema namespace, possibly extended).
*
* @alias xschema.SENTINEL
*/
const SENTINEL = xschema.SENTINEL = freeze({});
// ============================================================================
// [xschema.configuration]
// ============================================================================
/**
* Debug option - Verify normalized schemas for correctness.
*
* @private
*/
const kConfigVerifySchemas = false;
/**
* Tuning option - Turn on/off `Object.keys().length` optimization.
*
* If set to true the code generator will use `Object.keys(obj).length` to get
* the total number of properties `obj` has. This is turned off by default as it
* has been observed that simple `for (k in obj) props++` is much faster than
* calling `Object.keys().length`.
*
* @private
*/
const kConfigUseObjectKeysAsCount = false;
/**
* Tuning option - Turn on/off `Number.isInteger()` check.
*
* If set to true the code generator will use `Number.isInteger()` to test if
* the value is integer. If the option is off the code generator will generate
* `(x|0) === x` for 32-bit and less integer checks and `Math.floor(x) === x`
* for the rest.
*
* @private
*/
const kConfigUseNumberIsInteger = typeof Number.isInteger === "function";
// ============================================================================
// [xschema.constants]
// ============================================================================
/**
* Processing option - none.
*
* This constant has been added so the code that is using data processing can
* be more clear in cases where no options are used.
*
* @alias xschema.kNoOptions
*/
const kNoOptions = xschema.kNoOptions = 0;
/**
* Processing option - extract top fields from the source object.
*
* This option is used in case that you have a top level object that contains
* keys/values and you want to extract everything matching your schema out of
* it. Only keys defined in the schema are considered, others ignored silently.
*
* It's an error if user access control is enabled and the source object
* contains a property that the user doesn't have access to. In such case
* a "PermissionDenied" error will be generated.
*
* NOTE: This option can be combined with `kExtractAll`, in such case the
* latter has priority.
*
* @alias xschema.kExtractTop
*/
const kExtractTop = xschema.kExtractTop = 0x0001;
/**
* Processing option - extract nested fields from the source object.
*
* This option is used in case you have a top level object that doesn't contain
* any other properties than defined by the schema, but nested objects can. When
* combined with `xschema.kExtractTop` it efficiently forms `xschema.kExtractAll`.
*
* Extraction from nested objects follows the same rules as extraction from top
* level object. See `xschema.kExtractTop` for more detailed information.
*
* @alias xschema.kExtractNested
*/
const kExtractNested = xschema.kExtractNested = 0x0002;
/**
* Processing option - extract all fields from the source object and all nested
* objects.
*
* This is like `kExtractTop`, but it takes effect for any object, top level or
* nested. This option can be efficiently used to filter properties from source
* objects into properties defined by the schema.
*
* NOTE: This is a combination of `xschema.kExtractTop` and `xschema.kExtractNested`.
*
* @alias xschema.kExtractAll
*/
const kExtractAll = xschema.kExtractAll = 0x0003;
/**
* Processing option - delta mode.
*
* Delta mode allows to validate a data that contains only changes (deltas).
* When used all required fields become optional and default values won't
* be used to substitute data that is not present.
*
* NOTE: Delta updating makes sense when updating something that already exists,
* but it doesn't make sense for data insertion, where you probably don't want
* to omit what is 'required'. If your stack doesn't use delta updates or you
* use xschema for an input validation only, this feature can be completely
* ignored.
*
* @alias xschema.kDeltaMode
*/
const kDeltaMode = xschema.kDeltaMode = 0x0004;
/**
* Processing option - test-mode.
*
* Flag used internally to generate code for `xschema.test()` like validation.
*
* @private
*/
const kTestOnly = 0x0008;
/**
* Procession option - Flag used internally to force code generator to emit
* access control checks.
*
* @private
*/
const kTestAccess = 0x0010;
/**
* Procession option - Accumulate all errors instead of bailing out on the
* first failure.
*
* When this option is used the error object thrown in case of one or more
* error will always contain `errors` array that is populated by all errors
* found. This option is useful in cases that you want to see all problems
* of the input data - for example you want to highlight fields that are
* wrong on the client or perform an additional processing/fixing.
*
* @alias xschema.kAccumulateErrors
*/
const kAccumulateErrors = xschema.kAccumulateErrors = 0x1000;
/**
* Minimum value of a 8-bit signed integer.
*
* @alias xschema.kInt8Min
*/
const kInt8Min = xschema.kInt8Min = -128;
/**
* Maximum value of a 8-bit signed integer.
*
* @alias xschema.kInt8Max
*/
const kInt8Max = xschema.kInt8Max = 127;
/**
* Minimum value of a 8-bit unsigned integer.
*
* @alias xschema.kUInt8Min
*/
const kUInt8Min = xschema.kUInt8Min = 0;
/**
* Maximum value of a 8-bit unsigned integer.
*
* @alias xschema.kUInt8Max
*/
const kUInt8Max = xschema.kUInt8Max = 255;
/**
* Minimum value of a 16-bit signed integer.
*
* @alias xschema.kInt16Min
*/
const kInt16Min = xschema.kInt16Min = -32768;
/**
* Maximum value of a 16-bit signed integer.
*
* @alias xschema.kInt16Max
*/
const kInt16Max = xschema.kInt16Max = 32767;
/**
* Minimum value of a 16-bit unsigned integer.
*
* @alias xschema.kUInt16Min
*/
const kUInt16Min = xschema.kUInt16Min = 0;
/**
* Maximum value of a 16-bit unsigned integer.
*
* @alias xschema.kUInt16Max
*/
const kUInt16Max = xschema.kUInt16Max = 65535;
/**
* Minimum value of a 24-bit signed integer.
*
* @alias xschema.kInt24Min
*/
const kInt24Min = xschema.kInt24Min = -8388608;
/**
* Maximum value of a 24-bit signed integer.
*
* @alias xschema.kInt24Max
*/
const kInt24Max = xschema.kInt24Max = 8388607;
/**
* Minimum value of a 24-bit unsigned integer.
*
* @alias xschema.kUInt24Min
*/
const kUInt24Min = xschema.kUInt24Min = 0;
/**
* Maximum value of a 24-bit unsigned integer.
*
* @alias xschema.kUInt24Max
*/
const kUInt24Max = xschema.kUInt24Max = 16777215;
/**
* Minimum value of a 32-bit signed integer.
*
* @alias xschema.kInt32Min
*/
const kInt32Min = xschema.kInt32Min = -2147483648;
/**
* Maximum value of a 32-bit signed integer.
*
* @alias xschema.kInt32Max
*/
const kInt32Max = xschema.kInt32Max = 2147483647;
/**
* Minimum value of a 32-bit unsigned integer.
*
* @alias xschema.kUInt32Min
*/
const kUInt32Min = xschema.kUInt32Min = 0;
/**
* Maximum value of a 32-bit unsigned integer.
*
* @alias xschema.kUInt32Max
*/
const kUInt32Max = xschema.kUInt32Max = 4294967295;
/**
* Minimum value of a 53-bit signed integer.
*
* Should be fully compliant with ES6's `Number.isSafeInteger()`.
*
* @alias xschema.kInt53Min
*/
const kInt53Min = xschema.kInt53Min = -9007199254740991;
/**
* Maximum value of a 53-bit signed integer.
*
* Should be fully compliant with ES6's `Number.isSafeInteger()`.
*
* @alias xschema.kInt53Max
*/
const kInt53Max = xschema.kInt53Max = 9007199254740991;
/**
* Minimum value of a 64-bit signed integer (as string).
*
* @alias xschema.kInt64Min
*/
const kInt64Min = xschema.kInt64Min = "-9223372036854775808";
/**
* Maximum value of a 64-bit signed integer (as string).
*
* @alias xschema.kInt64Max
*/
const kInt64Max = xschema.kInt64Max = "9223372036854775807";
/**
* Minimum value of a 64-bit unsigned integer (as string).
*
* @alias xschema.kUInt64Min
*/
const kUInt64Min = xschema.kUInt64Min = "0";
/**
* Maximum value of a 64-bit unsigned integer (as string).
*
* @alias xschema.kUInt64Max
*/
const kUInt64Max = xschema.kUInt64Max = "18446744073709551615";
/**
* Minimum year that is handled by xschema library.
*
* @alias xschema.kYearMin
*/
const kYearMin = xschema.kYearMin = 1;
// ============================================================================
// [xschema.regexp]
// ============================================================================
// Some useful regexps.
const reNewLine = /\n/g; // Matches a newline (test).
const reUnescapeFieldName = /\\(.)/g; // Unescape field name (replace).
const reInvalidIdentifier = /[^\w\$]/; // Invalid identifier (test).
// Schema specific - type-name can be matched by '[A-Za-z_][\w-]*':
const reTypeArgs = /^([A-Za-z_][\w-]*)\(([^\(]+)\)/; // Matches `type(args)`.
const reTypeArray = /^([A-Za-z_][\w-]*\??)\[(\d+)?(:)?(\d+)?\](\?)?/; // Matches `type?[x:y]`.
const reTypeNullable = /\?$/; // Nullable type suffix "...?" (match).
const reInclude = /^\$include/; // Test for $include directive.
// Test if the given access right is valid (forbid some characters that can
// violate with future boolean algebra that can be applied to the AC system).
const reInvalidAccessName = /[\x00-\x1F\s\(\)\[\]\{\}\&\|\*\^\!%]/;
// ============================================================================
// [xschema.internals]
// ============================================================================
/**
* Mask of all options that take effect in cache lookup. These options that are
* not here are always checked in the validator function itself and won't cause
* a new function to be generated when one is already present (even if it was
* generated with some different options).
*
* @private
*/
const kFuncCacheMask = kExtractAll | kDeltaMode | kTestOnly | kTestAccess;
/**
* Maximum number of functions that can be generated per one final schema. This
* is basically a last flag shifted one bit left. For example if the last bit is
* 0x8 the total number of functions generated per schema to cover all possible
* combinations would be 16 (indexes 0...15).
*
* @private
*/
const kFuncCacheCount = kFuncCacheMask + 1;
// Dummy frozen objects.
const NoObject = freeze({});
const NoArray = freeze([]);
/**
* Unsafe properties are properties that collide with `Object.prototype`. These
* are always checked by using hasOwnProperty() even if the field can't contain
* `undefined` value.
*
* `UnsafeProperties` is array, not object!
*
* @private
*/
const UnsafeProperties = Object.getOwnPropertyNames(Object.prototype);
/**
* Mapping of JS types into a character that describes the type. This mapping
* is used by `SchemaCompiler` to reduce the length of variable names and to map
* distinct JS types to different variable names in case of the same property
* name. This is good for JS engines as each variable will always contain values
* of specific types and the engine will never deoptimize the function in case
* of type misprediction.
*
* @private
*/
const TypeToChar = freeze({
any : "x",
array : "a",
bool : "b",
function: "f",
number : "n",
object : "o",
string : "s"
});
const TypeToJSTypeOf = freeze({
array : "object",
bool : "boolean",
function: "function",
int : "number",
number : "number",
object : "object",
string : "string"
});
const TypeToErrorCode = freeze({
any : "ExpectedAny",
array : "ExpectedArray",
bool : "ExpectedBoolean",
number : "ExpectedNumber",
object : "ExpectedObject",
string : "ExpectedString"
});
const NumberInfo = Object.freeze({
number : { integer: 0, min: null , max: null },
numeric : { integer: 0, min: null , max: null },
float : { integer: 0, min: null , max: null },
double : { integer: 0, min: null , max: null },
latitude : { integer: 0, min: -90 , max: 90 },
longitude: { integer: 0, min: -180 , max: 180 },
int : { integer: 1, min: null , max: null },
uint : { integer: 1, min: 0 , max: null },
int8 : { integer: 1, min: kInt8Min , max: kInt8Max },
uint8 : { integer: 1, min: kUInt8Min , max: kUInt8Max },
int16 : { integer: 1, min: kInt16Min , max: kInt16Max },
uint16 : { integer: 1, min: kUInt16Min , max: kUInt16Max },
short : { integer: 1, min: kInt16Min , max: kInt16Max },
ushort : { integer: 1, min: kUInt16Min , max: kUInt16Max },
int24 : { integer: 1, min: kInt24Min , max: kInt24Max },
uint24 : { integer: 1, min: kUInt24Min , max: kUInt24Max },
int32 : { integer: 1, min: kInt32Min , max: kInt32Max },
uint32 : { integer: 1, min: kUInt32Min , max: kUInt32Max },
int53 : { integer: 1, min: kInt53Min , max: kInt53Max },
uint53 : { integer: 1, min: 0 , max: kInt53Max }
});
const CSSColorNames = freeze({
aliceblue : "#f0f8ff", antiquewhite : "#faebd7",
aqua : "#00ffff", aquamarine : "#7fffd4",
azure : "#f0ffff",
beige : "#f5f5dc", bisque : "#ffe4c4",
black : "#000000", blanchedalmond : "#ffebcd",
blue : "#0000ff", blueviolet : "#8a2be2",
brown : "#a52a2a", burlywood : "#deb887",
cadetblue : "#5f9ea0", chartreuse : "#7fff00",
chocolate : "#d2691e", coral : "#ff7f50",
cornflowerblue : "#6495ed", cornsilk : "#fff8dc",
crimson : "#dc143c", cyan : "#00ffff",
darkblue : "#00008b", darkcyan : "#008b8b",
darkgoldenrod : "#b8860b", darkgray : "#a9a9a9",
darkgreen : "#006400", darkkhaki : "#bdb76b",
darkmagenta : "#8b008b", darkolivegreen : "#556b2f",
darkorange : "#ff8c00", darkorchid : "#9932cc",
darkred : "#8b0000", darksalmon : "#e9967a",
darkseagreen : "#8fbc8f", darkslateblue : "#483d8b",
darkslategray : "#2f4f4f", darkturquoise : "#00ced1",
darkviolet : "#9400d3", deeppink : "#ff1493",
deepskyblue : "#00bfff", dimgray : "#696969",
dodgerblue : "#1e90ff",
firebrick : "#b22222", floralwhite : "#fffaf0",
forestgreen : "#228b22", fuchsia : "#ff00ff",
gainsboro : "#dcdcdc", ghostwhite : "#f8f8ff",
gold : "#ffd700", goldenrod : "#daa520",
gray : "#808080", green : "#008000",
greenyellow : "#adff2f",
honeydew : "#f0fff0", hotpink : "#ff69b4",
indianred : "#cd5c5c", indigo : "#4b0082",
ivory : "#fffff0",
khaki : "#f0e68c",
lavender : "#e6e6fa", lavenderblush : "#fff0f5",
lawngreen : "#7cfc00", lemonchiffon : "#fffacd",
lightblue : "#add8e6", lightcoral : "#f08080",
lightcyan : "#e0ffff", lightgoldenrodyellow: "#fafad2",
lightgrey : "#d3d3d3", lightgreen : "#90ee90",
lightpink : "#ffb6c1", lightsalmon : "#ffa07a",
lightseagreen : "#20b2aa", lightskyblue : "#87cefa",
lightslategray : "#778899", lightsteelblue : "#b0c4de",
lightyellow : "#ffffe0", lime : "#00ff00",
limegreen : "#32cd32", linen : "#faf0e6",
magenta : "#ff00ff", maroon : "#800000",
mediumaquamarine : "#66cdaa", mediumblue : "#0000cd",
mediumorchid : "#ba55d3", mediumpurple : "#9370d8",
mediumseagreen : "#3cb371", mediumslateblue : "#7b68ee",
mediumspringgreen : "#00fa9a", mediumturquoise : "#48d1cc",
mediumvioletred : "#c71585", midnightblue : "#191970",
mintcream : "#f5fffa", mistyrose : "#ffe4e1",
moccasin : "#ffe4b5",
navajowhite : "#ffdead", navy : "#000080",
oldlace : "#fdf5e6", olive : "#808000",
olivedrab : "#6b8e23", orange : "#ffa500",
orangered : "#ff4500", orchid : "#da70d6",
palegoldenrod : "#eee8aa", palegreen : "#98fb98",
paleturquoise : "#afeeee", palevioletred : "#d87093",
papayawhip : "#ffefd5", peachpuff : "#ffdab9",
peru : "#cd853f", pink : "#ffc0cb",
plum : "#dda0dd", powderblue : "#b0e0e6",
purple : "#800080",
red : "#ff0000", rosybrown : "#bc8f8f",
royalblue : "#4169e1",
saddlebrown : "#8b4513", salmon : "#fa8072",
sandybrown : "#f4a460", seagreen : "#2e8b57",
seashell : "#fff5ee", sienna : "#a0522d",
silver : "#c0c0c0", skyblue : "#87ceeb",
slateblue : "#6a5acd", slategray : "#708090",
snow : "#fffafa", springgreen : "#00ff7f",
steelblue : "#4682b4",
tan : "#d2b48c", teal : "#008080",
thistle : "#d8bfd8", tomato : "#ff6347",
turquoise : "#40e0d0",
violet : "#ee82ee",
wheat : "#f5deb3", white : "#ffffff",
whitesmoke : "#f5f5f5",
yellow : "#ffff00", yellowgreen : "#9acd32"
});
// ============================================================================
// [xschema.error]
// ============================================================================
/**
* Error thrown if xschema has been misused.
*
* @param {string} message Error message.
*
* @alias xschema.RuntimeError
*/
class RuntimeError extends Error {
constructor(message) {
super(message);
this.name = "RuntimeError";
this.message = message;
}
}
xschema.RuntimeError = RuntimeError;
function throwRuntimeError(msg, params) {
const ex = new RuntimeError(msg);
if (params != null && typeof params === "object") {
for (var k in params)
ex[k] = params[k];
}
throw ex;
}
/**
* Error thrown on validation failure. The `SchemaError` constructor
* always accepts array of errors, where each element is an object (descriptor)
* containing the following properties:
*
* - "code": String - Code of the error (not a message).
* - "path": String - Path to the error (dot is used to separate nested fields).
*
* The error descriptor can also contain an optional properties that are specific
* to the type and rule used, for example `InvalidDate` will contain the requested
* date format, etc...
*
* @param {object[]} errors Array of error descriptor.
*
* @alias xschema.SchemaError
*/
class SchemaError extends Error {
constructor(errors) {
super("Invalid data");
this.name = "SchemaError";
this.message = "Invalid data";
this.errors = errors;
}
}
xschema.SchemaError = SchemaError;
function throwSchemaError(errors) {
throw new SchemaError(errors);
}
// ============================================================================
// [xschema.misc]
// ============================================================================
/**
* Miscellaneous utility functions.
*
* Many of the functions included in this namespace are used by xschema itself.
* They were made public to simplify testing and to allow users to use some of
* these functions without needing to create xschema schemas.
*
* @namespace
* @alias xschema.misc
*/
const xschema$misc = xschema.misc = {};
/**
* Returns an extended type of the variable `x`.
*
* Extended type makes a distinction between null, object, and array types. For
* example `typeOf([]) === "array"` and `typeOf(null) === "null"`.
*
* @param {*} x Variable to examine.
* @return {string} Extended type of the variable `x`.
*
* @alias xschema.misc.typeOf
*/
function misc$typeOf(x) {
const type = typeof x;
if (type !== "object")
return x === null ? "null" : type;
if (isArray(x))
return "array";
switch (toString.call(x)) {
case "[object Map]" : return "map";
case "[object Set]" : return "set";
case "[object RegExp]" : return "regexp";
case "[object WeakMap]": return "weakmap";
case "[object WeakSet]": return "weakset";
default: return "object";
}
}
xschema$misc.typeOf = misc$typeOf;
/**
* Checks if the string `s` is a valid JS variable name:
*
* - `s` is not an empty string.
* - `s` starts with ASCII letter [A-Za-z], underscore [_] or a dollar sign [$].
* - `s` may contain ASCII numeric characters, but cannot start with them.
*
* Please note that EcmaScript allows to use any unicode alphanumeric and
* ideographic characters to be used in a variable name, but this function
* doesn't allow these, only ASCII characters are considered. It basically
* follows the same convention as C/C++, with dollar sign [$] included.
*
* @param {string} s Input string to check.
* @return {boolean}
*
* @alias xschema.misc.isVariableName
*/
function misc$isVariableName(s) {
if (!s) return false;
var c;
return !reInvalidIdentifier.test(s) && ((c = s.charCodeAt(0)) < 48 || c >= 58);
}
xschema$misc.isVariableName = misc$isVariableName;
/**
* Checks if the string `s` is a xschema's directive name (i.e. it starts with "$").
*
* @param {string} s Input string to check.
* @return {boolean}
*
* @alias xschema.misc.isDirectiveName
*/
function misc$isDirectiveName(s) {
return s.charCodeAt(0) === 36;
}
xschema$misc.isDirectiveName = misc$isDirectiveName;
/**
* Escapes a string `s` so it can be used in a regular expression for exact
* matching. For example a string "[]" would be escaped to "\\[\\]".
*
* @param {string} s Input string to escape.
* @return {string} Escaped string.
*
* @alias xschema.misc.escapeRegExp
*/
function misc$escapeRegExp(s) {
return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
xschema$misc.escapeRegExp = misc$escapeRegExp;
/**
* Converts a string `s` which contains an escaped field name (xschema specific)
* into a real field name that can be used in JS to access an object's property.
*
* @param {string} s Input string.
* @return {string} Unescaped string.
*
* @alias xschema.misc.unescapeFieldName
*/
function misc$unescapeFieldName(s) {
return s.replace(reUnescapeFieldName, "$1");
}
xschema$misc.unescapeFieldName = misc$unescapeFieldName;
/**
* Converts a string into camelCase.
*
* This version of `toCamelCase()` preserves words that start with an uppercased
* character, so for example "CamelCased" string will be properly converted to
* "camelCased".
*
* Examples:
*
* ```
* toCamelCase("ThisIsString") -> "thisIsString"
* toCamelCase("this-is-string") -> "thisIsString"
* toCamelCase("THIS_IS_STRING") -> "thisIsString"
* toCamelCase("this-isString") -> "thisIsString"
* toCamelCase("THIS_IsSTRING") -> "thisIsString"
* ```
*
* @param {string} s Input string.
* @return {string} CamelCased string.
*
* @function
* @alias xschema.misc.toCamelCase
*/
const misc$toCamelCase = (function() {
const re1 = /[A-Z]+/g;
const fn1 = function(m) { return m[0] + m.substr(1).toLowerCase(); };
const re2 = /[_-][A-Za-z]/g;
const fn2 = function(m) { return m.substr(1).toUpperCase(); };
function misc$toCamelCase(s) {
s = s.replace(re1, fn1);
s = s.replace(re2, fn2);
return s.charAt(0).toLowerCase() + s.substr(1);
}
return misc$toCamelCase;
})();
xschema$misc.toCamelCase = misc$toCamelCase;
/**
* Replaces the content of the given string `s` starting at `from` and ending
* at `to` by `content`.
*
* @param {string} s Input string.
* @param {number} from Replace from here.
* @param {number} to Replace until here.
* @param {string} content Replacement string.
* @return {string} New string having the input portion replaced by `content`.
*
* @alias xschema.misc.stringSplice
*/
function misc$stringSplice(s, from, to, content) {
return s.substr(0, from) + (content ? content : "") + s.substr(to);
}
xschema$misc.stringSplice = misc$stringSplice;
/**
* Checks if the input object or array is empty (doesn't have members).
*
* @param {array|object} x Input object or array.
* @return {boolean} True if the input is empty
*
* @alias xschema.misc.isEmpty
*/
function misc$isEmpty(x) {
if (isArray(x))
return x.length === 0;
for (var k in x)
return false;
return true;
}
xschema$misc.isEmpty = misc$isEmpty;
/**
* Checks if the given array `arr` is value-only - it can only contain values
* like boolean, number, string, null, or undefined (can't contain objects).
*
* @param {array} arr Array to check.
* @return {boolean} True if the given array contains only values.
*
* @alias xschema.misc.isValueOnlyArray
*/
function misc$isValueOnlyArray(arr) {
for (var i = 0, len = arr.length; i < len; i++) {
const value = arr[i];
if (value !== null && typeof value === "object")
return false;
}
return true;
}
xschema$misc.isValueOnlyArray = misc$isValueOnlyArray;
/**
* Trims all strings in the given array `arr` and returns it.
*
* @param {string[]} arr Array of strings.
* @return {string[]} Returns the given `arr`.
*
* @alias xschema.misc.trimStringArray
*/
function trimStringArray(arr) {
for (var i = 0, len = arr.length; i < len; i++)
arr[i] = String(arr[i]).trim();
return arr;
}
// Convert an array to a set (i.e. object having array values as key/true pairs).
function arrayToSet(arr) {
const obj = {};
for (var i = 0, len = arr.length; i < len; i++)
obj[arr[i]] = true;
return obj;
}
xschema$misc.arrayToSet = arrayToSet;
// Convert an object into a set (i.e. return an array containing all object keys).
function setToArray(set) {
return Object.keys(set);
}
xschema$misc.setToArray = setToArray;
// Merge a set `a` with another set or array `b`.
function mergeSets(a, b) {
if (b != null) {
if (isArray(b)) {
const srcArr = b;
for (var i = 0, len = srcArr.length; i < len; i++)
a[srcArr[i]] = true;
}
else {
Object.assign(a, b);
}
}
return a;
}
xschema$misc.mergeSets = mergeSets;
// Join all keys in a set `set` separated by `sep`. The functionality is similar
// to `Array.join()`, however, it's designed to join an object keys.
function joinSet(set, sep) {
var s = "";
// Compatible with `Array.prototype.join()`.
if (sep == null)
sep = ",";
for (var k in set) {
if (s) s += sep;
s += k;
}
return s;
}
xschema$misc.joinSet = joinSet;
function freezeOrEmpty(x) {
if (x === null || typeof x !== "object")
throwTypeError(`Argument 'x' must be object or array, not '${misc$typeOf(x)}'`);
return misc$isEmpty(x) ? (isArray(x) ? NoArray : NoObject) : freeze(x);
}
/**
* Compares `a` and `b` for deep equality.
*
* @param {*} a Any variable.
* @param {*} b Any variable.
* @return {boolean} True if `a` and `b` are equal.
*
* @alias xschema.misc.equals
*/
function misc$equals(a, b) {
return (a === b) ? true : misc$_equals(a, b, []);
}
xschema$misc.equals = misc$equals;
function misc$_equals(a, b, buffer) {
const aType = typeof a;
const bType = typeof b;
// NaN !== NaN.
if (aType === "number" && bType === "number")
return true;
// Anything else than object should be caught by `a === b`.
if (a === null || aType !== "object" || b === null || bType !== "object")
return false;
const aIsArray = isArray(a);
const bIsArray = isArray(b);
var aValue;
var bValue;
var i, k;
if (aIsArray & bIsArray) {
const aLen = a.length;
const bLen = b.length;
if (aLen !== bLen)
return false;
// Detect cyclic references.
for (i = 0; i < buffer.length; i += 2)
if (buffer[i] === a || buffer[i + 1] === b)
throwRuntimeError(`Detected cyclic reference`);
buffer.push(a, b);
for (var i = 0; i < aLen; i++) {
aValue = a[i];
bValue = b[i];
if (aValue === bValue)
continue;
if (!misc$_equals(aValue, bValue, buffer))
return false;
}
buffer.length -= 2;
return true;
}
else if (aIsArray | bIsArray) {
return false;
}
else {
// Detect cyclic references.
for (i = 0; i < buffer.length; i += 2) {
if (buffer[i] === a || buffer[i + 1] === b)
throwRuntimeError(`Detected cyclic reference`);
}
buffer.push(a, b);
for (k in a) {
if (!hasOwn.call(a, k))
continue;
if (!hasOwn.call(b, k))
return false;
}
for (k in b) {
if (!hasOwn.call(b, k))
continue;
if (!hasOwn.call(a, k))
return false;
aValue = a[k];
bValue = b[k];
if (aValue === bValue)
continue;
if (!misc$_equals(aValue, bValue, buffer))
return false;
}
buffer.length -= 2;
return true;
}
}
/**
* Returns a weak clone of `x`.
*
* Weak clone clones only `x`, but keeps all nested members weak referenced.
*
* @param {*} x Anything to clone.
*
* @alias xschema.misc.cloneWeak
*/
function misc$cloneWeak(x) {
if (!x || typeof x !== "object")
return x;