-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinyveil.js
1490 lines (1320 loc) · 49.4 KB
/
tinyveil.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
const TINYVEIL_CUSTOM_TYPES_CHECKS = {
"hexcolorcode": function (colorcode) {
if (typeof colorcode !== 'string') {
return false;
}
var reg = /^#([0-9a-f]{3}){1,2}$/i;
return reg.test(colorcode);
}
};
function AssertInstOf(target, ...src) {
for (let i = 0; i < src.length; i++) {
if (!(src[i] instanceof target)) {
panic("invalid parameter ", i, ": we got ", ((src[i] && src[i].constructor && src[i].constructor.name) ? src[i].constructor.name : src[i]), " but expected ", target);
}
}
}
/**
*
* @param {...number} n
*/
function AssertPositiveOrZero(...n) {
for (let i = 0; i < n.length; i++) {
AssertTypeOf('number', n[i]);
if (n[i] < 0) {
panic("invalid parameter " + i + " of value " + n[i] + " which is not positive or zero");
}
}
}
function AssertNullOrInstOf(target, ...src) {
for (let i = 0; i < src.length; i++) {
if (src[i] !== null && !(src[i] instanceof target)) {
panic("invalid parameter " + i + ": " + JSON.stringify(src[i]));
}
}
}
function AssertComplexInstOf(conditions, ...src) {
AssertInstOf(Array, conditions);
for (let i = 0; i < conditions.length; i++) {
for (let j = 0; j < src.length; j++) {
AssertInstOfOR(src[j], ...conditions[i].OR);
}
}
}
function AssertStringStartsWith(prefix, ...strs) {
for (let i = 0; i < strs.length; i++) {
if (!strs[i].startsWith(prefix)) {
panic("invalid parameter " + i + ": " + strs[i]);
}
}
}
function AssertStringStartsWithOr(str, ...prefixes) {
AssertTypeOf('string', str);
for (let i = 0; i < prefixes.length; i++) {
if (str.startsWith(prefixes[i])) {
return;
}
}
panic("invalid parameter not starting with either " + prefixes.join(" or ") + ": " + str);
}
function AssertTypeOf(t, ...src) {
let customtype = null;
if (typeof t === 'string' && TINYVEIL_CUSTOM_TYPES_CHECKS[t] !== undefined) {
if (typeof TINYVEIL_CUSTOM_TYPES_CHECKS[t] !== 'function') {
panic("tinyveil internal inconsistency error");
}
customtype = TINYVEIL_CUSTOM_TYPES_CHECKS[t];
}
for (let i = 0; i < src.length; i++) {
if (customtype !== null) {
if (!customtype(src[i])) {
panic("invalid parameter " + i + ", expected " + t + " and got: " + typeof src[i] + " " + src[i]);
}
} else if (t === null) {
if (src[i] !== null) {
panic("invalid parameter " + i + ", expected " + t + " and got: " + typeof src[i] + " " + src[i]);
}
} else if (t === undefined) {
if (src[i] !== undefined) {
panic("invalid parameter " + i + ": " + typeof src[i] + " " + src[i]);
}
} else if (src[i] === null || src[i] === undefined || typeof src[i] !== t) { // typeof null is "object" and typeof undefined is "undefined"
panic("invalid parameter " + i + ", expected " + t + " and got: " + typeof src[i] + " " + src[i]);
} else if (t === 'number' && isNaN(src[i])) {
panic("invalid parameter " + i + ", expected " + t + " and got: " + typeof src[i] + " " + src[i]);
}
}
}
function AssertNullOrTypeOf(t, ...src) {
let customtype = null;
if (typeof t === 'string' && TINYVEIL_CUSTOM_TYPES_CHECKS[t] !== undefined) {
if (typeof TINYVEIL_CUSTOM_TYPES_CHECKS[t] !== 'function') {
panic("tinyveil internal inconsistency error");
}
customtype = TINYVEIL_CUSTOM_TYPES_CHECKS[t];
}
for (let i = 0; i < src.length; i++) {
if (src[i] !== null) {
if (customtype !== null) {
if (!customtype(src[i])) {
panic("invalid parameter " + i + " and got: " + typeof src[i] + " " + src[i]);
}
} else if (t === undefined) {
if (src[i] !== undefined) {
panic("invalid parameter " + i + " and got: " + typeof src[i] + " " + src[i]);
}
} else if (typeof src[i] !== t) {
panic("invalid parameter " + i + " and got: " + typeof src[i] + " " + src[i]);
} else if (t === 'number' && isNaN(src[i])) {
panic("invalid parameter " + i + " and got: " + typeof src[i] + " " + src[i]);
}
}
}
}
function AssertEnum(src, possibleValues) {
AssertInstOf(Array, possibleValues);
if (!possibleValues.includes(src)) {
panic("invalid parameter", src, "which is not enum", possibleValues);
}
}
/**
* AssertOneOrTheOtherString throws an error if more than one string is not empty
* @param {...string} n
*/
function AssertOneOrTheOtherString(...n) {
let one = false
for (let i = 0; i < n.length; i++) {
AssertTypeOf('string', n[i]);
if (n[i].length > 0) {
if (one) {
panic("invalid parameters: only one non empty string supported");
}
one = true
}
}
}
function AssertTypeOfOR(src, ...t) {
for (let i = 0; i < t.length; i++) {
if (typeof t[i] === 'string' && TINYVEIL_CUSTOM_TYPES_CHECKS[t[i]] !== undefined) {
if (typeof TINYVEIL_CUSTOM_TYPES_CHECKS[t[i]] !== 'function') {
panic("tinyveil internal inconsistency error");
}
if (TINYVEIL_CUSTOM_TYPES_CHECKS[t[i]](src)) {
return;
}
} else if (t[i] === null) {
if (src === null) {
return;
}
} else if (t[i] === undefined) {
if (src === undefined) {
return;
}
} else if (typeof src === t[i] && (t[i] !== 'number' || !isNaN(src))) {
return;
}
}
panic("invalid parameter " + typeof src);
}
function AssertInstOfOR(src, ...t) {
for (let i = 0; i < t.length; i++) {
if (t[i] === null) {
if (src === null) {
return;
}
} else if (t[i] === undefined) {
if (src === undefined) {
return;
}
} else if (src instanceof t[i]) {
return;
}
}
panic("invalid parameter " + typeof src);
}
function AssertNotEqual(src, target) {
if (src === target) {
panic("invalid parameter");
}
}
function AssertEqual(src, ...targets) {
for (let i = 0; i < targets.length; i++) {
if (src !== targets[i]) {
panic(`invalid parameter at index ${i}: expected ${src} but got ${targets[i]}`);
}
}
}
function AssertArray(src) {
if (!Array.isArray(src)) {
panic("invalid parameter, expected an array, got: " + src);
}
}
function AssertArrayOfInstances(src, ...t) {
AssertArray(src);
MAIN:
for (let i = 0; i < src.length; i++) {
for (let j = 0; j < t.length; j++) {
if (src[i] instanceof t[j]) {
continue MAIN;
}
}
panic(`invalid parameter at index ${i}, expected one of ${t}, got ${src[i]}`)
}
}
function AssertArrayOfType(src, t) {
AssertArray(src);
let customtype = null;
if (typeof t === 'string' && TINYVEIL_CUSTOM_TYPES_CHECKS[t] !== undefined) {
if (typeof TINYVEIL_CUSTOM_TYPES_CHECKS[t] !== 'function') {
panic("tinyveil internal inconsistency error");
}
customtype = TINYVEIL_CUSTOM_TYPES_CHECKS[t];
}
for (let i = 0; i < src.length; i++) {
if (t === null) {
if (src[i] !== null) {
panic(`invalid parameter at index ${i}, expected a ${t}, but got`, src[i]);
}
} else if (t === undefined) {
if (src[i] !== undefined) {
panic(`invalid parameter at index ${i}, expected a ${t}, but got`, src[i]);
}
} else if (customtype !== null) {
if (!customtype(src[i])) {
panic(`invalid parameter at index ${i}, expected a ${t}, but got`, src[i]);
}
} else if (typeof src[i] !== t) {
panic(`invalid parameter at index ${i}, expected a ${t}, but got`, src[i], "which is a", typeof src[i]);
} else if (t === 'number' && isNaN(src[i])) {
panic(`invalid parameter at index ${i}, expected a ${t}, but got`, src[i]);
}
}
}
/**
* Function to check Object against a type schema with the possibility to reference schemas as the type of one or more fields.
*
* @param {Object<string, any>} obj
* @param {Object<string, any>} schema
* @param {Object<string, Object<string, any>>|undefined} referencedSchemas
*/
function AssertObjectSchema(obj, schema, referencedSchemas) {
let resp = CheckObjectAgainstSchema(obj, schema, referencedSchemas);
if (!resp.success) {
panic("object does not respect schema: " + resp.message);
}
}
/**
*
* @param {any} v
* @return {Boolean}
*/
function IsNumber(v) {
return typeof v === 'number' && !isNaN(v);
}
/**
* Function to check Object against a type schema with the possibility to reference schemas as the type of one or more fields.
*
* TODO: refactor
* @template {{success: boolean, message: string}} resp
* @param {Object<string, any>} obj
* @param {Object<string, any>} schema
* @param {Object<string, Object<string, any>>|undefined} referencedSchemas
* @return {resp}
*/
function CheckObjectAgainstSchema(obj, schema, referencedSchemas) {
AssertTypeOf("object", schema);
AssertTypeOfOR(referencedSchemas, "object", "undefined");
if (typeof obj !== 'object' || obj === null || obj === undefined) {
return { success: false, message: stringLog("Invalid object to check:", obj) };
}
// hack to handle root map type
if (schema.type !== undefined && schema.keytype !== undefined && schema.valuetype !== undefined) {
obj = { ____: obj };
schema = { ____: schema };
}
// Iterate over each property in the schema
for (let key in schema) {
// the key may be modified below in this iteration if it begins with .
let requiredType;
// for `map` type only
let keytype = null;
let valuetype = null;
if (schema[key].type) {
requiredType = schema[key].type;
if (requiredType === 'map') {
if (typeof schema[key].keytype !== 'string') {
panic("When using type `map` we also need a string keytype field, for example 'number' or 'string'");
}
if (schema[key].valuetype === undefined) {
panic("When using type `map` we also need a valuetype occupying the role of the classic type field");
}
keytype = schema[key].keytype;
valuetype = schema[key].valuetype;
}
} else {
requiredType = schema[key];
}
// If the Object doesn't have this property, check if it's optional
if (!obj.hasOwnProperty(key) || obj[key] === undefined || obj[key] === null) {
if (schema[key].optional) {
continue; // If it's optional, skip the rest of the loop for this property
} else if (key.charAt(0) === ".") {
key = removeFirstCharacter(key);
if (obj[key] === undefined) {
return { success: false, message: stringLog(`Missing property: ${key} in object`, obj, `having to satisfy schema`, schema) };
}
} else {
return { success: false, message: stringLog(`Missing property: ${key} in object`, obj, `having to satisfy schema`, schema) };
}
}
// If the required type is a reference a schema, substitute it
if (typeof requiredType === 'string' && requiredType.charAt(0) === "$") {
requiredType = referencedSchemas[requiredType];
if (requiredType === undefined || typeof requiredType !== 'object') {
panic("could not find the schema " + requiredType + " referenced in root schema defintion"); // better to panic early for this error than returning false
}
}
let typeAndInstanceOfCheck = function (target, reqT) {
if (typeof reqT === 'string' && reqT.charAt(0) === "#") {
reqT = referencedSchemas[reqT];
if (reqT === undefined) {
panic("could not find the class " + reqT + " referenced in root schema defintion"); // better to panic early for this error than returning false
}
if (target instanceof reqT) {
return { success: true };
}
} else if (typeof reqT === 'string' && reqT.startsWith('enum(')) {
let possibleValues = reqT.substring('enum('.length, reqT.length - 1).split(',').map(x => x.trim());
for (let i = 0; i < possibleValues.length; i++) {
if (typeAndInstanceOfCheck(target, possibleValues[i])) {
return { success: true };
}
}
} else if (isQuoted(reqT)) { // in an enum with a limited number of allowed predefined strings
if (typeof target === 'string' && target === reqT.slice(1, reqT.length - 1)) {
return { success: true }
}
} else if (typeof target === reqT && (reqT !== 'number' || !isNaN(target))) {
return { success: true };
}
return { success: false, message: stringLog(`Incorrect type for property: ${key}. Got ${stringLog(target)}, but expected ${stringLog(reqT)}`) };
};
// If the required type is an object, recurse into it
if (typeof requiredType === "object" && !Array.isArray(requiredType)) {
// If the corresponding Object property is not an object, return false
if (typeof obj[key] !== "object" || Array.isArray(obj[key])) {
return { success: false, message: stringLog(`Expected object for property: ${key}`) };
}
// Recurse into the object
let resp = CheckObjectAgainstSchema(obj[key], requiredType, referencedSchemas);
if (!resp.success) {
return resp;
}
} else if (requiredType === "map") {
// If the corresponding Object property is not an object, return false
if (typeof obj[key] !== "object" || Array.isArray(obj[key])) {
return { success: false, message: stringLog(`Expected object(map) for property: ${key}`) };
}
for (let [k, v] of Object.entries(obj[key])) {
// in the case of maps, in javascript an object's keys are always strings even when the object values are set with number keys, they are converted.
switch (keytype) {
default:
panic(`We do not support keys of type ${keytype} in a map type`);
case "number":
let tmp = parseFloat(k);
if (isNaN(tmp) || typeof tmp !== 'number') {
return { success: false, message: stringLog("We got an invalid map key", k, "which should be a string parsable as a number") };
}
break;
case "boolean":
if (!["true", "false"].includes(k.toLowerCase())) {
return { success: false, message: stringLog("We got an invalid map key", k, "which should be a string parsable as a boolean true or false") };
}
break;
case "string":
if (typeof k !== 'string') {
return { success: false, message: stringLog("We got an invalid map key", k, "which should be a string") };
}
break;
}
switch (true) {
default:
let checkresp = typeAndInstanceOfCheck(v, valuetype);
if (!checkresp.success) {
return { success: false, message: stringLog(`We got an invalid value in map: ${checkresp.message}`) };
}
break;
case typeof valuetype === "object": // object or array
// Recurse into the value
let resp = CheckObjectAgainstSchema(v, valuetype, referencedSchemas);
if (!resp.success) {
return { success: false, message: stringLog(`We got an invalid value in map: ${resp.message}`) };
}
break;
}
}
} else if (Array.isArray(requiredType)) {
// If requiredType is an array, check if the object value is an array of the correct type
if (!Array.isArray(obj[key])) {
return { success: false, message: stringLog(`Expected array for property: ${key}`) };
} else {
if (typeof requiredType[0] === 'string' && requiredType[0].charAt(0) === "$") {
requiredType[0] = referencedSchemas[requiredType[0]];
if (requiredType[0] === undefined || typeof requiredType[0] !== 'object') {
panic("could not find the schema " + requiredType[0] + " referenced in root schema defintion"); // better to panic early for this error than returning false
}
}
// Check each item in the array
for (let item of obj[key]) {
if (typeof requiredType[0] === 'object') {
// Recurse into the array item and expected item type
let resp = CheckObjectAgainstSchema(item, requiredType[0], referencedSchemas);
if (!resp.success) {
return resp;
}
} else {
// If the types don't match, return false
let checkresp = typeAndInstanceOfCheck(item, requiredType[0]);
if (!checkresp.success) {
return checkresp;
}
}
}
}
} else {
// If the types don't match, return false
let checkresp = typeAndInstanceOfCheck(obj[key], requiredType);
if (!checkresp.success) {
return checkresp;
}
}
}
// If we made it through all properties without returning false, the Object matches the schema
return { success: true };
}
class HTMLElementType {
#NATIVE_SCHEMAS = {
"#HTMLElement": HTMLElement, // the # identifies an instance of a class
"$HTML_ELEMENT": { // the $ identifies a schema that can be referenced in validation schemas
"tagName": "string",
"attributes": {
"id": "string",
"class": "string"
},
"children": {
"type": ["$HTML_ELEMENT"],
"optional": true,
}
},
}
/**
*
* @param {Object<string, any>} htmlSchema
*/
constructor(htmlSchema) {
AssertTypeOf("object", htmlSchema);
let resp = CheckObjectAgainstSchema(htmlSchema, this.#NATIVE_SCHEMAS["$HTML_ELEMENT"], this.#NATIVE_SCHEMAS);
if (!resp.success) {
panic("invalid parameter: " + resp.message);
}
this.Schema = htmlSchema;
}
/**
*
* @param {HTMLElement} node
* @return {Boolean}
*/
Check(node) {
// TODO
panic("not yet implemented");
return false;
}
/**
* @template {{innerText: string}} attr
* @param {Object<string, attr>} fromContent
* @return {HTMLElement}
*/
ToHTML(fromContent) {
AssertTypeOf("object", fromContent);
var htmlnode = this.#_tohtml(this.Schema);
for (const [query, attrs] of Object.entries(fromContent)) {
if (typeof attrs.innerText === 'string') {
htmlnode.querySelector(query).innerText = attrs.innerText;
}
}
return htmlnode;
}
#_tohtml(schema) {
AssertTypeOf("object", schema);
// Create a new element based on the tagName
let newElement = document.createElement(schema.tagName);
// Set the element's id and class if they're present in the schema
if (schema.attributes.id) {
newElement.id = schema.attributes.id;
}
if (schema.attributes.class) {
newElement.className = schema.attributes.class;
}
// Recurse into children, if any
if (Array.isArray(schema.children)) {
for (let i = 0; i < schema.children.length; i++) {
if (schema.children[i] !== null) {
let childElement = this.#_tohtml(schema.children[i]);
newElement.appendChild(childElement);
}
}
}
return newElement;
}
/**
*
* @param {string} htmlString
* @return {HTMLElementType}
*/
static FromString(htmlString) {
AssertTypeOf('string', htmlString);
return HTMLElementType.FromNode(CreateElementFromHTML(htmlString));
}
/**
*
* @param {HTMLElement} element
* @return {HTMLElementType}
*/
static FromNode(element) {
AssertInstOf(HTMLElement, element);
let queue = [{ element: element, parentJson: null }];
let rootJson;
while (queue.length > 0) {
let current = queue.shift();
let currentElement = current.element;
let parentJson = current.parentJson;
// Initialize the JSON object for this element.
let json = {
tagName: currentElement.tagName.toLowerCase(),
attributes: {
id: currentElement.id ? currentElement.id : "",
class: currentElement.className ? currentElement.className : ""
},
children: []
};
if (parentJson !== null) {
parentJson.children.push(json);
} else {
rootJson = json;
}
// Loop through all children of the current element
for (let i = 0; i < currentElement.children.length; i++) {
let childElement = currentElement.children[i];
if (childElement instanceof HTMLElement) {
queue.push({ element: childElement, parentJson: json });
}
}
}
return new HTMLElementType(rootJson);
}
}
// TODO: set an optional timeout waiting for backend response and enhance idempotency hash usage
class WebsocketAPI {
/**
*
* @param {string} url
*/
constructor(url) {
AssertTypeOf('string', url);
this.socket = null;
/**
* @template {{routename:string, message:Object, cb:function}} request
* @type {Array<request>}
*/
this.requestbuffer = [];
/**
* @template {{routename:string, message:Object, cb:function}} request
* @type {Object<number, request>} Keys are request IDs
*/
this.requestCallbacks = {};
this.routes = {};
this.references = {};
this.requestidincrement = 0;
this.address = url;
this.opened = false;
this.restarting = false;
this.retryDelay = 5000;
this.retryBackoffFactor = 2;
this.retryMaxDelay = 60000;
this.retryCount = 0;
this.sessionID = null;
this.#start();
}
#start() {
if (this.opened || this.restarting) {
return;
}
this.restarting = true;
let that = this;
if (this.retryCount > 0) {
this.retryDelay *= this.retryBackoffFactor;
if (this.retryDelay > this.retryMaxDelay) {
this.retryDelay = this.retryMaxDelay;
}
}
this.retryCount++;
try {
this.socket = new WebSocket(this.address);
} catch (e) {
that.restarting = false;
console.log("We could not establish websocket to backend:", e);
that.#close();
return;
}
this.socket.addEventListener('open', (event) => {
that.opened = true;
that.restarting = false;
that.retryDelay = 5000;
for (let request = that.requestbuffer.pop(); request !== undefined; request = that.requestbuffer.pop()) {
if (!that.Send(request.routename, request.message, request.cb)) {
return;
}
}
console.log("server connection established successfully");
});
this.socket.addEventListener('message', (event) => {
that.#onmessage(event);
});
this.socket.addEventListener('error', (event) => {
if (that.opened || that.restarting) {
that.restarting = false;
console.log("server connection error:", event);
that.#close();
}
});
this.socket.addEventListener('close', (event) => {
if (that.opened || that.restarting) {
that.restarting = false;
console.log("server connection closed:", event);
that.#close();
}
});
}
#close() {
if (this.opened) {
this.opened = false;
this.socket.close();
this.socket = null;
for (const [_, definition] of Object.entries(this.requestCallbacks)) {
definition.cb(new Err("lostConnection", "we lost connection with the server"), null);
}
this.requestCallbacks = {};
}
let delay = (this.retryDelay / 10) * 7 + Math.random() * (this.retryDelay / 10) * 3;
console.log(`trying reconnection in ${(delay / 1000).toFixed(2)} seconds..`);
setTimeout(() => { this.#start(); }, delay);
}
#onmessage(event) {
let resp;
try {
resp = JSON.parse(event.data);
} catch (e) {
console.log("Could not JSON parse payload:", e, event);
return;
}
if (resp.order === undefined || typeof resp.order !== 'number') {
console.log("Received payload from the backend without a requestid:", resp);
return;
}
if ((resp.message === undefined || typeof resp.message !== 'object') && (resp.error === undefined || typeof resp.error !== 'object')) {
console.log("Received payload from the backend without an object message or error:", resp);
return;
}
if (resp.sessionid === undefined || typeof resp.sessionid !== 'string') {
console.log("Received payload from the backend without a sessionid:", resp);
return;
}
if (this.sessionID !== null && resp.sessionid !== this.sessionID) {
console.log("Received payload from the backend with an invalid sessionid different from " + this.sessionID + " :", resp);
return;
} else if (this.sessionID === null) {
this.sessionID = resp.sessionid;
}
if (this.requestCallbacks[resp.order] === undefined) {
console.log("Could not find response callback: Either Received duplicate payload from the backend with the same order number or backend inconsistency error:", resp);
return;
}
let definition = this.requestCallbacks[resp.order];
delete this.requestCallbacks[resp.order];
if (resp.error !== undefined) {
definition.cb(new Err(resp.error.code, resp.error.message), null);
return;
}
let checkresp = CheckObjectAgainstSchema(resp.message, this.routes[definition.routename].responseType, this.references);
if (!checkresp.success) {
definition.cb(new Err("invalidMessageStructure", "The response received from the backend: " + JSON.stringify(resp.message) + " does not satisfy the set response type: " + JSON.stringify(this.routes[definition.routename].responseType) + " for route " + definition.routename + " for the following reason: " + checkresp.message), null);
return false;
}
definition.cb(null, resp.message);
}
/**
*
* @param {string} name
* @param {Object} requestType
* @param {Object} responseType
* @return {WebsocketAPI}
*/
CreateRoute(name, requestType, responseType) {
AssertTypeOf('string', name);
AssertTypeOf('object', requestType, responseType);
if (this.routes[name] !== undefined) {
panic("We already registered route " + name);
}
this.routes[name] = {
"requestType": requestType,
"responseType": responseType,
};
return this;
}
/**
*
* @param {string} routename
* @param {object} message
* @param {function(Err|null, object|null):void} cb(err:Err, data:object)
* @return {Boolean}
*/
Send(routename, message, cb) {
if (this.routes[routename] === undefined) {
panic("Route " + routename + " does not exist");
}
let checkresp = CheckObjectAgainstSchema(message, this.routes[routename].requestType, this.references);
if (!checkresp.success) {
cb(new Err("invalidMessageStructure", "The provided message: " + JSON.stringify(message) + " does not satisfy the set request type: " + JSON.stringify(this.routes[routename].requestType) + " for route " + routename + " for the following reason: " + checkresp.message), null);
return false;
}
var definition = {
"routename": routename,
"message": message,
"cb": cb
};
if (!this.opened) {
this.requestbuffer.push(definition);
return false;
}
let payload = {
"routename": routename,
"order": (this.requestidincrement++),
// "idempotencyhash": CRC64(JSON.stringify({ routename: routename, message: message })),
"message": message
};
if (this.sessionID !== null) {
payload.sessionid = this.sessionID;
}
this.requestCallbacks[payload.order] = definition;
// fail fast
var str = JSON.stringify(payload);
try {
this.socket.send(str);
} catch (e) {
this.#close();
}
return true
}
/**
*
* @param {string} routename
* @param {object} message
* @return {Promise}
*/
SendPromise(routename, message) {
return new Promise(function (resolve, reject) {
this.Send(routename, message, function (err, data) {
if (err !== null) {
reject(err);
return;
}
resolve(data);
});
}.bind(this));
}
}
function CreateElementFromHTML(htmlString) {
AssertTypeOf('string', htmlString);
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
let trimwhitespaces = function (node) {
for (let i = 0; i < node.childNodes.length; i++) {
let child = node.childNodes[i];
if (child.nodeType === 3) {
child.textContent = child.textContent.trim();
} else if (child.nodeType === 1) {
trimwhitespaces(child);
}
}
};
trimwhitespaces(div);
// Change this to div.childNodes to support multiple top-level nodes.
return div.firstChild;
}
function CreateManyElementsFromHTML(htmlString) {
AssertTypeOf('string', htmlString);
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
var ret = [];
for (let i = 0; i < div.childNodes.length; i++) {
if (!(div.childNodes[i] instanceof Text)) {
ret.push(div.childNodes[i]);
}
}
return ret;
}
/**
*
* @param {HTMLElement|SVGElement} node
* @param {Object<string, string>} styleObj
* @return {HTMLElement}
*/
function SetStyle(node, styleObj) {
AssertInstOfOR(node, HTMLElement, SVGElement);
AssertObjectSchema(styleObj, { type: "map", keytype: "string", valuetype: "string" });
for (let prop in styleObj) {
if (styleObj.hasOwnProperty(prop)) {
node.style[prop] = styleObj[prop];
}
}
return node;
}
function SetMStyle(styleObj, ...nodes) {
AssertObjectSchema(styleObj, { type: "map", keytype: "string", valuetype: "string" });
AssertObjectSchema({ nodes: nodes }, { nodes: ["enum(#HTMLElement, #SVGElement)"] }, { "#HTMLElement": HTMLElement, "#SVGElement": SVGElement });
for (let prop in styleObj) {
if (styleObj.hasOwnProperty(prop)) {
for (let i = 0; i < nodes.length; i++) {
nodes[i].style[prop] = styleObj[prop];
}
}
}
}
/**
* handles prefixing the cursor type with -webkit when appropri
* @param {...HTMLElement} element
* @param {string} style
*/
function SetCursorStyle(style, ...elements) {
AssertObjectSchema({ elements: elements }, { elements: ["enum(#HTMLElement, #SVGElement)"] }, { "#HTMLElement": HTMLElement, "#SVGElement": SVGElement });
AssertTypeOf('string', style);
for (let i = 0; i < elements.length; i++) {
elements[i].style.cursor = style;
if (elements[i].style.cursor !== style) {
elements[i].style.cursor = '-webkit-' + style;
}
}
}
/**
* One final callback is great, we want to avoid callback hell consisting of many nested callbacks.
* We want readable linear and flat code. We do not want obscurity and contamination as with async/await.
* @param {function():void} code
* @param {function(Err|null, ...any):void} finalcb
*/
function ASYNC(code, finalcb) {
if (typeof code !== 'function' || typeof finalcb !== 'function') {
panic("The arguments must be functions.");
}
let generator = code();
function handleResult(result) {
if (result.done) {
if (Array.isArray(result.value)) {
return finalcb(...result.value);
}
return finalcb(result.value);
}
let value = result.value;
if (Array.isArray(value)) {
if (value.every(isPromise)) {
return Promise.all(value) // Promise.all preserves the order of the promises in the result array.
.then(function (res) {
if (res.length !== value.length) {
panic(`we received a number of responses ${res.length} which does not match the number of promises ${value.length}`);
}
for (let i = 0; i < res.length; i++) {
if (!Array.isArray(res[i])) {
panic("Promises must return an array of results to work with our choosen specification");
}
if (res[i].length === 0) {
panic("We need promises to return array with at least null or Err as the first element");
}
if (res[i][0] !== null) {
handleError(res[i][0]);
return;
}
if (res[i].length > 1) {
res[i] = res[i].slice(1);
} else {
res[i] = null;