@rootintf/protocol-2phw 0.7.5-api-0.7 → 1.0.28-api-0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,84 @@
1
1
  'use strict';
2
2
 
3
- const validate_Msg2PhW = validate10;const pattern0 = new RegExp("0\\.7", "u");function validate10(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data["2PhW"] === undefined) && (missing0 = "2PhW")){validate10.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data["2PhW"] !== undefined){let data0 = data["2PhW"];{if(typeof data0 === "string"){if(!pattern0.test(data0)){validate10.errors = [{instancePath:instancePath+"/2PhW",schemaPath:"#/properties/2PhW/pattern",keyword:"pattern",params:{pattern: "0\\.7"},message:"must match pattern \""+"0\\.7"+"\""}];return false;}}else {validate10.errors = [{instancePath:instancePath+"/2PhW",schemaPath:"#/properties/2PhW/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}}}}}else {validate10.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate10.errors = vErrors;return errors === 0;}const validate_MsgOptions = validate11;function validate11(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.options === undefined) && (missing0 = "options")){validate11.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.options !== undefined){let data0 = data.options;if(!(data0 && typeof data0 == "object" && !Array.isArray(data0))){validate11.errors = [{instancePath:instancePath+"/options",schemaPath:"#/properties/options/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}}}else {validate11.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate11.errors = vErrors;return errors === 0;}const validate_Options_delay = validate12;function validate12(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.ttl_msec_incr === undefined) && (missing0 = "ttl_msec_incr")){validate12.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.ttl_msec_incr !== undefined){let data0 = data.ttl_msec_incr;const _errs1 = errors;{if(Array.isArray(data0)){var valid1 = true;const len0 = data0.length;for(let i0=0; i0<len0; i0++){let data1 = data0[i0];const _errs3 = errors;if(!(((typeof data1 == "number") && (!(data1 % 1) && !isNaN(data1))) && (isFinite(data1)))){validate12.errors = [{instancePath:instancePath+"/ttl_msec_incr/" + i0,schemaPath:"#/properties/ttl_msec_incr/items/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}var valid1 = _errs3 === errors;if(!valid1){break;}}}else {validate12.errors = [{instancePath:instancePath+"/ttl_msec_incr",schemaPath:"#/properties/ttl_msec_incr/type",keyword:"type",params:{type: "array"},message:"must be array"}];return false;}}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data.reason !== undefined){const _errs5 = errors;if(typeof data.reason !== "string"){validate12.errors = [{instancePath:instancePath+"/reason",schemaPath:"#/properties/reason/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs5 === errors;}else {var valid0 = true;}}}}else {validate12.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate12.errors = vErrors;return errors === 0;}const validate_MsgWarp = validate13;function validate13(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.warp === undefined) && (missing0 = "warp")){validate13.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.warp !== undefined){let data0 = data.warp;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if(((data0.user === undefined) && (missing1 = "user")) || ((data0.hyperport === undefined) && (missing1 = "hyperport"))){validate13.errors = [{instancePath:instancePath+"/warp",schemaPath:"#/properties/warp/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data0.ttl_msec !== undefined){let data1 = data0.ttl_msec;const _errs3 = errors;if(!(((typeof data1 == "number") && (!(data1 % 1) && !isNaN(data1))) && (isFinite(data1)))){validate13.errors = [{instancePath:instancePath+"/warp/ttl_msec",schemaPath:"#/properties/warp/properties/ttl_msec/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}var valid1 = _errs3 === errors;}else {var valid1 = true;}if(valid1){if(data0.instantaneous !== undefined){const _errs5 = errors;if(typeof data0.instantaneous !== "boolean"){validate13.errors = [{instancePath:instancePath+"/warp/instantaneous",schemaPath:"#/properties/warp/properties/instantaneous/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];return false;}var valid1 = _errs5 === errors;}else {var valid1 = true;}}}}else {validate13.errors = [{instancePath:instancePath+"/warp",schemaPath:"#/properties/warp/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}}}}else {validate13.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate13.errors = vErrors;return errors === 0;}const validate_MsgEngage = validate14;function validate14(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.engage === undefined) && (missing0 = "engage")){validate14.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.engage !== undefined){let data0 = data.engage;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if(((data0.user === undefined) && (missing1 = "user")) || ((data0.hyperport === undefined) && (missing1 = "hyperport"))){validate14.errors = [{instancePath:instancePath+"/engage",schemaPath:"#/properties/engage/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}}else {validate14.errors = [{instancePath:instancePath+"/engage",schemaPath:"#/properties/engage/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}}}}else {validate14.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate14.errors = vErrors;return errors === 0;}
3
+ const schema_MsgWarp = validate19;function validate19(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate19.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.warp === undefined) && (missing0 = "warp")){validate19.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.warp !== undefined){let data0 = data.warp;const _errs1 = errors;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if(((((data0.id === undefined) && (missing1 = "id")) || ((data0.user === undefined) && (missing1 = "user"))) || ((data0.hyperport === undefined) && (missing1 = "hyperport"))) || ((data0.ttl_msec === undefined) && (missing1 = "ttl_msec"))){validate19.errors = [{instancePath:instancePath+"/warp",schemaPath:"#/properties/warp/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data0.id !== undefined){const _errs3 = errors;if(typeof data0.id !== "string"){validate19.errors = [{instancePath:instancePath+"/warp/id",schemaPath:"definitions_2PhW#/definitions/warp_id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid1 = _errs3 === errors;}else {var valid1 = true;}if(valid1){if(data0.ttl_msec !== undefined){let data2 = data0.ttl_msec;const _errs6 = errors;if(!(((typeof data2 == "number") && (!(data2 % 1) && !isNaN(data2))) && (isFinite(data2)))){validate19.errors = [{instancePath:instancePath+"/warp/ttl_msec",schemaPath:"#/properties/warp/properties/ttl_msec/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}var valid1 = _errs6 === errors;}else {var valid1 = true;}if(valid1){if(data0.instantaneous !== undefined){const _errs8 = errors;if(typeof data0.instantaneous !== "boolean"){validate19.errors = [{instancePath:instancePath+"/warp/instantaneous",schemaPath:"#/properties/warp/properties/instantaneous/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];return false;}var valid1 = _errs8 === errors;}else {var valid1 = true;}}}}}else {validate19.errors = [{instancePath:instancePath+"/warp",schemaPath:"#/properties/warp/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data["2PhW"] !== undefined){const _errs10 = errors;if("0.8" !== data["2PhW"]){validate19.errors = [{instancePath:instancePath+"/2PhW",schemaPath:"definitions_2PhW#/definitions/2PhW/const",keyword:"const",params:{allowedValue: "0.8"},message:"must be equal to constant"}];return false;}var valid0 = _errs10 === errors;}else {var valid0 = true;}}}}else {validate19.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate19.errors = vErrors;return errors === 0;}validate19.evaluated = {"props":{"warp":true,"2PhW":true},"dynamicProps":false,"dynamicItems":false};const schema_MsgEngage = validate20;function validate20(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate20.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.engage === undefined) && (missing0 = "engage")){validate20.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.engage !== undefined){let data0 = data.engage;const _errs1 = errors;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if(((data0.ok === undefined) && (missing1 = "ok")) || ((data0.rtt_msec === undefined) && (missing1 = "rtt_msec"))){validate20.errors = [{instancePath:instancePath+"/engage",schemaPath:"#/properties/engage/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data0.ok !== undefined){const _errs3 = errors;if(typeof data0.ok !== "boolean"){validate20.errors = [{instancePath:instancePath+"/engage/ok",schemaPath:"#/properties/engage/properties/ok/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];return false;}var valid1 = _errs3 === errors;}else {var valid1 = true;}if(valid1){if(data0.rtt_msec !== undefined){let data2 = data0.rtt_msec;const _errs5 = errors;if(!(((typeof data2 == "number") && (!(data2 % 1) && !isNaN(data2))) && (isFinite(data2)))){validate20.errors = [{instancePath:instancePath+"/engage/rtt_msec",schemaPath:"#/properties/engage/properties/rtt_msec/type",keyword:"type",params:{type: "integer"},message:"must be integer"}];return false;}var valid1 = _errs5 === errors;}else {var valid1 = true;}}}}else {validate20.errors = [{instancePath:instancePath+"/engage",schemaPath:"#/properties/engage/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data["2PhW"] !== undefined){const _errs7 = errors;if("0.8" !== data["2PhW"]){validate20.errors = [{instancePath:instancePath+"/2PhW",schemaPath:"definitions_2PhW#/definitions/2PhW/const",keyword:"const",params:{allowedValue: "0.8"},message:"must be equal to constant"}];return false;}var valid0 = _errs7 === errors;}else {var valid0 = true;}}}}else {validate20.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate20.errors = vErrors;return errors === 0;}validate20.evaluated = {"props":{"engage":true,"2PhW":true},"dynamicProps":false,"dynamicItems":false};const schema_MsgOptions = validate21;function validate21(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate21.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.options === undefined) && (missing0 = "options")){validate21.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.options !== undefined){let data0 = data.options;const _errs1 = errors;if(!(data0 && typeof data0 == "object" && !Array.isArray(data0))){validate21.errors = [{instancePath:instancePath+"/options",schemaPath:"#/properties/options/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data["2PhW"] !== undefined){const _errs3 = errors;if("0.8" !== data["2PhW"]){validate21.errors = [{instancePath:instancePath+"/2PhW",schemaPath:"definitions_2PhW#/definitions/2PhW/const",keyword:"const",params:{allowedValue: "0.8"},message:"must be equal to constant"}];return false;}var valid0 = _errs3 === errors;}else {var valid0 = true;}}}}else {validate21.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate21.errors = vErrors;return errors === 0;}validate21.evaluated = {"props":{"options":true,"2PhW":true},"dynamicProps":false,"dynamicItems":false};
4
4
 
5
5
  // console.log('OUT', __name({variableName}) );
6
6
 
7
- function l_toBigInt_(ref, obj, ignore= false) {
8
- console.assert(ref !== BigInt(0), 'no labels initialized');
9
- let bigInt = BigInt(0);
10
- for (const [k,v] of Object.entries(obj)) {
11
- if ( ( ignore || v ) && ref[k])
12
- bigInt|= BigInt( ref[k] );
13
- // console.log('0b'+ bigInt.toString(2) );
14
- }
15
- return bigInt;
7
+ //-------------------------------------------------------------------------------------------------
8
+
9
+ function l_length_(obj_labels) {
10
+ if (! obj_labels || typeof obj_labels !== 'object')
11
+ throw new Error('obj_labels must be an object');
12
+ const obj_1label = Object.values(obj_labels);
13
+ if (! obj_1label.every(v => typeof v === 'number' && Number.isFinite(v)))
14
+ throw new Error('All values must be finite numbers');
15
+
16
+ const labels = Object.values(obj_labels);
17
+ if (labels.length === 0)
18
+ return 1; // Empty object case, start at 1
19
+
20
+ const value_max = Math.max(...labels);
21
+ if (value_max <= 0) return 1
22
+
23
+ const bit_highest = Math.floor(Math.log2(value_max));
24
+ return 1 << (bit_highest + 1);
16
25
  }
17
26
 
18
- function l_LL_(obj, x) {
19
- let obj_new= {};
20
- for (var [k,v] of Object.entries(obj))
21
- obj_new[k]= v<<x;
22
- return obj_new;
27
+ function l_array_(arr_labels, start = 1) {
28
+ if (! Array.isArray(arr_labels))
29
+ throw new Error('arr_labels must be an array');
30
+ if (! Number.isSafeInteger(start) || start < 0)
31
+ throw new Error('start must be a safe, non-negative integer');
32
+
33
+ return Object.freeze(arr_labels.reduce((acc, key, index) => {
34
+ acc[key] = start << index;
35
+ return acc;
36
+ }, {}));
37
+ }
38
+
39
+ function l_concat_(obj_labels, arg) {
40
+ if (! obj_labels || typeof obj_labels !== 'object')
41
+ throw new Error('obj_labels must be an object');
42
+ const obj_1label = Object.values(obj_labels);
43
+ if (! obj_1label.every(v => typeof v === 'number' && Number.isFinite(v)))
44
+ throw new Error('All values must be finite numbers');
45
+ if (! arg || (typeof arg !== 'object' && ! Array.isArray(arg)))
46
+ throw new Error('arg must be an object or array');
47
+
48
+ if (Array.isArray(arg)) {
49
+ const len = l_length_(obj_labels);
50
+ const arr_labels_new = l_array_(arg, len);
51
+ return l_concat_(obj_labels, arr_labels_new);
52
+ }
53
+
54
+ const next_pos = l_length_(obj_labels);
55
+ const arg_entries = Object.entries(arg);
56
+ const result = Object.create(null);
57
+ Object.entries(obj_labels).forEach(([k, v]) => {
58
+ if (k !== '__proto__' && k !== 'constructor')
59
+ result[k] = v;
60
+ });
61
+
62
+ let min_arg = Infinity;
63
+ for (const [, value] of arg_entries) {
64
+ if (typeof value !== 'number' || ! Number.isFinite(value))
65
+ continue; // Skip non-numeric
66
+
67
+ if (value > 0 && value < min_arg)
68
+ min_arg = value;
69
+ }
70
+ // Shift only if min_arg is less than next_pos
71
+ const shift = min_arg === Infinity || min_arg >= next_pos
72
+ ? 0
73
+ : Math.floor(Math.log2(next_pos / min_arg));
74
+
75
+ for (const [key, value] of arg_entries) {
76
+ if (!(key in result)) {
77
+ result[key] = value === 0 ? 0 : value << shift;
78
+ }
79
+ }
80
+
81
+ return Object.freeze(result);
23
82
  }
24
83
 
25
84
  //-------------------------------------------------------------------------------------------------
@@ -32,56 +91,85 @@ function handler_default_( /* ... */ ) {
32
91
 
33
92
  //-------------------------------------------------------------------------------------------------
34
93
 
35
- class BitLogr {
36
- constructor() {
37
- this._handler_log= handler_default_;
38
- this._Bint_labels= BigInt(0);
39
- this._Bint_toggled= BigInt(0);
40
-
41
- BitLogr.prototype['log']= function (nr_logged, /* ... */ ) {
42
- // console.log('NOP')
43
- };
44
- }
94
+ function l_toBigInt_(obj_labels, obj, ignore= false) {
95
+ if (! obj_labels || typeof obj_labels !== 'object')
96
+ throw new Error('obj_labels must be an object');
97
+ if (! obj || typeof obj !== 'object')
98
+ throw new Error('obj must be an object');
45
99
 
46
- set handler(fx) {
47
- this._handler_log= fx;
48
- }
49
-
50
- get labels() { return this._Bint_labels; }
51
- set labels(obj) {
52
- this._Bint_labels= obj;
53
- this._Bint_toggled= BigInt(0);
100
+ let bigInt = BigInt(0);
101
+ for (const [k,v] of Object.entries(obj)) {
102
+ if ( ( ignore || v ) && obj_labels[k] !== undefined && typeof obj_labels[k] === 'number')
103
+ bigInt|= BigInt( obj_labels[k] );
104
+ // console.log('0b'+ bigInt.toString(2) );
54
105
  }
106
+ return bigInt;
107
+ }
55
108
 
56
- // put= function(label, abbrv) {
57
- // let name= __name(label);
58
- // _labels[name]= label[name];
59
- // console.log(_labels);
60
- // }
109
+ // console.log(l_toBigInt_({},{}))
61
110
 
62
- get toggled() { return this._Bint_toggled; }
63
- set toggled(obj) {
64
- this._Bint_toggled= l_toBigInt_(this._Bint_labels, obj);
111
+ const LOGR = (function () {
112
+ let _instance; // Private variable to hold the single instance
65
113
 
66
- if (this._Bint_toggled === BigInt(0)) {
67
- console.log('adlkjasdlfk');
68
- return;
69
- }
114
+ function _create_instance() {
115
+ // Private state (replacing constructor properties)
116
+ let _handler_log = handler_default_;
117
+ let _obj_labels = undefined;
118
+ let _Bint_toggled = BigInt(0);
70
119
 
71
- BitLogr.prototype['log']= function (nr_logged, /* ... */ ) {
72
- if ( (BigInt(nr_logged) & this._Bint_toggled) === BigInt(0))
120
+ function _log_fxn(nr_logged, argsFn /* args */) {
121
+ if ((BigInt(nr_logged) & _Bint_toggled) === BigInt(0))
73
122
  return false;
74
-
75
- var args = Array.prototype.slice.call(arguments);
76
- args.shift(); // remove first arg: nr_logged
77
- this._handler_log.apply(this, args);
78
-
123
+
124
+ const args = argsFn();
125
+ _handler_log.apply(this, args);
126
+ // _handler_log.apply(this, args);
79
127
  return true;
128
+ }
129
+
130
+ return {
131
+ set handler(fx) {
132
+ _handler_log = fx;
133
+ },
134
+ get handler() {
135
+ return _handler_log;
136
+ },
137
+
138
+ get labels() { return _obj_labels; },
139
+ set labels(obj) {
140
+ _obj_labels = obj;
141
+ _Bint_toggled = BigInt(0);
142
+ },
143
+
144
+ // put= function(label, abbrv) {
145
+ // let name= __name(label);
146
+ // _labels[name]= label[name];
147
+ // console.log(_labels);
148
+ // }
149
+
150
+ get toggled() { return _Bint_toggled; },
151
+ set toggled(obj_toggled) {
152
+ _Bint_toggled= l_toBigInt_(_obj_labels, obj_toggled);
153
+ },
154
+
155
+ log(nr_logged, argsFn) {
156
+
157
+ return _log_fxn.call(this, nr_logged, argsFn); // Pass the thunk
158
+ }
80
159
  };
81
160
  }
82
161
 
83
- // log= function (nr_logged, /* ... */ ) {}
84
- }
162
+ // Public interface
163
+ return {
164
+ get_instance() {
165
+ if (!_instance) {
166
+ _instance = _create_instance(); // Lazy initialization
167
+ }
168
+ return _instance;
169
+ }
170
+ };
171
+
172
+ })();
85
173
 
86
174
  var jsonMsg_cjs = {};
87
175
 
@@ -91,63 +179,62 @@ function requireJsonMsg_cjs () {
91
179
  if (hasRequiredJsonMsg_cjs) return jsonMsg_cjs;
92
180
  hasRequiredJsonMsg_cjs = 1;
93
181
 
94
- Object.defineProperty(jsonMsg_cjs, '__esModule', { value: true });
182
+ const schema_Msg = validate18;function validate18(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate18.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((((data.id === undefined) && (missing0 = "id")) || ((data.referer === undefined) && (missing0 = "referer"))) || ((data.dt === undefined) && (missing0 = "dt"))){validate18.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.id !== undefined){const _errs1 = errors;if(typeof data.id !== "string"){validate18.errors = [{instancePath:instancePath+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data.dt !== undefined){const _errs3 = errors;if(typeof data.dt !== "string"){validate18.errors = [{instancePath:instancePath+"/dt",schemaPath:"#/properties/dt/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs3 === errors;}else {var valid0 = true;}}}}else {validate18.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate18.errors = vErrors;return errors === 0;}validate18.evaluated = {"props":{"id":true,"dt":true},"dynamicProps":false,"dynamicItems":false};const schema_Msg_msg = validate19;function validate19(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate19.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data._msg === undefined) && (missing0 = "_msg")){validate19.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}}else {validate19.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate19.errors = vErrors;return errors === 0;}validate19.evaluated = {"dynamicProps":false,"dynamicItems":false};const schema_MsgAck_msg = validate20;function validate20(data, {instancePath="", parentData, parentDataProperty, rootData=data, dynamicAnchors={}}={}){let vErrors = null;let errors = 0;const evaluated0 = validate20.evaluated;if(evaluated0.dynamicProps){evaluated0.props = undefined;}if(evaluated0.dynamicItems){evaluated0.items = undefined;}{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.ack === undefined) && (missing0 = "ack")){validate20.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.ack !== undefined){let data0 = data.ack;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if((data0.ok === undefined) && (missing1 = "ok")){validate20.errors = [{instancePath:instancePath+"/ack",schemaPath:"#/properties/ack/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data0.ok !== undefined){if(typeof data0.ok !== "boolean"){validate20.errors = [{instancePath:instancePath+"/ack/ok",schemaPath:"#/properties/ack/properties/ok/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];return false;}}}}else {validate20.errors = [{instancePath:instancePath+"/ack",schemaPath:"#/properties/ack/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}}}}else {validate20.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate20.errors = vErrors;return errors === 0;}validate20.evaluated = {"props":{"ack":true},"dynamicProps":false,"dynamicItems":false};
95
183
 
96
- const validate_Msg = validate10;function validate10(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((((data.id === undefined) && (missing0 = "id")) || ((data.referer === undefined) && (missing0 = "referer"))) || ((data.dt === undefined) && (missing0 = "dt"))){validate10.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.id !== undefined){const _errs1 = errors;if(typeof data.id !== "string"){validate10.errors = [{instancePath:instancePath+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs1 === errors;}else {var valid0 = true;}if(valid0){if(data.referer !== undefined){let data1 = data.referer;const _errs3 = errors;{if(Array.isArray(data1)){if(data1.length > 2){validate10.errors = [{instancePath:instancePath+"/referer",schemaPath:"#/properties/referer/maxItems",keyword:"maxItems",params:{limit: 2},message:"must NOT have more than 2 items"}];return false;}else {if(data1.length < 2){validate10.errors = [{instancePath:instancePath+"/referer",schemaPath:"#/properties/referer/minItems",keyword:"minItems",params:{limit: 2},message:"must NOT have fewer than 2 items"}];return false;}else {var valid1 = true;const len0 = data1.length;for(let i0=0; i0<len0; i0++){const _errs5 = errors;if(typeof data1[i0] !== "string"){validate10.errors = [{instancePath:instancePath+"/referer/" + i0,schemaPath:"#/properties/referer/items/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid1 = _errs5 === errors;if(!valid1){break;}}}}}else {validate10.errors = [{instancePath:instancePath+"/referer",schemaPath:"#/properties/referer/type",keyword:"type",params:{type: "array"},message:"must be array"}];return false;}}var valid0 = _errs3 === errors;}else {var valid0 = true;}if(valid0){if(data.dt !== undefined){const _errs7 = errors;if(typeof data.dt !== "string"){validate10.errors = [{instancePath:instancePath+"/dt",schemaPath:"#/properties/dt/type",keyword:"type",params:{type: "string"},message:"must be string"}];return false;}var valid0 = _errs7 === errors;}else {var valid0 = true;}}}}}else {validate10.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate10.errors = vErrors;return errors === 0;}const validate_Msg_msg = validate11;function validate11(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data._msg === undefined) && (missing0 = "_msg")){validate11.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}}else {validate11.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate11.errors = vErrors;return errors === 0;}const validate_MsgAck = validate12;function validate12(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){let vErrors = null;let errors = 0;{if(data && typeof data == "object" && !Array.isArray(data)){let missing0;if((data.ack === undefined) && (missing0 = "ack")){validate12.errors = [{instancePath,schemaPath:"#/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"}];return false;}else {if(data.ack !== undefined){let data0 = data.ack;{if(data0 && typeof data0 == "object" && !Array.isArray(data0)){let missing1;if((data0.ok === undefined) && (missing1 = "ok")){validate12.errors = [{instancePath:instancePath+"/ack",schemaPath:"#/properties/ack/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"}];return false;}else {if(data0.ok !== undefined){if(typeof data0.ok !== "boolean"){validate12.errors = [{instancePath:instancePath+"/ack/ok",schemaPath:"#/properties/ack/properties/ok/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];return false;}}}}else {validate12.errors = [{instancePath:instancePath+"/ack",schemaPath:"#/properties/ack/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}}}}else {validate12.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];return false;}}validate12.errors = vErrors;return errors === 0;}
184
+ const byteToHex = [];
185
+ for (let i = 0; i < 256; ++i) {
186
+ byteToHex.push((i + 0x100).toString(16).slice(1));
187
+ }
188
+ function unsafeStringify(arr, offset = 0) {
189
+ return (byteToHex[arr[offset + 0]] +
190
+ byteToHex[arr[offset + 1]] +
191
+ byteToHex[arr[offset + 2]] +
192
+ byteToHex[arr[offset + 3]] +
193
+ '-' +
194
+ byteToHex[arr[offset + 4]] +
195
+ byteToHex[arr[offset + 5]] +
196
+ '-' +
197
+ byteToHex[arr[offset + 6]] +
198
+ byteToHex[arr[offset + 7]] +
199
+ '-' +
200
+ byteToHex[arr[offset + 8]] +
201
+ byteToHex[arr[offset + 9]] +
202
+ '-' +
203
+ byteToHex[arr[offset + 10]] +
204
+ byteToHex[arr[offset + 11]] +
205
+ byteToHex[arr[offset + 12]] +
206
+ byteToHex[arr[offset + 13]] +
207
+ byteToHex[arr[offset + 14]] +
208
+ byteToHex[arr[offset + 15]]).toLowerCase();
209
+ }
97
210
 
98
- // Unique ID creation requires a high quality random # generator. In the browser we therefore
99
- // require the crypto API and do not support built-in fallback to lower quality random number
100
- // generators (like Math.random()).
101
211
  let getRandomValues;
102
212
  const rnds8 = new Uint8Array(16);
103
213
  function rng() {
104
- // lazy load so that environments that need to polyfill have a chance to do so
105
- if (!getRandomValues) {
106
- // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
107
- getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
108
-
109
214
  if (!getRandomValues) {
110
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
215
+ if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
216
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
217
+ }
218
+ getRandomValues = crypto.getRandomValues.bind(crypto);
111
219
  }
112
- }
113
-
114
- return getRandomValues(rnds8);
115
- }
116
-
117
- /**
118
- * Convert array of 16 byte values to UUID string format of the form:
119
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
120
- */
121
-
122
- const byteToHex = [];
123
-
124
- for (let i = 0; i < 256; ++i) {
125
- byteToHex.push((i + 0x100).toString(16).slice(1));
126
- }
127
-
128
- function unsafeStringify(arr, offset = 0) {
129
- // Note: Be careful editing this code! It's been tuned for performance
130
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
131
- return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
220
+ return getRandomValues(rnds8);
132
221
  }
133
222
 
134
223
  const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
135
- var native = {
136
- randomUUID
137
- };
224
+ var native = { randomUUID };
138
225
 
139
226
  function v4(options, buf, offset) {
140
- if (native.randomUUID && true && !options) {
141
- return native.randomUUID();
142
- }
143
-
144
- options = options || {};
145
- const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
146
-
147
- rnds[6] = rnds[6] & 0x0f | 0x40;
148
- rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
149
-
150
- return unsafeStringify(rnds);
227
+ if (native.randomUUID && true && !options) {
228
+ return native.randomUUID();
229
+ }
230
+ options = options || {};
231
+ const rnds = options.random ?? options.rng?.() ?? rng();
232
+ if (rnds.length < 16) {
233
+ throw new Error('Random bytes length must be >= 16');
234
+ }
235
+ rnds[6] = (rnds[6] & 0x0f) | 0x40;
236
+ rnds[8] = (rnds[8] & 0x3f) | 0x80;
237
+ return unsafeStringify(rnds);
151
238
  }
152
239
 
153
240
  // console.log('OUT', __name({variableName}) );
@@ -235,25 +322,19 @@ function requireJsonMsg_cjs () {
235
322
  // "module" pattern to avoid "static" and "#" private : https://stackoverflow.com/a/1479341/298545
236
323
  var JSON_Msg = (function() {
237
324
  return {
238
- merge : function(json) {
239
- const dt_Msg= new Date();
240
- let json_msg= {
241
- id : v4(),
242
- referer : null,
243
- dt : dt_Msg.toISOString(),
244
- };
245
- // https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object
246
- for (var key of Object.keys(json)) {
247
- json_msg[key]= json[key];
248
- }
249
- return json_msg;
325
+ merge: function(json) {
326
+ return Object.assign({
327
+ id: v4(),
328
+ referer: null,
329
+ dt: new Date().toISOString()
330
+ }, json || {});
250
331
  },
251
- validate : function(json) {
252
- const b_valid= validate_Msg(json);
253
- if (!b_valid)
254
- LOGR_.log(l_.VALIDATION, 'JSON_Msg: validate: ', validate_Msg.errors);
332
+ validate : function (json) {
333
+ const b_valid = schema_Msg(json);
334
+ if (!b_valid)
335
+ LOGR_.log(l_.VALIDATION, 'JSON_Msg: validate: ', schema_Msg.errors);
255
336
  return b_valid;
256
- }
337
+ },
257
338
  // TODO: requires a separate ajv module require, and JTD specific schema
258
339
  // https://ajv.js.org/guide/getting-started.html#parsing-and-serializing-json
259
340
  // static #ajv_parse_= ajv.compileParser(this.#schema_json_Msg);
@@ -262,26 +343,24 @@ function requireJsonMsg_cjs () {
262
343
  // }
263
344
  }
264
345
  })();
265
-
346
+
266
347
  var JSON_Msg_msg = (function() {
267
348
  return {
268
- create_with_msg_merge : function(_msg, json) {
269
- let json_msg= JSON_Msg.merge(json);
270
- json_msg._msg= _msg;
271
- return json_msg;
349
+ create_with_msg_merge: function(_msg, json) {
350
+ return Object.assign(JSON_Msg.merge(json), { _msg });
272
351
  },
273
352
  validate : function(json) {
274
353
  if (! JSON_Msg.validate(json))
275
354
  return false;
276
- const b_valid= validate_Msg_msg(json);
355
+ const b_valid= schema_Msg_msg(json);
277
356
  if (!b_valid)
278
- LOGR_.log(l_.VALIDATION, 'JSON_Msg_msg: validate: ', validate_Msg_msg.errors);
357
+ LOGR_.log(l_.VALIDATION, 'JSON_Msg_msg: validate: ', schema_Msg_msg.errors);
279
358
  return b_valid;
280
359
  }
281
360
  }
282
361
  })();
283
362
 
284
- var JSON_MsgAck = (function() {
363
+ var JSON_MsgAck_msg = (function() {
285
364
  return {
286
365
  create_with_msgOk : function(_msg, b_ok= true) {
287
366
  return JSON_Msg_msg.create_with_msg_merge(_msg, {
@@ -301,53 +380,177 @@ function requireJsonMsg_cjs () {
301
380
  validate : function(json) {
302
381
  if (! JSON_Msg_msg.validate(json))
303
382
  return false;
304
- const b_valid= validate_MsgAck(json);
383
+ const b_valid= schema_MsgAck_msg(json);
305
384
  if (!b_valid)
306
- LOGR_.log(l_.VALIDATION, 'JSON_MsgAck: validate: ', validate_MsgAck.errors);
385
+ LOGR_.log(l_.VALIDATION, 'JSON_MsgAck: validate: ', schema_MsgAck_msg.errors);
307
386
  return b_valid;
308
387
  }
309
388
  }
310
389
  })();
311
390
 
312
391
  jsonMsg_cjs.JSON_Msg = JSON_Msg;
313
- jsonMsg_cjs.JSON_MsgAck = JSON_MsgAck;
392
+ jsonMsg_cjs.JSON_MsgAck_msg = JSON_MsgAck_msg;
314
393
  jsonMsg_cjs.JSON_Msg_msg = JSON_Msg_msg;
315
394
  return jsonMsg_cjs;
316
395
  }
317
396
 
318
397
  var jsonMsg_cjsExports = requireJsonMsg_cjs();
319
398
 
399
+ //-------------------------------------------------------------------------------------------------
400
+
401
+ let LOGR_$1= LOGR.get_instance();
402
+ const log_$1= LOGR_$1.log;
403
+
404
+ const l_$1= {
405
+ EVENTS : 0b1 << 0,
406
+ TIMEOUTS : 0b1 << 1,
407
+ };
408
+ LOGR_$1.labels= l_$1;
409
+ // LOGR_.toggled= {
410
+ // EVENTS : 1
411
+ // }
412
+
413
+
414
+ //-------------------------------------------------------------------------------------------------
415
+
416
+ class EventLog {
417
+ constructor() {
418
+ this.arr_events = []; // In-memory event store
419
+ this.map_index_id = new Map(); // Map of id -> array of indices into arr_events; arr_events[idx]
420
+ this.map_timeouts = new Map(); // Store timeout references: idx -> timeout_id
421
+ }
422
+
423
+ addEvent(type, id, data, timeout_ms = null, timeout_callback = null) {
424
+ const evt = {
425
+ type,
426
+ dt: Date.now(),
427
+ id,
428
+ data,
429
+ timeout_id: null // Will store timeout reference if set
430
+ };
431
+ const idx = this.arr_events.push(evt) - 1; // More efficient than .length before push
432
+
433
+ let arr_indices = this.map_index_id.get(id);
434
+ if (! arr_indices) {
435
+ arr_indices = [];
436
+ this.map_index_id.set(id, arr_indices);
437
+ }
438
+ arr_indices.push(idx);
439
+
440
+ // Set timeout if specified
441
+ if (timeout_ms && timeout_callback) {
442
+ evt.timeout_id = setTimeout(() => {
443
+ if (this.map_timeouts.delete(idx)) {
444
+ evt.timeout_id = null;
445
+ timeout_callback(evt);
446
+ log_$1(l_$1.EVENTS, `Event DELETED[${idx}]: ${type}`, evt);
447
+ }
448
+ }, timeout_ms);
449
+
450
+ this.map_timeouts.set(idx, evt.timeout_id);
451
+ }
452
+
453
+ log_$1(l_$1.EVENTS, `Event added[${idx}] @${Date(evt.dt).toISOString()}: ${type}`, evt);
454
+ return { idx, evt };
455
+ }
456
+
457
+ cancelTimeout(idx) {
458
+ const timeout_id = this.map_timeouts.get(idx);
459
+ if (timeout_id) {
460
+ clearTimeout(timeout_id);
461
+ this.map_timeouts.delete(idx);
462
+ if (this.arr_events[idx])
463
+ this.arr_events[idx].timeout_id = null;
464
+ return true;
465
+ }
466
+ return false;
467
+ }
468
+
469
+ cancelAllTimeouts() {
470
+ for (const [idx, timeout_id] of this.map_timeouts) {
471
+ clearTimeout(timeout_id);
472
+ if (this.arr_events[idx])
473
+ this.arr_events[idx].timeout_id = null;
474
+ }
475
+ this.map_timeouts.clear();
476
+ }
477
+
478
+ getEventById(id, lookback_ms = null) {
479
+ const arr_indices = this.map_index_id.get(id);
480
+ if (!arr_indices?.length) return [];
481
+
482
+ const result = [];
483
+ const cutoff = lookback_ms !== null ? Date.now() - lookback_ms : -Infinity;
484
+
485
+ // Single loop with early cutoff
486
+ for (let i = arr_indices.length - 1; i >= 0; i--) {
487
+ const idx = arr_indices[i];
488
+ const evt = this.arr_events[idx];
489
+ if (evt.dt < cutoff)
490
+ break;
491
+ result.push({ idx, evt });
492
+ }
493
+
494
+ return result; // Newest to oldest order
495
+ }
496
+
497
+ // getRecentEvents(id, lookbackMs) {
498
+ // const cutoff = Date.now() - lookbackMs;
499
+ // return this.events.filter(e => e.id === id && e.dt >= cutoff);
500
+ // }
501
+
502
+ getEvents(lookback_ms, predicate) {
503
+ const cutoff = Date.now() - lookback_ms;
504
+ const result = [];
505
+
506
+ // Iterate backwards from the end
507
+ for (let idx = this.arr_events.length - 1; idx >= 0; idx--) {
508
+ const evt = this.arr_events[idx];
509
+ if (evt.dt < cutoff) {
510
+ break; // Stop once we pass the cutoff
511
+ }
512
+ if (predicate(evt)) {
513
+ result.push({ idx, evt });
514
+ }
515
+ }
516
+
517
+ return result; // Newest to oldest order
518
+ }
519
+
520
+ // setLogr(obj_logr) {
521
+ // this.logr.toggled = obj_logr;
522
+ // }
523
+
524
+ clear() {
525
+ this.cancelAllTimeouts(); // Clear all timeouts before clearing events
526
+ this.arr_events.length = 0;
527
+ this.map_index_id.clear();
528
+ }
529
+ }
530
+
320
531
  const k_TTL= 20000;
321
532
 
322
533
  //-------------------------------------------------------------------------------------------------
323
534
 
324
- let LOGR_= new BitLogr();
535
+ // LOGR
536
+ // - l_LL and l_RR should accept 0b1 << 0 style shift
537
+ // - function to debug output bit values of labels instead of binary
538
+ // - rollup example in READMNE
325
539
 
326
- const l_msgs_ = {
327
- MSG : 0b1 << 0,
328
- WARP : 0b1 << 1,
329
- ENGAGE : 0b1 << 2,
330
- ACK : 0b1 << 3,
331
- };
540
+ const LOGR_= LOGR.get_instance();
541
+ const log_= LOGR_.log;
332
542
 
333
- const l_= {
334
- HANDLERS : 0b1 << 0,
335
- DROPS : 0b1 << 1,
336
- VALIDATION : 0b1 << 2,
337
- ... l_LL_(l_msgs_, 8)
338
- };
543
+ const l_msgs_ = l_array_(['PROTOCOL_STATE','RECVER','SENDER']); // b0, b1, b2
544
+
545
+ Object.assign(l_$1, l_array_(['EVENTS','TIMEOUTS'], 0b1 << 3)); // b3, b4
546
+
547
+ const l_= l_concat_( l_msgs_, l_concat_(l_$1, l_array_(['HANDLERS','DROPS','VALIDATION'])) );
339
548
  LOGR_.labels= l_;
340
549
 
341
550
  //-------------------------------------------------------------------------------------------------
342
551
 
343
552
  let map_Context_= new Map();
344
553
 
345
- function set_ctx(key, ctx) {
346
- map_Context_.set(key, ctx);
347
- // console.log(map_Context_);
348
- return ctx;
349
- }
350
-
351
554
  function get_ctx(key) {
352
555
  return map_Context_.get(key);
353
556
  }
@@ -355,20 +558,30 @@ function get_ctx(key) {
355
558
  //-------------------------------------------------------------------------------------------------
356
559
 
357
560
  class Config {
358
- receiver(callback_msgWarp,callback_msgEngage) {
561
+ constructor() {
562
+ // Initialize callbacks as no-op functions
563
+ this._callback_msgWarp = () => { console.assert(false, 'callback_msgWarp uninitialized'); };
564
+ this._callback_msgEngage = () => { console.assert(false, 'callback_msgEngage uninitialized'); };
565
+ this._callback_msgAckWarp = () => { console.assert(false, 'callback_msgAckWarp uninitialized'); };
566
+ this._callback_msgAckEngage = () => { console.assert(false, 'callback_msgAckEngage uninitialized'); };
567
+ this._callback_msg_sent_expired = () => { console.assert(false, '_callback_msg_sent_expired uninitialized'); };
568
+ this._callback_msgOptions = () => { console.assert(false, 'callback_msgOptions uninitialized'); };
569
+ }
570
+
571
+ receiver(callback_msgWarp, callback_msgEngage, callback_msg_sent_expired) {
359
572
  this._callback_msgWarp= callback_msgWarp;
360
573
  this._callback_msgEngage= callback_msgEngage;
574
+ this._callback_msg_sent_expired= callback_msg_sent_expired;
361
575
  }
362
- sender(callback_msgAckWarp,callback_msgAckEngage ) {
576
+ sender(callback_msgAckWarp, callback_msgAckEngage, callback_msg_sent_expired ) {
363
577
  this._callback_msgAckWarp= callback_msgAckWarp;
364
578
  this._callback_msgAckEngage= callback_msgAckEngage;
579
+ this._callback_msg_sent_expired= callback_msg_sent_expired;
365
580
  }
581
+
366
582
  set callback_msgOptions(callback) {
367
583
  this._callback_msgOptions= callback;
368
584
  }
369
- set logr(obj_logr) {
370
- LOGR_.toggled= obj_logr;
371
- }
372
585
  }
373
586
 
374
587
  // var config = (function() {
@@ -387,11 +600,21 @@ class Config {
387
600
 
388
601
  //-------------------------------------------------------------------------------------------------
389
602
 
390
- let k_VERSION= "0.7";
603
+ let k_VERSION= "0.8";
604
+
605
+ function t_ttl_rtt_(ttl_msec, rtt_msec) {
606
+ if (ttl_msec === undefined)
607
+ return undefined;
608
+ if (rtt_msec === undefined)
609
+ return ttl_msec *2;
610
+
611
+ console.assert(rtt_msec <= ttl_msec *2, `t_ttl_rtt_: INVALID rtt_msec ttl_msec[${ttl_msec}] rtt_msec[${rtt_msec}]`);
612
+ return (ttl_msec *2) + rtt_msec;
613
+ }
391
614
 
392
615
  var JSON_MsgOptions = (function() {
393
616
  return {
394
- create_with_msg_options : function(_msg, options) {
617
+ create_with_msg_options : function(_msg, options) {
395
618
  return jsonMsg_cjsExports.JSON_Msg_msg.create_with_msg_merge(_msg, {
396
619
  options: options,
397
620
  "2PhW": k_VERSION
@@ -400,12 +623,8 @@ var JSON_MsgOptions = (function() {
400
623
  validate : function(json) {
401
624
  if (! jsonMsg_cjsExports.JSON_Msg_msg.validate(json))
402
625
  return false;
403
- if (! validate_Msg2PhW(json)) {
404
- LOGR_.log(l_.VALIDATION, 'JSON_MsgWarp: validate_Msg2PhW_: ', validate_Msg2PhW.errors);
405
- return false;
406
- }
407
- if (! validate_MsgOptions(json)) {
408
- LOGR_.log(l_.VALIDATION, 'JSON_MsgOptions: validate_MsgOptions_: ', validate_MsgOptions.errors);
626
+ if (! schema_MsgOptions(json)) {
627
+ log_(l_.VALIDATION, () => ['JSON_MsgOptions: schema_MsgOptions_: ', schema_MsgOptions.errors]);
409
628
  return false;
410
629
  }
411
630
  return true;
@@ -415,9 +634,10 @@ var JSON_MsgOptions = (function() {
415
634
 
416
635
  var JSON_MsgWarp = (function() {
417
636
  return {
418
- create_with_user_hyperport : function(json_user, json_hyperport, nr_ttl_msec) {
637
+ create_with_id_user_hyperport : function(json_warp_id, json_user, json_hyperport, nr_ttl_msec) {
419
638
  return jsonMsg_cjsExports.JSON_Msg.merge({
420
639
  warp : {
640
+ id : json_warp_id,
421
641
  user : json_user,
422
642
  hyperport : json_hyperport,
423
643
  ttl_msec : nr_ttl_msec
@@ -425,15 +645,22 @@ var JSON_MsgWarp = (function() {
425
645
  "2PhW": k_VERSION
426
646
  });
427
647
  },
648
+ compare : function(json_L, json_R) {
649
+ if (json_L.dt !== json_R.dt)
650
+ return false;
651
+ if (json_L.warp.id !== json_R.warp.id)
652
+ return false;
653
+ if (json_L.referer[0] !== json_R.referer[0])
654
+ return false;
655
+ if (json_L.referer[1] !== json_R.referer[1])
656
+ return false;
657
+ return true;
658
+ },
428
659
  validate : function(json) {
429
660
  if (! jsonMsg_cjsExports.JSON_Msg.validate(json))
430
661
  return false;
431
- if (! validate_Msg2PhW(json)) {
432
- LOGR_.log(l_.VALIDATION, 'JSON_MsgWarp: validate_Msg2PhW_: ', validate_Msg2PhW.errors);
433
- return false;
434
- }
435
- if (! validate_MsgWarp(json)) {
436
- LOGR_.log(l_.VALIDATION, 'JSON_MsgWarp: validate_MsgWarp_: ', validate_MsgWarp.errors);
662
+ if (! schema_MsgWarp(json)) {
663
+ log_(l_.VALIDATION, () => ['JSON_MsgWarp: schema_MsgWarp_: ', schema_MsgWarp.errors]);
437
664
  return false;
438
665
  }
439
666
  return true;
@@ -442,32 +669,29 @@ var JSON_MsgWarp = (function() {
442
669
  })();
443
670
 
444
671
  var JSON_MsgEngage = (function() {
445
- return {
672
+ return {
446
673
  create_with_MsgWarp : function(json_msgWarp) {
447
- let json_msgEngage= jsonMsg_cjsExports.JSON_Msg.merge({
674
+ console.assert(json_msgWarp.ack === undefined, "Engage with a Warp, not an Ack");
675
+ return jsonMsg_cjsExports.JSON_Msg_msg.create_with_msg_merge(json_msgWarp, {
448
676
  engage : {
449
- user : json_msgWarp.warp.user,
450
- hyperport : json_msgWarp.warp.hyperport,
677
+ "ok" : true,
678
+ "rtt_msec" : Date.now() - Date.parse(json_msgWarp.dt)
451
679
  },
452
680
  "2PhW": k_VERSION
453
681
  });
454
- json_msgEngage["id"]= json_msgWarp.id;
455
- return json_msgEngage;
456
682
  },
457
683
  validate : function(json) {
458
- if (! jsonMsg_cjsExports.JSON_Msg.validate(json))
684
+ if (! jsonMsg_cjsExports.JSON_Msg_msg.validate(json))
459
685
  return false;
460
- if (! validate_Msg2PhW(json)) {
461
- LOGR_.log(l_.VALIDATION, 'JSON_MsgWarp: validate_Msg2PhW_: ', validate_Msg2PhW.errors);
686
+ if (! JSON_MsgWarp.validate(json._msg))
462
687
  return false;
463
- }
464
- if (! validate_MsgEngage(json)) {
465
- LOGR_.log(l_.VALIDATION, 'JSON_MsgEngage: validate_MsgEngage_: ', validate_MsgEngage.errors);
688
+ if (! schema_MsgEngage(json)) {
689
+ log_(l_.VALIDATION, () => ['JSON_MsgEngage: schema_MsgEngage_: ', schema_MsgEngage.errors]);
466
690
  return false;
467
691
  }
468
692
  return true;
469
693
  }
470
- }
694
+ };
471
695
  })();
472
696
 
473
697
  var JSON_MsgAckWarp = (function() {
@@ -478,21 +702,17 @@ var JSON_MsgAckWarp = (function() {
478
702
  // return json_msgAckWarp;
479
703
  // }
480
704
  create_with_msgOk : function(json_msgWarp, b_ok= true) {
481
- const json_msgAck= jsonMsg_cjsExports.JSON_MsgAck.create_with_msgOk(json_msgWarp, b_ok);
482
- json_msgAck["2PhW"]= k_VERSION;
483
- return json_msgAck;
705
+ const json_msgAck_msg= jsonMsg_cjsExports.JSON_MsgAck_msg.create_with_msgOk(json_msgWarp, b_ok);
706
+ json_msgAck_msg["2PhW"]= k_VERSION;
707
+ return json_msgAck_msg;
484
708
  },
485
709
  create_with_msgExpired : function( json_msgWarp ) {
486
- const json_msgAck= jsonMsg_cjsExports.JSON_MsgAck.create_with_msgExpired( json_msgWarp );
487
- json_msgAck["2PhW"]= k_VERSION;
488
- return json_msgAck;
710
+ const json_msgAck_msg= jsonMsg_cjsExports.JSON_MsgAck_msg.create_with_msgExpired( json_msgWarp );
711
+ json_msgAck_msg["2PhW"]= k_VERSION;
712
+ return json_msgAck_msg;
489
713
  },
490
714
  validate : function(json) {
491
- if (! validate_Msg2PhW(json)) {
492
- LOGR_.log(l_.VALIDATION, 'JSON_MsgAckWarp: validate_Msg2PhW_: ', validate_Msg2PhW.errors);
493
- return false;
494
- }
495
- if (! jsonMsg_cjsExports.JSON_MsgAck.validate(json))
715
+ if (! jsonMsg_cjsExports.JSON_MsgAck_msg.validate(json))
496
716
  return false;
497
717
  if (! JSON_MsgWarp.validate(json._msg))
498
718
  return false;
@@ -509,21 +729,17 @@ var JSON_MsgAckEngage = (function() {
509
729
  // return json_msgAckEngage;
510
730
  // }
511
731
  create_with_msgOk : function(json_msgEngage, b_ok= true) {
512
- const json_msgAck= jsonMsg_cjsExports.JSON_MsgAck.create_with_msgOk(json_msgEngage, b_ok);
513
- json_msgAck["2PhW"]= k_VERSION;
514
- return json_msgAck;
732
+ const json_msgAck_msg= jsonMsg_cjsExports.JSON_MsgAck_msg.create_with_msgOk(json_msgEngage, b_ok);
733
+ json_msgAck_msg["2PhW"]= k_VERSION;
734
+ return json_msgAck_msg;
515
735
  },
516
736
  create_with_msgExpired : function( json_msgEngage ) {
517
- const json_msgAck= jsonMsg_cjsExports.JSON_MsgAck.create_with_msgExpired( json_msgEngage );
518
- json_msgAck["2PhW"]= k_VERSION;
519
- return json_msgAck;
737
+ const json_msgAck_msg= jsonMsg_cjsExports.JSON_MsgAck_msg.create_with_msgExpired( json_msgEngage );
738
+ json_msgAck_msg["2PhW"]= k_VERSION;
739
+ return json_msgAck_msg;
520
740
  },
521
741
  validate : function(json) {
522
- if (! validate_Msg2PhW(json)) {
523
- LOGR_.log(l_.VALIDATION, 'JSON_MsgAckEngage: validate_Msg2PhW_: ', validate_Msg2PhW.errors);
524
- return false;
525
- }
526
- if (! jsonMsg_cjsExports.JSON_MsgAck.validate(json))
742
+ if (! jsonMsg_cjsExports.JSON_MsgAck_msg.validate(json))
527
743
  return false;
528
744
  if (! JSON_MsgEngage.validate(json._msg))
529
745
  return false;
@@ -532,305 +748,508 @@ var JSON_MsgAckEngage = (function() {
532
748
  }
533
749
  })();
534
750
 
535
-
536
751
  //-------------------------------------------------------------------------------------------------
537
- // State
752
+ // States
538
753
 
539
754
  class StateState {
540
- constructor(initState) {
541
- this.state_current_ = initState;
542
- this.dt_start_= null;
543
- this.nr_timeout_id_= -1;
544
- this.nr_remaining_msec_= 0;
545
- this.f_callback_= undefined;
546
- }
547
- start() {
548
- this.dt_start_= Date.now();
549
- console.log(`setTimeout: start ${this.dt_start_}, remaining ${this.nr_remaining_msec_}`);
550
- this.nr_timeout_id_= setTimeout(this.f_callback_, this.nr_remaining_msec_);
551
- }
552
- changeState(newState, nr_ttl_msec, f_callback) {
553
- if (! this.state_current_.changeState(newState))
554
- return false;
555
- this.state_current_ = newState;
556
-
557
- clearTimeout(this.nr_timeout_id_);
558
- if (nr_ttl_msec != undefined && f_callback != undefined) {
559
- this.f_callback_= f_callback;
560
- this.nr_remaining_msec_= nr_ttl_msec;
561
- this.start();
562
- }
563
- return true;
755
+ constructor(idx_event, event) {
756
+ this._protocol_parent = null;
757
+ this._idx_event = idx_event;
758
+ this._event = event;
759
+ }
760
+ get protocol() {
761
+ return this._protocol_parent;
564
762
  }
565
- delayTimeout(nr_delay_msec) {
566
- clearTimeout(this.nr_timeout_id_);
567
- const nr_elapsed_ms= Date.now() - this.dt_start_;
568
- this.nr_remaining_msec_= Math.max(this.nr_remaining_msec_ - nr_elapsed_ms, 0) + nr_delay_msec;
569
- this.start();
763
+ set protocol(parent) {
764
+ this._protocol_parent = parent;
570
765
  }
571
- inState(stateClass) {
572
- return this.state_current_ instanceof stateClass;
766
+ get idx_event() {
767
+ return this._idx_event;
768
+ }
769
+ get event() {
770
+ return this._event;
771
+ }
772
+ get json_msg() {
773
+ return this._event.data;
774
+ }
775
+ changeState(state_new) {
776
+ if (this.canChangeState(state_new))
777
+ this.protocol.state = state_new;
778
+ else
779
+ this.protocol.state = new StateINVALID(state_new._idx_event, state_new._event);
780
+ }
781
+ canChangeState(_state_new) {
782
+ throw new Error("Subclass must implement canChangeState()");
573
783
  }
574
784
  }
575
785
 
576
- class StateInitialState {
577
- changeState(newState) {
578
- return true;
786
+ class StateAckEngage extends StateState {
787
+ constructor(idx_event, event) { super(idx_event, event); }
788
+ get evt_AckEngage() { return this.event }
789
+ get json_msgAckEngage() { return this.json_msg }
790
+ canChangeState(_state_new) {
791
+ return false;
579
792
  }
580
793
  }
581
-
582
- // class State<Name> {
583
- // changeState= function(newState) {
584
- // return false;
585
- // }
586
- // }
587
794
 
588
- // if (newState instanceof State<Name>)
589
- // return true;
795
+ class StateEngage extends StateState {
796
+ constructor(idx_event, event) { super(idx_event, event); }
797
+ get evt_Engage() { return this.event }
798
+ get json_msgEngage() { return this.json_msg }
799
+ canChangeState(state_new) {
800
+ if (false === state_new instanceof StateAckEngage)
801
+ return false;
590
802
 
591
- // if (! <Class>.inState( State<Name> ))
592
- // if (! <Class>.changeState( new State<Name>() ))
593
-
594
- //-------------------------------------------------------------------------------------------------
803
+ // The Engage gets to live for THE WARP'S creation time + TTL*2 + RTT
804
+ const json_msgWarp= this.json_msgEngage._msg;
805
+ const timeout_ms= t_ttl_rtt_(json_msgWarp.warp.ttl_msec, this.json_msgEngage.engage.rtt_msec);
806
+ log_(l_.PROTOCOL_STATE, () => [`StateEngage: evt_AckEngage.dt@${state_new.evt_AckEngage.dt}, msgWarp.dt@${Date.parse(json_msgWarp.dt)} + ${timeout_ms}`]);
807
+ if (state_new.evt_AckEngage.dt >= Date.parse(json_msgWarp.dt) + timeout_ms)
808
+ return false;
595
809
 
596
- class ProtocolStateState extends StateState {
597
- constructor(initState= new StateInitialState() ) {
598
- super(initState);
810
+ return true;
599
811
  }
600
812
  }
601
813
 
602
- class StateWarp {
603
- changeState(newState) {
604
- if (newState instanceof StateAckWarp)
605
- return true;
606
- if (newState instanceof StateComplete)
607
- return true;
608
- return false;
609
- }
610
- }
814
+ class StateAckWarp extends StateState {
815
+ constructor(idx_event, event) { super(idx_event, event); }
816
+ get evt_AckWarp() { return this.event }
817
+ get json_msgAckWarp() { return this.json_msg }
818
+ canChangeState(state_new) {
819
+ if (false === state_new instanceof StateEngage)
820
+ return false;
611
821
 
612
- class StateAckWarp {
613
- changeState(newState) {
614
- if (newState instanceof StateEngage)
615
- return true;
616
- if (newState instanceof StateComplete)
617
- return true;
618
- return false;
822
+ if (! this.json_msgAckWarp.ack.ok)
823
+ return false;
824
+
825
+ if (this.json_msgAckWarp._msg.warp.instantaneous)
826
+ return false;
827
+
828
+ // The Ack gets to live for THE ACK'S creation time + TTL*2 + STT
829
+ // +STT, so lines up with the Engage timeout
830
+ // - Engage: T0 +2TTL +RTT; RTT= STT+STT
831
+ // - AckWarp: TAckWarp +2TLL +STT; TAckWarp= T0 +STT;
832
+ // - STT: Date of the Ack minus date of the Warp.
833
+ const timeout_ms= t_ttl_rtt_(this.json_msgAckWarp._msg.warp.ttl_msec) + Date.parse(this.json_msgAckWarp.dt) - Date.parse(this.json_msgAckWarp._msg.dt);
834
+ log_(l_.PROTOCOL_STATE, () => [`StateAckWarp: evt_Engage.dt@${state_new.evt_Engage.dt}, msgAckWarp.dt@${Date.parse(this.json_msgAckWarp.dt)} + ${timeout_ms}`]);
835
+ if (state_new.evt_Engage.dt >= Date.parse(this.json_msgAckWarp.dt) + timeout_ms)
836
+ return false;
837
+
838
+ return true;
619
839
  }
620
840
  }
621
841
 
622
- class StateEngage {
623
- changeState(newState) {
624
- if (newState instanceof StateComplete)
625
- return true;
626
- return false;
842
+ class StateWarp extends StateState {
843
+ constructor(idx_event, event) { super(idx_event, event); }
844
+ get evt_Warp() { return this.event }
845
+ get json_msgWarp() { return this.json_msg }
846
+ canChangeState(state_new) {
847
+ if (false === state_new instanceof StateAckWarp)
848
+ return false;
849
+
850
+ // The Warp gets to live for THE WARP'S creation time + TTL*2
851
+ const timeout_ms= t_ttl_rtt_(this.json_msgWarp.warp.ttl_msec);
852
+ log_(l_.PROTOCOL_STATE, () => [`StateWarp: evt_AckWarp.dt@${state_new.evt_AckWarp.dt}, msgWarp.dt@${Date.parse(this.json_msgWarp.dt)} + ${timeout_ms}`]);
853
+ if (state_new.evt_AckWarp.dt >= Date.parse(this.json_msgWarp.dt) + timeout_ms)
854
+ return false;
855
+
856
+ return true;
627
857
  }
628
858
  }
629
859
 
630
- class StateComplete {
631
- changeState(newState) {
860
+ class StateINVALID extends StateState {
861
+ constructor(idx_event, event) { super(idx_event, event); }
862
+ canChangeState(_state_new) {
863
+ // INVALID can't transition to any state
632
864
  return false;
633
865
  }
634
866
  }
635
867
 
636
- //-------------------------------------------------------------------------------------------------
637
-
638
- function handler_msgOptions_(cfg, msg, json_msgOptions)
639
- {
640
- LOGR_.log(l_.HANDLERS, 'handler_msgOptions_: ...');
641
-
642
- if (! validate_Options_delay(json_msgOptions.options))
643
- return false;
644
-
645
- if (JSON_MsgWarp.validate(json_msgOptions._msg)) {
646
- const json_msgWarp= json_msgOptions._msg;
647
-
648
- const ctx= get_ctx(json_msgWarp.id);
649
- if (!ctx )
868
+ class StateInitialState extends StateState {
869
+ constructor() { super(null, null); }
870
+ canChangeState(state_new) {
871
+ if (false === state_new instanceof StateWarp)
650
872
  return false;
651
873
 
652
- json_msgOptions.options.ttl_msec_incr[0];
653
- const ttl_incr= json_msgOptions.options.ttl_msec_incr[1];
654
-
655
- //TODO: double check ttl_msec is the same as current accummulated ttl for idempotence.
874
+ // The NEWLY created Warp only gets to live for its creation time + TTL
875
+ const timeout_ms= state_new.json_msgWarp.warp.ttl_msec;
876
+ log_(l_.PROTOCOL_STATE, () => [`StateInitialState: evt_Warp.dt@${state_new.evt_Warp.dt}, msgWarp.dt@${Date.parse(state_new.json_msgWarp.dt)} + ${timeout_ms}`]);
877
+ if (state_new.evt_Warp.dt >= Date.parse(state_new.json_msgWarp.dt) + timeout_ms)
878
+ return false;
656
879
 
657
- LOGR_.log(l_.HANDLERS, 'handler_msgOptions_: ', json_msgOptions);
880
+ return true;
881
+ }
882
+ }
658
883
 
659
- ctx.protocol.delayTimeout(ttl_incr);
884
+ //----
660
885
 
661
- if (cfg._callback_msgOptions)
662
- return cfg._callback_msgOptions(msg, json_msgOptions);
886
+ class ProtocolStateState {
887
+ constructor(state_initial) {
888
+ this.state = state_initial || new StateInitialState();
889
+ }
663
890
 
664
- return true;
891
+ set state(state_new) {
892
+ if (! (state_new instanceof StateState)) {
893
+ throw new Error("initState must be an instance of StateState or its subclasses");
894
+ }
895
+ this._state = state_new;
896
+ if (state_new && state_new.protocol !== this) {
897
+ state_new.protocol = this;
898
+ }
899
+ }
900
+ get state() {
901
+ return this._state;
665
902
  }
666
903
 
667
- return false;
904
+ canChangeState(state_new) {
905
+ return this._state.canChangeState(state_new);
906
+ }
668
907
  }
669
908
 
670
909
  //-------------------------------------------------------------------------------------------------
671
- // Sender
672
910
 
673
- function handler_msgAckWarp_(cfg, msg, json_msgAckWarp)
674
- {
675
- // NOTE: json_msgAck here has a string as _msg, instead of JSON.
911
+ class TwoPhW_EventLog {
912
+ constructor(eventLog) {
913
+ this._eventLog = eventLog;
914
+ }
676
915
 
677
- LOGR_.log(l_.HANDLERS, 'handler_msgAckWarp: ...');
916
+ _warp(json_msg) {
917
+ const b_Ack = json_msg.ack !== undefined;
918
+ const json = b_Ack ? json_msg["_msg"] : json_msg;
678
919
 
679
- const json_msgWarp= json_msgAckWarp._msg;
920
+ if (json.warp) {
921
+ return {
922
+ str_type: `2PhW[JSON_Msg${b_Ack ? 'Ack' : ''}Warp]`,
923
+ json_msgWarp: json
924
+ };
925
+ }
926
+ if (json.engage) {
927
+ return {
928
+ str_type: `2PhW[JSON_Msg${b_Ack ? 'Ack' : ''}Engage]`,
929
+ json_msgWarp: json["_msg"]
930
+ };
931
+ }
932
+ return null; // Explicit default for invalid cases
933
+ }
680
934
 
681
- const ctx= get_ctx(json_msgWarp.id);
682
- if (!ctx || !ctx.protocol.changeState( new StateAckWarp() ))
683
- return false;
935
+ _addEvent(json_msg, timeout_ms, timeout_callback) {
936
+ const { str_type, json_msgWarp }= this._warp(json_msg);
937
+ const { idx }= this._eventLog.addEvent(str_type, json_msgWarp.warp.id, json_msg, timeout_ms, timeout_callback);
938
+ log_(l_.PROTOCOL_STATE, () => [`_addEvent: [${idx}] timeout:${Date.now()}+${timeout_ms} `, json_msg]);
939
+ }
684
940
 
685
- //TODO: check if multiple warps have been sent out with the same destination
941
+ _dropEvent(json_msg) {
942
+ const { json_msgWarp }= this._warp(json_msg);
943
+ this._eventLog.addEvent('2PhW[DROPPED!]', json_msgWarp.warp.id, json_msg);
944
+ }
686
945
 
687
- LOGR_.log(l_.HANDLERS, 'handler_msgAckWarp: ', json_msgAckWarp);
946
+ _cancelTimeout(idx_event) {
947
+ log_(l_.PROTOCOL_STATE, () => [`_cancelTimeout: [${idx_event}] timeout cancelled`]);
948
+ this._eventLog.cancelTimeout(idx_event);
949
+ }
688
950
 
689
- // const json_msgAckWarp= JSON_MsgAckWarp.createWith_msgAck_msg(json_msgAck, json_msgWarp);
951
+ get_protocolState(json_msgWarp) {
952
+ const protocolState = new ProtocolStateState();
953
+
954
+ const arr_evts= this._eventLog.getEventById(json_msgWarp.warp.id, k_TTL);
955
+ log_(l_.EVENTS, () => ['get_protocolState: arr_evts: ', arr_evts]);
956
+
957
+ for (let i = arr_evts.length - 1; i >= 0; i--) {
958
+ const { idx, evt } = arr_evts[i];
959
+
960
+ if (evt.type === '2PhW[DROPPED!]')
961
+ continue;
962
+
963
+ const json_msg= evt.data;
964
+ if (! JSON_MsgWarp.compare(json_msgWarp, this._warp(json_msg).json_msgWarp) )
965
+ protocolState.state.changeState( new StateINVALID(idx, evt) );
966
+
967
+ switch(evt.type) {
968
+ case '2PhW[JSON_MsgWarp]' :
969
+ protocolState.state.changeState( new StateWarp(idx, evt) );
970
+ break;
971
+ case '2PhW[JSON_MsgAckWarp]' :
972
+ protocolState.state.changeState( new StateAckWarp(idx, evt) );
973
+ break;
974
+ case '2PhW[JSON_MsgEngage]' :
975
+ protocolState.state.changeState( new StateEngage(idx, evt) );
976
+ break;
977
+ case '2PhW[JSON_MsgAckEngage]' :
978
+ protocolState.state.changeState( new StateAckEngage(idx, evt) );
979
+ break;
980
+ default :
981
+ protocolState.state.changeState( new StateINVALID(idx, evt) );
982
+ break;
983
+ }
984
+ log_(l_.PROTOCOL_STATE, () => ['get_protocolState: type,state: ',
985
+ evt.type,
986
+ (protocolState.state.json_msg.ack?.ok === false) ? '--NACK--' : '',
987
+ protocolState.state
988
+ ]);
989
+ }
990
+ return protocolState;
991
+ }
690
992
 
691
- if (! cfg._callback_msgAckWarp(msg, json_msgAckWarp))
692
- return false;
993
+ }
693
994
 
694
- if (json_msgWarp.warp.instantaneous) {
695
- const b_res= ctx.protocol.changeState( new StateComplete() );
696
- console.assert(b_res);
697
-
698
- return true;
995
+ class TwoPhW {
996
+ constructor(eventLog) {
997
+ this._2PhW_eventLog = new TwoPhW_EventLog(eventLog);
998
+ this._config= new Config();
699
999
  }
700
1000
 
701
- const b_res= ctx.protocol.changeState( new StateEngage() );
702
- console.assert(b_res);
1001
+ get config() {
1002
+ return this._config;
1003
+ }
703
1004
 
704
- return true;
705
- }
1005
+ get eventLog() {
1006
+ return this._2PhW_eventLog;
1007
+ }
1008
+
1009
+ //-------------------------------------------------------------------------------------------------
706
1010
 
707
- function handler_msgAckEngage_(cfg, msg, json_msgAckEngage)
708
- {
709
- // NOTE: json_msgAck here has a string as _msg, instead of JSON.
1011
+ _handler_msgOptions(cfg, msg, json_msgOptions)
1012
+ {
1013
+ log_(l_.HANDLERS, () => ['handler_msgOptions_: ...']);
1014
+
1015
+ if (! validate_Options_delay_(json_msgOptions.options))
1016
+ return false;
1017
+
1018
+ if (JSON_MsgWarp.validate(json_msgOptions._msg)) {
1019
+ const json_msgWarp= json_msgOptions._msg;
1020
+
1021
+ const ctx= get_ctx(json_msgWarp.id);
1022
+ if (!ctx )
1023
+ return false;
1024
+
1025
+ json_msgOptions.options.ttl_msec_incr[0];
1026
+ const ttl_incr= json_msgOptions.options.ttl_msec_incr[1];
1027
+
1028
+ //TODO: double check ttl_msec is the same as current accummulated ttl for idempotence.
1029
+
1030
+ log_(l_.HANDLERS, () => ['handler_msgOptions_: ', json_msgOptions]);
1031
+
1032
+ ctx.protocol.delayTimeout(ttl_incr);
1033
+
1034
+ if (cfg._callback_msgOptions)
1035
+ return cfg._callback_msgOptions(msg, json_msgOptions);
1036
+
1037
+ return true;
1038
+ }
1039
+
1040
+ return false;
1041
+ }
1042
+
1043
+ //-------------------------------------------------------------------------------------------------
1044
+ // sender Source (src)
1045
+
1046
+ register_msgWarp(json_msgWarp)
1047
+ {
1048
+ log_(l_.SENDER, () => ['register_msgWarp: ', json_msgWarp]);
710
1049
 
711
- LOGR_.log(l_.HANDLERS, 'handler_msgAckEngage: ...');
1050
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1051
+ const b_changeState= protocolState.canChangeState( new StateWarp(null, {
1052
+ dt: Date.now(),
1053
+ data: json_msgWarp
1054
+ }) );
712
1055
 
713
- const json_msgEngage= json_msgAckEngage._msg;
1056
+ log_(l_.HANDLERS | l_.SENDER, () => ['register_msgWarp: protocolState.canChangeState ', b_changeState]);
1057
+ if (! b_changeState)
1058
+ return false;
714
1059
 
715
- const ctx= get_ctx(json_msgEngage.id);
716
- if (!ctx || !ctx.protocol.changeState( new StateAckEngage() ))
717
- return false;
1060
+ const timeout_ms= t_ttl_rtt_(json_msgWarp.warp.ttl_msec);
1061
+ const elapsed_ms= Date.now() - Date.parse(json_msgWarp.dt);
718
1062
 
719
- LOGR_.log(l_.HANDLERS, 'handler_msgAckEngage: ', json_msgAckEngage);
1063
+ this.eventLog._addEvent(json_msgWarp, timeout_ms-elapsed_ms, () => {
1064
+ this.config._callback_msg_sent_expired(json_msgWarp);
1065
+ });
1066
+ }
720
1067
 
721
- // const json_msgAckEngage= JSON_MsgAckEngage.createWith_msgAck_msg(json_msgAck, json_msgEngage);
1068
+ _handler_msgAckWarp(msg, json_msgAckWarp)
1069
+ {
1070
+ log_(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckWarp: ', json_msgAckWarp]);
1071
+
1072
+ const json_msgWarp= json_msgAckWarp._msg;
1073
+
1074
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1075
+ const b_changeState= protocolState.canChangeState( new StateAckWarp(null, {
1076
+ dt: Date.now(),
1077
+ data: json_msgAckWarp
1078
+ }) );
1079
+
1080
+ log_(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckWarp: protocolState.canChangeState ', b_changeState]);
1081
+ if (! b_changeState)
1082
+ return false;
722
1083
 
723
- if (! cfg._callback_msgAckEngage(msg, json_msgAckEngage))
724
- return false;
1084
+ this.eventLog._cancelTimeout(protocolState.state.idx_event);
1085
+ this.eventLog._addEvent(json_msgAckWarp);
1086
+ if (! this.config._callback_msgAckWarp(msg, json_msgAckWarp))
1087
+ return false;
1088
+
1089
+ return true;
1090
+ }
725
1091
 
726
- return true;
727
- }
1092
+ register_msgEngage(json_msgEngage)
1093
+ {
1094
+ log_(l_.SENDER, () => ['register_msgEngage: ', json_msgEngage]);
728
1095
 
729
- //-------------------------------------------------------------------------------------------------
730
- // Receiver
1096
+ const json_msgWarp= json_msgEngage._msg;
731
1097
 
732
- function handler_msgWarp_(cfg, msg, json_msgWarp)
733
- {
734
- LOGR_.log(l_.HANDLERS, 'handler_msgWarp: ...');
1098
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1099
+ const b_changeState= protocolState.canChangeState( new StateEngage(null, {
1100
+ dt: Date.now(),
1101
+ data : json_msgEngage
1102
+ }) );
735
1103
 
736
- let ctx= get_ctx(json_msgWarp.id);
737
- if (ctx === undefined)
738
- ctx= set_ctx(json_msgWarp.id, { protocol: new ProtocolStateState() });
1104
+ log_(l_.HANDLERS | l_.SENDER, () => ['register_msgEngage: protocolState.canChangeState ', b_changeState]);
1105
+ if (! b_changeState)
1106
+ return false;
1107
+
1108
+ const timeout_ms= t_ttl_rtt_(json_msgWarp.warp.ttl_msec, json_msgEngage.engage.rtt_msec);
1109
+ const elapsed_ms= Date.now() - Date.parse(json_msgWarp.dt);
739
1110
 
740
- if (!ctx || !ctx.protocol.changeState( new StateWarp() ))
741
- return false;
1111
+ this.eventLog._addEvent(json_msgEngage, timeout_ms-elapsed_ms, () => {
1112
+ this.config._callback_msg_sent_expired(json_msgEngage);
1113
+ });
1114
+ }
1115
+
1116
+ _handler_msgAckEngage(msg, json_msgAckEngage)
1117
+ {
1118
+ log_(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckEngage: ', json_msgAckEngage]);
1119
+
1120
+ const json_msgWarp= json_msgAckEngage._msg._msg;
742
1121
 
743
- LOGR_.log(l_.HANDLERS, 'handler_msgWarp: ', json_msgWarp);
1122
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1123
+ const b_changeState= protocolState.canChangeState( new StateAckEngage(null, {
1124
+ dt: Date.now(),
1125
+ data : json_msgAckEngage
1126
+ }) );
744
1127
 
745
- if (! cfg._callback_msgWarp(msg, json_msgWarp))
746
- return false;
1128
+ log_(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckEngage_: protocolState.canChangeState ', b_changeState]);
1129
+ if (! b_changeState)
1130
+ return false;
747
1131
 
748
- if (json_msgWarp.warp.instantaneous) {
749
- const b_res= ctx.protocol.changeState( new StateComplete() );
750
- console.assert(b_res);
1132
+ this.eventLog._cancelTimeout(protocolState.state.idx_event);
1133
+ this.eventLog._addEvent(json_msgAckEngage);
1134
+ if (! this.config._callback_msgAckEngage(msg, json_msgAckEngage))
1135
+ return false;
751
1136
 
752
1137
  return true;
753
1138
  }
1139
+
1140
+ //-------------------------------------------------------------------------------------------------
1141
+ // receiver Destination (dst)
754
1142
 
755
- const b_res= ctx.protocol.changeState( new StateAckWarp() );
756
- console.assert(b_res);
1143
+ _handler_msgWarp(msg, json_msgWarp)
1144
+ {
1145
+ log_(l_.HANDLERS | l_.RECVER, () => ['handler_msgWarp: ', json_msgWarp]);
1146
+
1147
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1148
+ const b_changeState= protocolState.canChangeState( new StateWarp(null, {
1149
+ dt: Date.now(),
1150
+ data: json_msgWarp
1151
+ }) );
1152
+
1153
+ log_(l_.HANDLERS | l_.RECVER, () => ['handler_msgWarp: protocolState.canChangeState: ', b_changeState]);
1154
+ if (! b_changeState)
1155
+ return false;
757
1156
 
758
- return true;
759
- }
1157
+ this.eventLog._addEvent(json_msgWarp);
1158
+ if (! this.config._callback_msgWarp(msg, json_msgWarp))
1159
+ return false;
1160
+
1161
+ return true;
1162
+ }
1163
+
1164
+ register_msgAckWarp(json_msgAckWarp)
1165
+ {
1166
+ log_(l_.RECVER, () => ['register_msgAckWarp: ', json_msgAckWarp]);
760
1167
 
761
- function handler_msgEngage_(cfg, msg, json_msgEngage)
762
- {
763
- LOGR_.log(l_.HANDLERS, 'handler_msgEngage: ...');
1168
+ const json_msgWarp= json_msgAckWarp._msg;
764
1169
 
765
- const ctx= get_ctx(json_msgEngage.id);
766
- if (!ctx || !ctx.protocol.changeState( new StateEngage() ))
767
- return false;
1170
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1171
+ const b_changeState= protocolState.canChangeState( new StateAckWarp(null, {
1172
+ dt: Date.now(),
1173
+ data: json_msgAckWarp
1174
+ }) );
768
1175
 
769
- LOGR_.log(l_.HANDLERS, 'handler_msgEngage: ', json_msgEngage);
1176
+ log_(l_.HANDLERS | l_.RECVER, () => ['register_msgAckWarp: protocolState.canChangeState: ', b_changeState]);
1177
+ if (! b_changeState)
1178
+ return false;
770
1179
 
771
- if (! cfg._callback_msgEngage(msg, json_msgEngage))
772
- return false;
1180
+ const elapsed_ms= Date.now() - Date.parse(json_msgAckWarp.dt);
1181
+ const timeout_ms= t_ttl_rtt_(json_msgWarp.warp.ttl_msec) + Date.parse(json_msgAckWarp.dt) - Date.parse(json_msgWarp.dt);
773
1182
 
774
- const b_res= ctx.protocol.changeState( new StateComplete() );
775
- console.assert(b_res);
1183
+ this.eventLog._addEvent(json_msgAckWarp, timeout_ms-elapsed_ms, () => {
1184
+ this.config._callback_msg_sent_expired(json_msgAckWarp);
1185
+ });
1186
+ }
776
1187
 
777
- return true;
778
- }
1188
+ _handler_msgEngage(msg, json_msgEngage)
1189
+ {
1190
+ log_(l_.HANDLERS | l_.RECVER, () => ['handler_msgEngage: ', json_msgEngage]);
779
1191
 
780
- //-------------------------------------------------------------------------------------------------
1192
+ const json_msgWarp= json_msgEngage["_msg"];
781
1193
 
782
- class TwoPhW {
783
- constructor() {
784
- this._config= new Config();
785
- }
1194
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1195
+ const b_changeState= protocolState.canChangeState( new StateEngage(null, {
1196
+ dt: Date.now(),
1197
+ data: json_msgEngage
1198
+ }) );
786
1199
 
787
- get config() {
788
- return this._config;
1200
+ log_(l_.HANDLERS | l_.RECVER, () => ['handler_msgEngage: protocolState.canChangeState: ', b_changeState]);
1201
+ if (! b_changeState)
1202
+ return false;
1203
+
1204
+ this.eventLog._cancelTimeout(protocolState.state.idx_event);
1205
+ this.eventLog._addEvent(json_msgEngage);
1206
+ if (! this.config._callback_msgEngage(msg, json_msgEngage))
1207
+ return false;
1208
+
1209
+ return true;
789
1210
  }
790
1211
 
791
- // this function need to be removed when a microservice db is used instead of a state machine
792
- create_MsgWarp_out(str_id, json_user, json_hyperport, nr_ttl_msec, b_instantaneous)
1212
+ register_msgAckEngage(json_msgAckEngage)
793
1213
  {
794
- if (nr_ttl_msec === undefined)
795
- nr_ttl_msec= k_TTL;
1214
+ log_(l_.RECVER, () => ['register_msgAckEngage: ', json_msgAckEngage]);
796
1215
 
797
- const json_msgWarp= JSON_MsgWarp.create_with_user_hyperport(json_user, json_hyperport, nr_ttl_msec);
798
- json_msgWarp.id= str_id;
799
-
800
- if (b_instantaneous !== undefined)
801
- json_msgWarp.warp.instantaneous= b_instantaneous;
1216
+ const json_msgWarp= json_msgAckEngage._msg._msg;
802
1217
 
803
- const ctx= set_ctx(json_msgWarp.id, { protocol: new ProtocolStateState() });
804
- const b_res= ctx.protocol.changeState( new StateWarp(), nr_ttl_msec, function() {
805
- const json_Nack= JSON_MsgAckWarp.create_with_msgExpired( json_msgWarp );
806
- //TODO: the referer is NULL here !
807
- this._config._callback_msgAckWarp(json_Nack, json_Nack);
808
- }.bind(this) );
1218
+ const protocolState= this.eventLog.get_protocolState(json_msgWarp);
1219
+ const b_changeState= protocolState.canChangeState( new StateAckEngage(null, {
1220
+ dt: Date.now(),
1221
+ data: json_msgAckEngage
1222
+ }) );
1223
+
1224
+ log_(l_.HANDLERS | l_.RECVER, () => ['register_msgAckEngage: protocolState.canChangeState: ', b_changeState]);
1225
+ if (! b_changeState)
1226
+ return false;
809
1227
 
810
- console.assert(b_res);
811
- return json_msgWarp;
1228
+ this.eventLog._addEvent(json_msgAckEngage);
812
1229
  }
813
1230
 
1231
+ //-------------------------------------------------------------------------------------------------
1232
+
814
1233
  handler_msg_json(msg, json_msg)
815
1234
  {
816
- LOGR_.log(l_.HANDLERS, 'handler_msg_json: ', json_msg);
1235
+ log_(l_.HANDLERS, () => ['handler_msg_json: ', json_msg]);
817
1236
 
818
1237
  // ADR: I could parse json_Msg_msg first and then MsgAck or MsgOptions, but
819
1238
  // doing so means super classes get parsed multiple times for no reason
820
1239
 
821
- if (JSON_MsgOptions.validate(json_msg) && handler_msgOptions_(this._config, msg, json_msg))
822
- return true;
1240
+ // if (JSON_MsgOptions.validate(json_msg) && this.handler_msgOptions_(this._config, msg, json_msg))
1241
+ // return true;
823
1242
 
824
- if (JSON_MsgWarp.validate(json_msg) && handler_msgWarp_(this._config, msg, json_msg))
1243
+ if (JSON_MsgWarp.validate(json_msg) && this._handler_msgWarp(msg, json_msg))
825
1244
  return true;
826
1245
 
827
- if (JSON_MsgEngage.validate(json_msg) && handler_msgEngage_(this._config, msg, json_msg))
1246
+ if (JSON_MsgEngage.validate(json_msg) && this._handler_msgEngage(msg, json_msg))
828
1247
  return true;
829
1248
 
830
- if (JSON_MsgAckWarp.validate(json_msg) && handler_msgAckWarp_(this._config, msg, json_msg))
1249
+ if (JSON_MsgAckWarp.validate(json_msg) && this._handler_msgAckWarp(msg, json_msg))
831
1250
  return true;
832
1251
 
833
- if (JSON_MsgAckEngage.validate(json_msg) && handler_msgAckEngage_(this._config, msg, json_msg))
1252
+ if (JSON_MsgAckEngage.validate(json_msg) && this._handler_msgAckEngage(msg, json_msg))
834
1253
  return true;
835
1254
 
836
1255
  // https://attacomsian.com/blog/javascript-iterate-objects
@@ -842,12 +1261,14 @@ class TwoPhW {
842
1261
  // console.log(`${key}: ${json_msg[key]}`);
843
1262
  // });
844
1263
 
1264
+ this.eventLog._dropEvent(json_msg);
1265
+ log_(l_.DROPS, () => ["TwoPhW: handler_msg: DROP! ", msg]);
845
1266
  return false;
846
1267
  }
847
1268
 
848
1269
  handler_msg_str(msg, str_msg)
849
1270
  {
850
- LOGR_.log(l_.HANDLERS, 'handler_msg_str: ['+ str_msg +']');
1271
+ log_(l_.HANDLERS, () => ['handler_msg_str: ['+ str_msg +']']);
851
1272
 
852
1273
  // ... test strings here
853
1274
 
@@ -864,24 +1285,31 @@ class TwoPhW {
864
1285
 
865
1286
  handler_msg(msg)
866
1287
  {
867
- LOGR_.log(l_.HANDLERS, 'handler_msg: ', msg);
1288
+ log_(l_.HANDLERS, () => ['handler_msg: ', msg]);
868
1289
 
869
1290
  if (typeof (msg) === 'string' && this.handler_msg_str(msg, msg))
870
1291
  return true;
871
1292
 
872
1293
  if (typeof (msg) === 'object' && this.handler_msg_json(msg, msg))
873
1294
  return true;
874
-
875
- LOGR_.log(l_.DROPS, "handler_msg: DROP! ", msg);
1295
+
876
1296
  return false
877
1297
  }
878
1298
 
879
1299
  }
880
1300
 
1301
+ exports.EventLog = EventLog;
881
1302
  exports.JSON_MsgAckEngage = JSON_MsgAckEngage;
882
1303
  exports.JSON_MsgAckWarp = JSON_MsgAckWarp;
883
1304
  exports.JSON_MsgEngage = JSON_MsgEngage;
884
1305
  exports.JSON_MsgOptions = JSON_MsgOptions;
885
1306
  exports.JSON_MsgWarp = JSON_MsgWarp;
1307
+ exports.StateAckEngage = StateAckEngage;
1308
+ exports.StateAckWarp = StateAckWarp;
1309
+ exports.StateEngage = StateEngage;
1310
+ exports.StateINVALID = StateINVALID;
1311
+ exports.StateInitialState = StateInitialState;
1312
+ exports.StateWarp = StateWarp;
886
1313
  exports.TwoPhW = TwoPhW;
887
1314
  exports.l = l_;
1315
+ exports.t_ttl_rtt = t_ttl_rtt_;