@rootintf/protocol-2phw 2.3.7-api.2 → 3.1.2-api.4

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,935 +1,62 @@
1
+ import { l_merge, l_concat, l_array, lRef, LOGR } from '@knev/bitlogr';
2
+ import { logr as logr$1, JSON_Hold, JSON_Ack } from '@rootintf/json-msg';
3
+ export { JSON_Ack, JSON_Eff, JSON_Msg } from '@rootintf/json-msg';
1
4
  import { logr } from '@rootintf/eventlog';
2
5
 
3
- const schema_MsgWarp = validate19;
4
- function validate19(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { let vErrors = null; let errors = 0; const evaluated0 = validate19.evaluated; if (evaluated0.dynamicProps) {
5
- evaluated0.props = undefined;
6
- } if (evaluated0.dynamicItems) {
7
- evaluated0.items = undefined;
8
- } {
9
- if (data && typeof data == "object" && !Array.isArray(data)) {
10
- let missing0;
11
- if ((data.warp === undefined) && (missing0 = "warp")) {
12
- validate19.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }];
13
- return false;
14
- }
15
- else {
16
- if (data.warp !== undefined) {
17
- let data0 = data.warp;
18
- const _errs1 = errors;
19
- {
20
- if (data0 && typeof data0 == "object" && !Array.isArray(data0)) {
21
- let missing1;
22
- if (((((data0.id === undefined) && (missing1 = "id")) || ((data0.user === undefined) && (missing1 = "user"))) || ((data0.hyperport === undefined) && (missing1 = "hyperport"))) || ((data0.ttl_msec === undefined) && (missing1 = "ttl_msec"))) {
23
- validate19.errors = [{ instancePath: instancePath + "/warp", schemaPath: "#/properties/warp/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }];
24
- return false;
25
- }
26
- else {
27
- if (data0.id !== undefined) {
28
- const _errs3 = errors;
29
- if (typeof data0.id !== "string") {
30
- validate19.errors = [{ instancePath: instancePath + "/warp/id", schemaPath: "definitions#/definitions/warp_id/type", keyword: "type", params: { type: "string" }, message: "must be string" }];
31
- return false;
32
- }
33
- var valid1 = _errs3 === errors;
34
- }
35
- else {
36
- var valid1 = true;
37
- }
38
- if (valid1) {
39
- if (data0.ttl_msec !== undefined) {
40
- let data2 = data0.ttl_msec;
41
- const _errs6 = errors;
42
- if (!(((typeof data2 == "number") && (!(data2 % 1) && !isNaN(data2))) && (isFinite(data2)))) {
43
- validate19.errors = [{ instancePath: instancePath + "/warp/ttl_msec", schemaPath: "#/properties/warp/properties/ttl_msec/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }];
44
- return false;
45
- }
46
- var valid1 = _errs6 === errors;
47
- }
48
- else {
49
- var valid1 = true;
50
- }
51
- if (valid1) {
52
- if (data0.instantaneous !== undefined) {
53
- const _errs8 = errors;
54
- if (typeof data0.instantaneous !== "boolean") {
55
- validate19.errors = [{ instancePath: instancePath + "/warp/instantaneous", schemaPath: "#/properties/warp/properties/instantaneous/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }];
56
- return false;
57
- }
58
- var valid1 = _errs8 === errors;
59
- }
60
- else {
61
- var valid1 = true;
62
- }
63
- }
64
- }
65
- }
66
- }
67
- else {
68
- validate19.errors = [{ instancePath: instancePath + "/warp", schemaPath: "#/properties/warp/type", keyword: "type", params: { type: "object" }, message: "must be object" }];
69
- return false;
70
- }
71
- }
72
- var valid0 = _errs1 === errors;
73
- }
74
- else {
75
- var valid0 = true;
76
- }
77
- if (valid0) {
78
- if (data["2PhW"] !== undefined) {
79
- const _errs10 = errors;
80
- if ("2" !== data["2PhW"]) {
81
- validate19.errors = [{ instancePath: instancePath + "/2PhW", schemaPath: "definitions#/definitions/2PhW/const", keyword: "const", params: { allowedValue: "2" }, message: "must be equal to constant" }];
82
- return false;
83
- }
84
- var valid0 = _errs10 === errors;
85
- }
86
- else {
87
- var valid0 = true;
88
- }
89
- }
90
- }
91
- }
92
- else {
93
- validate19.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }];
94
- return false;
95
- }
96
- } validate19.errors = vErrors; return errors === 0; }
97
- validate19.evaluated = { "props": { "warp": true, "2PhW": true }, "dynamicProps": false, "dynamicItems": false };
98
- const schema_MsgEngage = validate20;
99
- function validate20(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { let vErrors = null; let errors = 0; const evaluated0 = validate20.evaluated; if (evaluated0.dynamicProps) {
100
- evaluated0.props = undefined;
101
- } if (evaluated0.dynamicItems) {
102
- evaluated0.items = undefined;
103
- } {
104
- if (data && typeof data == "object" && !Array.isArray(data)) {
105
- let missing0;
106
- if ((data.engage === undefined) && (missing0 = "engage")) {
107
- validate20.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }];
108
- return false;
109
- }
110
- else {
111
- if (data.engage !== undefined) {
112
- let data0 = data.engage;
113
- const _errs1 = errors;
114
- {
115
- if (data0 && typeof data0 == "object" && !Array.isArray(data0)) {
116
- let missing1;
117
- if (((data0.ok === undefined) && (missing1 = "ok")) || ((data0.rtt_msec === undefined) && (missing1 = "rtt_msec"))) {
118
- validate20.errors = [{ instancePath: instancePath + "/engage", schemaPath: "#/properties/engage/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }];
119
- return false;
120
- }
121
- else {
122
- if (data0.ok !== undefined) {
123
- const _errs3 = errors;
124
- if (typeof data0.ok !== "boolean") {
125
- validate20.errors = [{ instancePath: instancePath + "/engage/ok", schemaPath: "#/properties/engage/properties/ok/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }];
126
- return false;
127
- }
128
- var valid1 = _errs3 === errors;
129
- }
130
- else {
131
- var valid1 = true;
132
- }
133
- if (valid1) {
134
- if (data0.rtt_msec !== undefined) {
135
- let data2 = data0.rtt_msec;
136
- const _errs5 = errors;
137
- if (!(((typeof data2 == "number") && (!(data2 % 1) && !isNaN(data2))) && (isFinite(data2)))) {
138
- validate20.errors = [{ instancePath: instancePath + "/engage/rtt_msec", schemaPath: "#/properties/engage/properties/rtt_msec/type", keyword: "type", params: { type: "integer" }, message: "must be integer" }];
139
- return false;
140
- }
141
- var valid1 = _errs5 === errors;
142
- }
143
- else {
144
- var valid1 = true;
145
- }
146
- }
147
- }
148
- }
149
- else {
150
- validate20.errors = [{ instancePath: instancePath + "/engage", schemaPath: "#/properties/engage/type", keyword: "type", params: { type: "object" }, message: "must be object" }];
151
- return false;
152
- }
153
- }
154
- var valid0 = _errs1 === errors;
155
- }
156
- else {
157
- var valid0 = true;
158
- }
159
- if (valid0) {
160
- if (data["2PhW"] !== undefined) {
161
- const _errs7 = errors;
162
- if ("2" !== data["2PhW"]) {
163
- validate20.errors = [{ instancePath: instancePath + "/2PhW", schemaPath: "definitions#/definitions/2PhW/const", keyword: "const", params: { allowedValue: "2" }, message: "must be equal to constant" }];
164
- return false;
165
- }
166
- var valid0 = _errs7 === errors;
167
- }
168
- else {
169
- var valid0 = true;
170
- }
171
- }
172
- }
173
- }
174
- else {
175
- validate20.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }];
176
- return false;
177
- }
178
- } validate20.errors = vErrors; return errors === 0; }
179
- validate20.evaluated = { "props": { "engage": true, "2PhW": true }, "dynamicProps": false, "dynamicItems": false };
180
-
181
- // https://stackoverflow.com/questions/4602141/variable-name-as-a-string-in-javascript
182
- // console.log('OUT', __name({variableName}) );
183
- //-------------------------------------------------------------------------------------------------
184
- function l_length_(obj_labels) {
185
- if (!obj_labels || typeof obj_labels !== 'object')
186
- throw new Error('obj_labels must be an object');
187
- const obj_1label = Object.values(obj_labels);
188
- if (!obj_1label.every(v => typeof v === 'number' && Number.isFinite(v)))
189
- throw new Error('All values must be finite numbers');
190
- const labels = Object.values(obj_labels);
191
- if (labels.length === 0)
192
- return 1; // Empty object case, start at 1
193
- const value_max = Math.max(...labels);
194
- if (value_max <= 0)
195
- return 1;
196
- const bit_highest = Math.floor(Math.log2(value_max));
197
- return 1 << (bit_highest + 1);
198
- }
199
- function l_array_(arr_labels, start = 1) {
200
- if (!Array.isArray(arr_labels))
201
- throw new Error('arr_labels must be an array');
202
- if (!Number.isSafeInteger(start) || start < 0)
203
- throw new Error('start must be a safe, non-negative integer');
204
- return Object.freeze(arr_labels.reduce((acc, key, index) => {
205
- acc[key] = start << index;
206
- return acc;
207
- }, {}));
208
- }
209
- function l_concat_(obj_labels, arg) {
210
- if (!obj_labels || typeof obj_labels !== 'object')
211
- throw new Error('obj_labels must be an object');
212
- const obj_1label = Object.values(obj_labels);
213
- if (!obj_1label.every(v => typeof v === 'number' && Number.isFinite(v)))
214
- throw new Error('All values must be finite numbers');
215
- if (!arg || (typeof arg !== 'object' && !Array.isArray(arg)))
216
- throw new Error('arg must be an object or array');
217
- if (Array.isArray(arg)) {
218
- const len = l_length_(obj_labels);
219
- const arr_labels_new = l_array_(arg, len);
220
- return l_concat_(obj_labels, arr_labels_new);
221
- }
222
- const next_pos = l_length_(obj_labels);
223
- const arg_entries = Object.entries(arg);
224
- const result = Object.create(null);
225
- Object.entries(obj_labels).forEach(([k, v]) => {
226
- if (k !== '__proto__' && k !== 'constructor')
227
- result[k] = v;
228
- });
229
- let min_arg = Infinity;
230
- for (const [, value] of arg_entries) {
231
- if (typeof value !== 'number' || !Number.isFinite(value))
232
- continue; // Skip non-numeric
233
- if (value > 0 && value < min_arg)
234
- min_arg = value;
235
- }
236
- // Shift only if min_arg is less than next_pos
237
- const shift = min_arg === Infinity || min_arg >= next_pos
238
- ? 0
239
- : Math.floor(Math.log2(next_pos / min_arg));
240
- for (const [key, value] of arg_entries) {
241
- if (!(key in result)) {
242
- result[key] = value === 0 ? 0 : value << shift;
243
- }
244
- }
245
- return Object.freeze(result);
246
- }
247
- function l_merge_(obj_labels1, obj_labels2) {
248
- if (!obj_labels1 || typeof obj_labels1 !== 'object')
249
- throw new Error('obj_labels must be an object');
250
- const obj_1label1 = Object.values(obj_labels1);
251
- if (!obj_1label1.every(v => typeof v === 'number' && Number.isFinite(v)))
252
- throw new Error('All values must be finite numbers');
253
- if (!obj_labels2 || typeof obj_labels2 !== 'object')
254
- throw new Error('obj_labels must be an object');
255
- const obj_1label2 = Object.values(obj_labels2);
256
- if (!obj_1label2.every(v => typeof v === 'number' && Number.isFinite(v)))
257
- throw new Error('All values must be finite numbers');
258
- const result = Object.create(null);
259
- Object.entries(obj_labels1).forEach(([k, v]) => {
260
- if (k !== '__proto__' && k !== 'constructor')
261
- result[k] = v;
262
- });
263
- const set_values = new Set(Object.values(obj_labels1)); // Track all used bit values
264
- // Find the highest bit position to start shifting from if needed
265
- const value_highest = Math.max(0, ...Array.from(set_values));
266
- let next_shift = value_highest ? Math.floor(Math.log2(value_highest)) + 1 : 0;
267
- // Process second set
268
- for (const [key, value] of Object.entries(obj_labels2)) {
269
- if (key in result) {
270
- // Same key: Values must match
271
- if (result[key] !== value) {
272
- throw new Error(`Key '${key}' has conflicting values: ${result[key]} (obj_labels1) vs ${value} (obj_labels2)`);
273
- }
274
- // No action needed if values match, already in result
275
- }
276
- else {
277
- let maxIterations = 1000;
278
- // New key: Add if value is unique, otherwise shift
279
- let value_new = value;
280
- while (set_values.has(value_new) && maxIterations--) {
281
- value_new = 1 << next_shift++;
282
- }
283
- if (maxIterations <= 0)
284
- throw new Error('Too many collisions in l_merge_');
285
- result[key] = value_new;
286
- set_values.add(value_new);
287
- }
288
- }
289
- return Object.freeze(result);
290
- }
291
- function l_LL_(obj, x) {
292
- if (!obj || typeof obj !== 'object')
293
- throw new Error('obj must be an object');
294
- if (!Number.isSafeInteger(x) || x < 0)
295
- throw new Error('Shift value must be a safe, non-negative integer');
296
- const obj_new = {};
297
- for (const [k, v] of Object.entries(obj)) {
298
- if (typeof v !== 'number' || !Number.isFinite(v))
299
- continue; // Skip non-numeric
300
- obj_new[k] = v << x;
301
- }
302
- return Object.freeze(obj_new);
303
- }
304
- function l_RR_(obj, x) {
305
- if (!obj || typeof obj !== 'object')
306
- throw new Error('obj must be an object');
307
- if (!Number.isSafeInteger(x) || x < 0)
308
- throw new Error('Shift value must be a safe, non-negative integer');
309
- const obj_new = {};
310
- for (const [k, v] of Object.entries(obj)) {
311
- if (typeof v !== 'number' || !Number.isFinite(v))
312
- continue; // Skip non-numeric
313
- obj_new[k] = v >> x;
314
- }
315
- return Object.freeze(obj_new);
316
- }
317
- function l_assert_(actual, required) {
318
- if (!actual || typeof actual !== 'object')
319
- return false;
320
- if (!required || typeof required !== 'object')
321
- return false;
322
- const actualEntries = Object.entries(actual);
323
- const requiredEntries = Object.entries(required);
324
- // if (actualEntries.length === 0 && expectedEntries.length > 0)
325
- // return false;
326
- const actualValues = new Set();
327
- for (const [, v] of actualEntries) {
328
- if (typeof v !== 'number' || !Number.isFinite(v))
329
- return false;
330
- actualValues.add(v);
331
- }
332
- const usedRequiredValues = new Set();
333
- for (const [k, v] of requiredEntries) {
334
- if (typeof v !== 'number' || !Number.isFinite(v))
335
- return false;
336
- if (k in actual) {
337
- if (actual[k] !== v)
338
- return false;
339
- }
340
- else {
341
- if (!actualValues.has(v))
342
- return false;
343
- }
344
- if (usedRequiredValues.has(v))
345
- return false;
346
- usedRequiredValues.add(v);
347
- }
348
- return true;
349
- }
350
- //-------------------------------------------------------------------------------------------------
351
- function handler_default_( /* ... */) {
352
- // https://stackoverflow.com/questions/18746440/passing-multiple-arguments-to-console-log
353
- var args = Array.prototype.slice.call(arguments);
354
- console.log.apply(console, args);
355
- }
356
- function l_toBigInt_(obj_labels, obj, ignore = false) {
357
- if (!obj_labels || typeof obj_labels !== 'object')
358
- throw new Error('obj_labels must be an object');
359
- if (!obj || typeof obj !== 'object')
360
- throw new Error('obj must be an object');
361
- let bigint_l = BigInt(0);
362
- for (const [k, v] of Object.entries(obj)) {
363
- if ((ignore || v) && obj_labels[k] !== undefined && typeof obj_labels[k] === 'number')
364
- bigint_l |= BigInt(obj_labels[k]);
365
- // console.log('0b'+ bigInt.toString(2) );
366
- }
367
- return bigint_l;
368
- }
369
- function lRef(initial) {
370
- if (arguments.length === 0 || initial === undefined) {
371
- return undefined;
372
- }
373
- let value = initial;
374
- return {
375
- get: () => value,
376
- set: (newVal) => { value = newVal; }
377
- };
378
- }
379
- /*
380
- const l_ = {
381
- get VALIDATION() { return logr_.lref.get().VALIDATION; }
382
- }
383
-
384
- function createBitFlags(ref) {
385
- // Create a proxy so that any property access computes the current bit
386
- return new Proxy({}, {
387
- get(target, prop, receiver) {
388
- const positions = ref.get(); // get current { VALIDATION: n, ... }
389
- const position = positions[prop]; // e.g., positions['VALIDATION']
390
-
391
- if (position === undefined) {
392
- // Optional: warn or return 0 for unknown keys
393
- console.warn(`Unknown bitflag key: ${String(prop)}`);
394
- return 0;
395
- }
396
-
397
- return 0b1 << position; // or 1 << position
398
- },
399
-
400
- // Optional: make Object.keys(l_) show the actual keys
401
- ownKeys(target) {
402
- return Object.keys(ref.get());
403
- },
404
-
405
- getOwnPropertyDescriptor(target, prop) {
406
- return {
407
- enumerable: true,
408
- configurable: true,
409
- };
410
- }
411
- });
412
- }
413
-
414
- type BitPositions = Record<string, number>;
415
-
416
- function createBitFlags<T extends BitPositions>(ref: { get: () => T }) {
417
- return new Proxy({} as { [K in keyof T]: number }, {
418
- get(target, prop: string | symbol) {
419
- if (typeof prop !== 'string') return undefined;
420
- const positions = ref.get();
421
- const position = positions[prop as keyof T];
422
- if (position === undefined) return 0;
423
- return 1 << position;
424
- },
425
- ownKeys() {
426
- return Object.keys(ref.get());
427
- },
428
- getOwnPropertyDescriptor() {
429
- return { enumerable: true, configurable: true };
430
- }
431
- });
432
- }
433
- */
434
- function create_Referenced_l_(ref) {
435
- return new Proxy({}, {
436
- get(target, prop) {
437
- if (typeof prop !== 'string')
438
- return undefined;
439
- // if (prop === 'get') {
440
- // return () => {
441
- // const positions = ref.get();
442
- // const result: Partial<Record<keyof T, number>> = {};
443
- // for (const key in positions) {
444
- // result[key as keyof T] = positions[key];
445
- // }
446
- // return result as Record<keyof T, number>;
447
- // };
448
- // }
449
- if (prop === 'get')
450
- return () => ref.get();
451
- const positions = ref.get();
452
- const value = positions[prop];
453
- if (value === undefined)
454
- return 0;
455
- return value;
456
- },
457
- ownKeys() {
458
- return Object.keys(ref.get());
459
- },
460
- getOwnPropertyDescriptor() {
461
- return { enumerable: true, configurable: true };
462
- }
463
- });
464
- }
465
- const LOGR = (function () {
466
- let _instance; // Private variable to hold the single instance
467
- // Module-level state would work - but only when the module is loaded once.
468
- // Your bundler is currently bundling @knev/bitlogr into your distribution file,
469
- // creating a second copy. The Global Symbol approach would work around this,
470
- // but it's treating the symptom, not the cause.
471
- const GLOBAL_KEY = Symbol.for('@knev/bitlogr/LOGR');
472
- // The real issue is your build configuration bundling dependencies that should remain external.
473
- // rollup.config.mjs: external: ['@knev/bitlogr', 'uuid'], // Don't bundle these
474
- function _create_instance() {
475
- const _id = Math.random();
476
- if (globalThis.LOGR_ENABLED ?? true)
477
- console.log('creating LOGR instance:', _id);
478
- // Private state (replacing constructor properties)
479
- let _Bint_toggled = BigInt(0);
480
- let _handler_log = handler_default_;
481
- function _log_fxn(nr_logged, argsFn /* args */) {
482
- // console.log('_log_fxn: ', BigInt(nr_logged), _Bint_toggled, (BigInt(nr_logged) & _Bint_toggled));
483
- if ((BigInt(nr_logged) & _Bint_toggled) === BigInt(0))
484
- return;
485
- const args = argsFn();
486
- _handler_log.apply(this, args);
487
- }
488
- return {
489
- _id, // for testing
490
- get handler() { return _handler_log; },
491
- set handler(fx) {
492
- _handler_log = fx;
493
- },
494
- get toggled() { return _Bint_toggled; },
495
- // toggle(obj_labels, obj_toggled) {
496
- // _Bint_toggled= l_toBigInt_(obj_labels, obj_toggled);
497
- // },
498
- toggle(labels, obj_toggled) {
499
- const obj_labels = typeof labels?.get === 'function'
500
- ? labels.get()
501
- : labels;
502
- // console.log('obj_labels', obj_labels)
503
- _Bint_toggled = l_toBigInt_(obj_labels, obj_toggled);
504
- },
505
- // Core internal log function (exposed only to created loggers)
506
- _log_fxn,
507
- create(options = {}) {
508
- // This constant will be replaced at build time
509
- if (!(globalThis.LOGR_ENABLED ?? true)) {
510
- return {
511
- _obj_labels: undefined, // optional: keep shape compatible if needed
512
- log: () => { }, // does nothing
513
- raw: () => { }, // does nothing
514
- };
515
- }
516
- const _logger = {
517
- // _lref_labels: (options.arr_labels === undefined) ? undefined : lRef( l_array_(options.arr_labels) ),
518
- _lref_labels: (options.labels === undefined)
519
- ? undefined
520
- : lRef(options.labels),
521
- get l() {
522
- // Always create a fresh proxy pointing to the current labels
523
- return create_Referenced_l_({
524
- get: () => this._lref_labels?.get() || {}
525
- });
526
- },
527
- get lref() { return this._lref_labels; },
528
- set lref(lref_labels_new) {
529
- this._lref_labels = lref_labels_new;
530
- },
531
- log(nr_logged, argsFn) {
532
- // This constant will be replaced at build time
533
- if (!(globalThis.LOGR_ENABLED ?? true))
534
- return;
535
- _log_fxn.call(this, nr_logged, argsFn);
536
- },
537
- // Optional shorthand for common cases
538
- raw(...args) {
539
- _handler_log.apply(this, args);
540
- }
541
- };
542
- return _logger;
543
- },
544
- };
545
- }
546
- // Public interface
547
- return {
548
- get_instance() {
549
- if (!(globalThis.LOGR_USE_GLOBAL_KEY ?? true)) {
550
- if (!_instance)
551
- _instance = _create_instance(); // Lazy initialization
552
- return _instance;
553
- }
554
- if (!globalThis[GLOBAL_KEY])
555
- globalThis[GLOBAL_KEY] = _create_instance();
556
- return globalThis[GLOBAL_KEY];
557
- },
558
- // For testing only - reset the singleton
559
- _reset_for_testing() {
560
- delete globalThis[GLOBAL_KEY];
561
- }
562
- };
563
- })();
564
-
565
- var logr_es = /*#__PURE__*/Object.freeze({
566
- __proto__: null,
567
- LOGR: LOGR,
568
- _create_Referenced_l: create_Referenced_l_,
569
- lRef: lRef,
570
- l_LL: l_LL_,
571
- l_RR: l_RR_,
572
- l_array: l_array_,
573
- l_assert: l_assert_,
574
- l_concat: l_concat_,
575
- l_length: l_length_,
576
- l_merge: l_merge_
577
- });
578
-
579
- function getAugmentedNamespace(n) {
580
- if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
581
- var f = n.default;
582
- if (typeof f == "function") {
583
- var a = function a () {
584
- var isInstance = false;
585
- try {
586
- isInstance = this instanceof a;
587
- } catch {}
588
- if (isInstance) {
589
- return Reflect.construct(f, arguments, this.constructor);
590
- }
591
- return f.apply(this, arguments);
592
- };
593
- a.prototype = f.prototype;
594
- } else a = {};
595
- Object.defineProperty(a, '__esModule', {value: true});
596
- Object.keys(n).forEach(function (k) {
597
- var d = Object.getOwnPropertyDescriptor(n, k);
598
- Object.defineProperty(a, k, d.get ? d : {
599
- enumerable: true,
600
- get: function () {
601
- return n[k];
602
- }
603
- });
604
- });
605
- return a;
606
- }
607
-
608
- var jsonMsg_cjs = {};
609
-
610
- var require$$0 = /*@__PURE__*/getAugmentedNamespace(logr_es);
611
-
612
- var hasRequiredJsonMsg_cjs;
613
-
614
- function requireJsonMsg_cjs () {
615
- if (hasRequiredJsonMsg_cjs) return jsonMsg_cjs;
616
- hasRequiredJsonMsg_cjs = 1;
617
-
618
- var bitlogr = require$$0;
619
-
620
- const schema_Msg = validate18;
621
- function validate18(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { let vErrors = null; let errors = 0; const evaluated0 = validate18.evaluated; if (evaluated0.dynamicProps) {
622
- evaluated0.props = undefined;
623
- } if (evaluated0.dynamicItems) {
624
- evaluated0.items = undefined;
625
- } {
626
- if (data && typeof data == "object" && !Array.isArray(data)) {
627
- let missing0;
628
- if ((((data.id === undefined) && (missing0 = "id")) || ((data.referer === undefined) && (missing0 = "referer"))) || ((data.dt === undefined) && (missing0 = "dt"))) {
629
- validate18.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }];
630
- return false;
631
- }
632
- else {
633
- if (data.id !== undefined) {
634
- const _errs1 = errors;
635
- if (typeof data.id !== "string") {
636
- validate18.errors = [{ instancePath: instancePath + "/id", schemaPath: "#/properties/id/type", keyword: "type", params: { type: "string" }, message: "must be string" }];
637
- return false;
638
- }
639
- var valid0 = _errs1 === errors;
640
- }
641
- else {
642
- var valid0 = true;
643
- }
644
- if (valid0) {
645
- if (data.dt !== undefined) {
646
- const _errs3 = errors;
647
- if (typeof data.dt !== "string") {
648
- validate18.errors = [{ instancePath: instancePath + "/dt", schemaPath: "#/properties/dt/type", keyword: "type", params: { type: "string" }, message: "must be string" }];
649
- return false;
650
- }
651
- var valid0 = _errs3 === errors;
652
- }
653
- else {
654
- var valid0 = true;
655
- }
656
- }
657
- }
658
- }
659
- else {
660
- validate18.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }];
661
- return false;
662
- }
663
- } validate18.errors = vErrors; return errors === 0; }
664
- validate18.evaluated = { "props": { "id": true, "dt": true }, "dynamicProps": false, "dynamicItems": false };
665
- const schema_MsgEffect = validate19;
666
- function validate19(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { let vErrors = null; let errors = 0; const evaluated0 = validate19.evaluated; if (evaluated0.dynamicProps) {
667
- evaluated0.props = undefined;
668
- } if (evaluated0.dynamicItems) {
669
- evaluated0.items = undefined;
670
- } {
671
- if (data && typeof data == "object" && !Array.isArray(data)) {
672
- let missing0;
673
- if ((data._cause === undefined) && (missing0 = "_cause")) {
674
- validate19.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }];
675
- return false;
676
- }
677
- }
678
- else {
679
- validate19.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }];
680
- return false;
681
- }
682
- } validate19.errors = vErrors; return errors === 0; }
683
- validate19.evaluated = { "dynamicProps": false, "dynamicItems": false };
684
- const schema_MsgAckEffect = validate20;
685
- function validate20(data, { instancePath = "", parentData, parentDataProperty, rootData = data, dynamicAnchors = {} } = {}) { let vErrors = null; let errors = 0; const evaluated0 = validate20.evaluated; if (evaluated0.dynamicProps) {
686
- evaluated0.props = undefined;
687
- } if (evaluated0.dynamicItems) {
688
- evaluated0.items = undefined;
689
- } {
690
- if (data && typeof data == "object" && !Array.isArray(data)) {
691
- let missing0;
692
- if ((data.ack === undefined) && (missing0 = "ack")) {
693
- validate20.errors = [{ instancePath, schemaPath: "#/required", keyword: "required", params: { missingProperty: missing0 }, message: "must have required property '" + missing0 + "'" }];
694
- return false;
695
- }
696
- else {
697
- if (data.ack !== undefined) {
698
- let data0 = data.ack;
699
- {
700
- if (data0 && typeof data0 == "object" && !Array.isArray(data0)) {
701
- let missing1;
702
- if ((data0.ok === undefined) && (missing1 = "ok")) {
703
- validate20.errors = [{ instancePath: instancePath + "/ack", schemaPath: "#/properties/ack/required", keyword: "required", params: { missingProperty: missing1 }, message: "must have required property '" + missing1 + "'" }];
704
- return false;
705
- }
706
- else {
707
- if (data0.ok !== undefined) {
708
- if (typeof data0.ok !== "boolean") {
709
- validate20.errors = [{ instancePath: instancePath + "/ack/ok", schemaPath: "#/properties/ack/properties/ok/type", keyword: "type", params: { type: "boolean" }, message: "must be boolean" }];
710
- return false;
711
- }
712
- }
713
- }
714
- }
715
- else {
716
- validate20.errors = [{ instancePath: instancePath + "/ack", schemaPath: "#/properties/ack/type", keyword: "type", params: { type: "object" }, message: "must be object" }];
717
- return false;
718
- }
719
- }
720
- }
721
- }
722
- }
723
- else {
724
- validate20.errors = [{ instancePath, schemaPath: "#/type", keyword: "type", params: { type: "object" }, message: "must be object" }];
725
- return false;
726
- }
727
- } validate20.errors = vErrors; return errors === 0; }
728
- validate20.evaluated = { "props": { "ack": true }, "dynamicProps": false, "dynamicItems": false };
729
-
730
- const byteToHex = [];
731
- for (let i = 0; i < 256; ++i) {
732
- byteToHex.push((i + 0x100).toString(16).slice(1));
733
- }
734
- function unsafeStringify(arr, offset = 0) {
735
- return (byteToHex[arr[offset + 0]] +
736
- byteToHex[arr[offset + 1]] +
737
- byteToHex[arr[offset + 2]] +
738
- byteToHex[arr[offset + 3]] +
739
- '-' +
740
- byteToHex[arr[offset + 4]] +
741
- byteToHex[arr[offset + 5]] +
742
- '-' +
743
- byteToHex[arr[offset + 6]] +
744
- byteToHex[arr[offset + 7]] +
745
- '-' +
746
- byteToHex[arr[offset + 8]] +
747
- byteToHex[arr[offset + 9]] +
748
- '-' +
749
- byteToHex[arr[offset + 10]] +
750
- byteToHex[arr[offset + 11]] +
751
- byteToHex[arr[offset + 12]] +
752
- byteToHex[arr[offset + 13]] +
753
- byteToHex[arr[offset + 14]] +
754
- byteToHex[arr[offset + 15]]).toLowerCase();
755
- }
756
-
757
- let getRandomValues;
758
- const rnds8 = new Uint8Array(16);
759
- function rng() {
760
- if (!getRandomValues) {
761
- if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
762
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
763
- }
764
- getRandomValues = crypto.getRandomValues.bind(crypto);
765
- }
766
- return getRandomValues(rnds8);
767
- }
768
-
769
- const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
770
- var native = { randomUUID };
771
-
772
- function _v4(options, buf, offset) {
773
- options = options || {};
774
- const rnds = options.random ?? options.rng?.() ?? rng();
775
- if (rnds.length < 16) {
776
- throw new Error('Random bytes length must be >= 16');
777
- }
778
- rnds[6] = (rnds[6] & 0x0f) | 0x40;
779
- rnds[8] = (rnds[8] & 0x3f) | 0x80;
780
- return unsafeStringify(rnds);
781
- }
782
- function v4(options, buf, offset) {
783
- if (native.randomUUID && true && !options) {
784
- return native.randomUUID();
785
- }
786
- return _v4(options);
787
- }
788
-
789
- //-------------------------------------------------------------------------------------------------
790
- const LOGR_ = bitlogr.LOGR.get_instance();
791
- const logr_ = LOGR_.create({ labels: bitlogr.l_array(['VALIDATION']) });
792
- const l_ = logr_.l;
793
- // console.log('File location:', import.meta.url, '[Implementation]');
794
- //-------------------------------------------------------------------------------------------------
795
- // TODO: use RFC3339 "timestamp"? https://ajv.js.org/json-type-definition.html
796
- // "module" pattern to avoid "static" and "#" private : https://stackoverflow.com/a/1479341/298545
797
- var JSON_Msg = (function () {
798
- return {
799
- merge: function (json) {
800
- return Object.assign({
801
- id: v4(),
802
- referer: null,
803
- dt: new Date().toISOString()
804
- }, json || {});
805
- },
806
- validate: function (json) {
807
- const b_valid = schema_Msg(json);
808
- if (!b_valid)
809
- logr_.log(l_.VALIDATION, () => ['JSON_Msg: validate: ', schema_Msg.errors]);
810
- return b_valid;
811
- },
812
- // TODO: requires a separate ajv module require, and JTD specific schema
813
- // https://ajv.js.org/guide/getting-started.html#parsing-and-serializing-json
814
- // static #ajv_parse_= ajv.compileParser(this.#schema_json_Msg);
815
- // static parse(json) {
816
- // return this.#ajv_parse_(json);
817
- // }
818
- };
819
- })();
820
- var JSON_MsgEffect = (function () {
821
- return {
822
- create_with_cause_merge: function (msg_cause, json) {
823
- const _cause = msg_cause;
824
- return Object.assign(JSON_Msg.merge(json), { _cause });
825
- },
826
- validate: function (json) {
827
- if (!JSON_Msg.validate(json))
828
- return false;
829
- const b_valid = schema_MsgEffect(json);
830
- if (!b_valid)
831
- logr_.log(l_.VALIDATION, () => ['JSON_MsgEffect: validate: ', schema_MsgEffect.errors]);
832
- return b_valid;
833
- }
834
- };
835
- })();
836
- var JSON_MsgAck = (function () {
837
- return {
838
- create_with_cause_Ok: function (msg_cause, b_ok = true) {
839
- return JSON_MsgEffect.create_with_cause_merge(msg_cause, {
840
- ack: {
841
- "ok": b_ok,
842
- },
843
- });
844
- },
845
- create_with_cause_Expired: function (msg_cause) {
846
- return JSON_MsgEffect.create_with_cause_merge(msg_cause, {
847
- ack: {
848
- "ok": false,
849
- "expired": true
850
- },
851
- });
852
- },
853
- validate: function (json) {
854
- if (!JSON_MsgEffect.validate(json))
855
- return false;
856
- const b_valid = schema_MsgAckEffect(json);
857
- if (!b_valid)
858
- logr_.log(l_.VALIDATION, () => ['JSON_MsgAckEffect: validate: ', schema_MsgAckEffect.errors]);
859
- return b_valid;
860
- }
861
- };
862
- })();
863
-
864
- jsonMsg_cjs.JSON_Msg = JSON_Msg;
865
- jsonMsg_cjs.JSON_MsgAck = JSON_MsgAck;
866
- jsonMsg_cjs.JSON_MsgEffect = JSON_MsgEffect;
867
- jsonMsg_cjs.logr = logr_;
868
- return jsonMsg_cjs;
869
- }
870
-
871
- var jsonMsg_cjsExports = requireJsonMsg_cjs();
872
-
6
+ // The wire interface (validators, constructors, VERSION) is GENERATED by iface-gen from schema_TwoPhW.json
7
+ // -- in the HOST's project, never here. This package has no interface and no schema of its own: the host
8
+ // hands its generated interface to protocol_TwoPhW() (at the bottom of this file), which is what binds
9
+ // the two. So the package and the host cannot disagree about the wire, the version included.
10
+ // import { v4 as uuidv4 } from 'uuid'; // uuid is already a dep of JSON_Msg, so why not
873
11
  // interface Event extends Required<EventMinimal> {
874
12
  // type : string;
875
13
  // id : string | number;
876
14
  // timeout_id : NodeJS.Timeout | null;
877
15
  // };
878
- const k_TTL = 20000;
879
16
  //-------------------------------------------------------------------------------------------------
880
- const obj_labels_merge_ = l_merge_(logr.lref.get(), jsonMsg_cjsExports.logr.lref.get()); // VALIDATION : 4
881
- const obj_labels_concat_ = l_concat_(obj_labels_merge_, l_array_(['HANDLERS', 'DROPS', 'PROTOCOL_STATE', 'RECVER', 'SENDER']));
17
+ const obj_labels_merge_ = l_merge(logr.lref.get(), logr$1.lref.get()); // VALIDATION : 4
18
+ const obj_labels_concat_ = l_concat(obj_labels_merge_, l_array(['HANDLERS', 'DROPS', 'PROTOCOL_STATE', 'RECVER', 'SENDER']));
882
19
  const lref_ = lRef(obj_labels_concat_);
883
- jsonMsg_cjsExports.logr.lref = lref_;
20
+ logr$1.lref = lref_;
884
21
  logr.lref = lref_;
885
22
  const LOGR_ = LOGR.get_instance();
886
23
  const logr_ = LOGR_.create(); // don't let create() make a new ref, assign lref_ from here
887
24
  logr_.lref = lref_;
888
25
  const l_ = logr_.l;
889
26
  class Config {
890
- _callback_msgWarp;
891
- _callback_msgEngage;
892
- _callback_msgAckWarp;
893
- _callback_msgAckEngage;
894
- _callback_msg_sent_expired;
895
- _callback_msgOptions;
27
+ // A step's callback is what makes the step this participant's to handle: with no callback set,
28
+ // the step's handler refuses it (returns false) before anything is logged. Every participant on
29
+ // the ME hears every exchange, so "no callback" is the normal case for a role it does not play.
30
+ _callback_msgWarp = null;
31
+ _callback_effEngage = null;
32
+ _callback_ackWarp = null;
33
+ _callback_ackEngage = null;
34
+ // Optional, and not what makes a hold ours (that is the sender role, _callback_ackWarp): a hold
35
+ // moves the Warp's expiry whether or not anybody wants to be told about it.
36
+ _callback_holdWarp = null;
37
+ // "a step I sent was never answered inside its window", one per role: the sender's fires for its
38
+ // Warp / Engage, the receiver's for its AckWarp. A participant playing both roles keeps both.
39
+ _callback_sender_sent_expired;
40
+ _callback_receiver_sent_expired;
896
41
  constructor() {
897
- // Initialize callbacks as no-op functions
898
- this._callback_msgWarp = (_msg, _json_msg) => {
899
- console.assert(false, 'callback_msgWarp uninitialized');
900
- return false;
901
- };
902
- this._callback_msgEngage = (_msg, _json_msg) => {
903
- console.assert(false, 'callback_msgEngage uninitialized');
904
- return false;
905
- };
906
- this._callback_msgAckWarp = (_msg, _json_msg) => {
907
- console.assert(false, 'callback_msgAckWarp uninitialized');
908
- return false;
42
+ this._callback_sender_sent_expired = (_msg, _json_msg) => {
43
+ console.assert(false, '_callback_sender_sent_expired uninitialized');
909
44
  };
910
- this._callback_msgAckEngage = (_msg, _json_msg) => {
911
- console.assert(false, 'callback_msgAckEngage uninitialized');
912
- return false;
913
- };
914
- this._callback_msg_sent_expired = (_msg, _json_msg) => {
915
- console.assert(false, '_callback_msg_sent_expired uninitialized');
916
- };
917
- this._callback_msgOptions = () => {
918
- console.assert(false, 'callback_msgOptions uninitialized');
45
+ this._callback_receiver_sent_expired = (_msg, _json_msg) => {
46
+ console.assert(false, '_callback_receiver_sent_expired uninitialized');
919
47
  };
920
48
  }
921
- receiver(callback_msgWarp, callback_msgEngage, callback_msg_sent_expired) {
49
+ receiver(callback_msgWarp, callback_effEngage, callback_msg_sent_expired) {
922
50
  this._callback_msgWarp = callback_msgWarp;
923
- this._callback_msgEngage = callback_msgEngage;
924
- this._callback_msg_sent_expired = callback_msg_sent_expired;
925
- }
926
- sender(callback_msgAckWarp, callback_msgAckEngage, callback_msg_sent_expired) {
927
- this._callback_msgAckWarp = callback_msgAckWarp;
928
- this._callback_msgAckEngage = callback_msgAckEngage;
929
- this._callback_msg_sent_expired = callback_msg_sent_expired;
51
+ this._callback_effEngage = callback_effEngage;
52
+ this._callback_receiver_sent_expired = callback_msg_sent_expired;
930
53
  }
931
- set callback_msgOptions(callback) {
932
- this._callback_msgOptions = callback;
54
+ // callback_holdWarp: the receiver says it is working on our Warp (what it waits for, how far it is)
55
+ sender(callback_ackWarp, callback_ackEngage, callback_msg_sent_expired, callback_holdWarp = null) {
56
+ this._callback_ackWarp = callback_ackWarp;
57
+ this._callback_ackEngage = callback_ackEngage;
58
+ this._callback_sender_sent_expired = callback_msg_sent_expired;
59
+ this._callback_holdWarp = callback_holdWarp;
933
60
  }
934
61
  }
935
62
  // var config = (function() {
@@ -944,148 +71,31 @@ class Config {
944
71
  // }
945
72
  // })();
946
73
  //-------------------------------------------------------------------------------------------------
947
- let k_VERSION = "2";
948
- // rtt_msec <= ttl_msec *2 => rtt_msec = ttl_msec *2
949
- // t_ttl_rtt_(TTL, RTT) = t_ttl_rtt_(TTL, TTL *2) = TTL *2 + TTL *2 = TTL *4 MAX
950
- function time_ttl_rtt_(ttl_msec, rtt_msec) {
951
- if (ttl_msec === undefined)
952
- return undefined;
953
- if (rtt_msec === undefined)
954
- return ttl_msec * 2;
955
- console.assert(rtt_msec <= ttl_msec * 2, `t_ttl_rtt_: INVALID rtt_msec ttl_msec[${ttl_msec}] rtt_msec[${rtt_msec}]`);
956
- return (ttl_msec * 2) + rtt_msec;
74
+ // Timing. Every step is timed from the message it answers, by that message's own dt; no step looks further
75
+ // back than the message before it. Two durations:
76
+ // - TTL (warp.ttl_msec, set by the sender): the longest a message may take to travel ONE way. Network only.
77
+ // - the lease (hold.ttl_msec of a JSON_HoldWarp, set by the receiver): "my next word comes within this long".
78
+ // Work only.
79
+ // A message that hands the turn over (Warp, AckWarp, Engage) is answered within its dt + TTL*2, there and
80
+ // back. After a hold the next word is due within the hold's dt + its lease + TTL. Of several holds the one
81
+ // that ends latest counts; nothing is added up. The exchange as a whole has no limit: it stays open for as
82
+ // long as leases are renewed.
83
+ // the window in which a message that hands the turn over is answered: TTL there, TTL back
84
+ function window_msec_(nr_ttl_msec) {
85
+ return nr_ttl_msec * 2;
86
+ }
87
+ // Are these the same Warp? The identity of an exchange: the Warp's own dt, its warp.id and its sender.
88
+ function compare_msgWarp_(json_L, json_R) {
89
+ if (json_L.dt !== json_R.dt)
90
+ return false;
91
+ if (json_L.warp.id !== json_R.warp.id)
92
+ return false;
93
+ if (json_L.referer[0] !== json_R.referer[0])
94
+ return false;
95
+ if (json_L.referer[1] !== json_R.referer[1])
96
+ return false;
97
+ return true;
957
98
  }
958
- var JSON_MsgOptions = (function () {
959
- return {
960
- create_with_cause_options: function (msg_cause, options) {
961
- return jsonMsg_cjsExports.JSON_MsgEffect.create_with_msg_merge(msg_cause, {
962
- options: options,
963
- "2PhW": k_VERSION
964
- });
965
- },
966
- validate: function (json) {
967
- // if (! JSON_Msg_msg.validate(json))
968
- // return false;
969
- // if (! schema_MsgOptions_(json)) {
970
- // logr_.log(l_.VALIDATION, () => ['JSON_MsgOptions: schema_MsgOptions_: ', (schema_MsgOptions_ as any).errors])
971
- // return false;
972
- // }
973
- return true;
974
- }
975
- };
976
- })();
977
- var JSON_MsgWarp = (function () {
978
- return {
979
- create_with_id_user_hyperport: function (json_warp_id, json_user, json_hyperport, nr_ttl_msec) {
980
- return jsonMsg_cjsExports.JSON_Msg.merge({
981
- warp: {
982
- id: json_warp_id,
983
- user: json_user,
984
- hyperport: json_hyperport,
985
- ttl_msec: nr_ttl_msec
986
- },
987
- "2PhW": k_VERSION
988
- });
989
- },
990
- compare: function (json_L, json_R) {
991
- if (json_L.dt !== json_R.dt)
992
- return false;
993
- if (json_L.warp.id !== json_R.warp.id)
994
- return false;
995
- if (json_L.referer[0] !== json_R.referer[0])
996
- return false;
997
- if (json_L.referer[1] !== json_R.referer[1])
998
- return false;
999
- return true;
1000
- },
1001
- validate: function (json_msg) {
1002
- // if (! JSON_Msg.validate(json))
1003
- // return false;
1004
- if (!schema_MsgWarp(json_msg)) {
1005
- logr_.log(l_.VALIDATION, () => ['JSON_MsgWarp: schema_MsgWarp_: ', schema_MsgWarp.errors]);
1006
- return false;
1007
- }
1008
- return true;
1009
- }
1010
- };
1011
- })();
1012
- var JSON_MsgEngage = (function () {
1013
- return {
1014
- create_with_Warp: function (json_msgWarp) {
1015
- console.assert(json_msgWarp.ack === undefined, "Engage with a Warp, not an Ack");
1016
- return jsonMsg_cjsExports.JSON_MsgEffect.create_with_cause_merge(json_msgWarp, {
1017
- engage: {
1018
- "ok": true,
1019
- "rtt_msec": Date.now() - Date.parse(json_msgWarp.dt)
1020
- },
1021
- "2PhW": k_VERSION
1022
- });
1023
- },
1024
- validate: function (json_msgEffect) {
1025
- // if (! JSON_Msg_msg.validate(json))
1026
- // return false;
1027
- if (!JSON_MsgWarp.validate(json_msgEffect._cause))
1028
- return false;
1029
- if (!schema_MsgEngage(json_msgEffect)) {
1030
- logr_.log(l_.VALIDATION, () => ['JSON_MsgEngage: schema_MsgEngage_: ', schema_MsgEngage.errors]);
1031
- return false;
1032
- }
1033
- return true;
1034
- }
1035
- };
1036
- })();
1037
- var JSON_MsgAckWarp = (function () {
1038
- return {
1039
- // createWith_msgAck_msg : function(json_msgAck, _msg) {
1040
- // const json_msgAckWarp= structuredClone(json_msgAck);
1041
- // json_msgAckWarp._cause= _cause;
1042
- // return json_msgAckWarp;
1043
- // }
1044
- create_with_Warp_Ok: function (json_msgWarp, b_ok = true) {
1045
- const json_msgAck = jsonMsg_cjsExports.JSON_MsgAck.create_with_cause_Ok(json_msgWarp, b_ok);
1046
- json_msgAck["2PhW"] = k_VERSION;
1047
- return json_msgAck;
1048
- },
1049
- // create_with_msgExpired : function( json_msgWarp ) {
1050
- // const json_msgAck_msg= JSON_MsgAck_msg.create_with_msgExpired( json_msgWarp )
1051
- // json_msgAck_msg["2PhW"]= k_VERSION;
1052
- // return json_msgAck_msg;
1053
- // },
1054
- validate: function (json_msgAck) {
1055
- // if (! JSON_MsgAck_msg.validate(json))
1056
- // return false;
1057
- if (!JSON_MsgWarp.validate(json_msgAck._cause))
1058
- return false;
1059
- return true;
1060
- }
1061
- };
1062
- })();
1063
- var JSON_MsgAckEngage = (function () {
1064
- return {
1065
- // createWith_msgAck_msg : function(json_msgAck, _msg) {
1066
- // const json_msgAckEngage= structuredClone(json_msgAck);
1067
- // json_msgAckEngage._cause= _cause;
1068
- // return json_msgAckEngage;
1069
- // }
1070
- create_with_Engage_Ok: function (json_msgEngage, b_ok = true) {
1071
- const json_msgAck = jsonMsg_cjsExports.JSON_MsgAck.create_with_cause_Ok(json_msgEngage, b_ok);
1072
- json_msgAck["2PhW"] = k_VERSION;
1073
- return json_msgAck;
1074
- },
1075
- // create_with_msgExpired : function( json_msgEngage ) {
1076
- // const json_msgAck_msg= JSON_MsgAck_msg.create_with_msgExpired( json_msgEngage )
1077
- // json_msgAck_msg["2PhW"]= k_VERSION;
1078
- // return json_msgAck_msg;
1079
- // },
1080
- validate: function (json_msgAck) {
1081
- // if (! JSON_MsgAck_msg.validate(json_msgAck_msg))
1082
- // return false;
1083
- if (!JSON_MsgEngage.validate(json_msgAck._cause))
1084
- return false;
1085
- return true;
1086
- }
1087
- };
1088
- })();
1089
99
  //-------------------------------------------------------------------------------------------------
1090
100
  // States
1091
101
  class StateState {
@@ -1125,7 +135,7 @@ class StateState {
1125
135
  class StateAckEngage extends StateState {
1126
136
  constructor(idx_event, event) { super(idx_event, event); }
1127
137
  get evt_AckEngage() { return this.event; }
1128
- get json_msgAckEngage() { return this.json_msg; }
138
+ get json_ackEngage() { return this.json_msg; }
1129
139
  canChangeState(_state_new) {
1130
140
  return false;
1131
141
  }
@@ -1133,53 +143,80 @@ class StateAckEngage extends StateState {
1133
143
  class StateEngage extends StateState {
1134
144
  constructor(idx_event, event) { super(idx_event, event); }
1135
145
  get evt_Engage() { return this.event; }
1136
- get json_msgEngage() { return this.json_msg; }
146
+ get json_effEngage() { return this.json_msg; }
1137
147
  canChangeState(state_new) {
1138
148
  if (false === state_new instanceof StateAckEngage)
1139
149
  return false;
1140
- // The Engage gets to live for THE WARP'S creation time + TTL*2 + RTT
1141
- const json_msgWarp = this.json_msgEngage._cause;
1142
- const timeout_ms = time_ttl_rtt_(json_msgWarp.warp.ttl_msec, this.json_msgEngage.engage.rtt_msec);
1143
- logr_.log(l_.PROTOCOL_STATE, () => [`StateEngage: evt_AckEngage.dt@${state_new.evt_AckEngage.dt}, msgWarp.dt@${Date.parse(json_msgWarp.dt)} + ${timeout_ms}`]);
1144
- if (state_new.evt_AckEngage.dt >= Date.parse(json_msgWarp.dt) + timeout_ms)
150
+ // The AckEngage is accepted until THE ENGAGE'S creation time + TTL*2
151
+ const timeout_ms = window_msec_(this.json_effEngage._cause.warp.ttl_msec);
152
+ logr_.log(l_.PROTOCOL_STATE, () => [`StateEngage: evt_AckEngage.dt@${state_new.evt_AckEngage.dt}, effEngage.dt@${Date.parse(this.json_effEngage.dt)} + ${timeout_ms}`]);
153
+ if (state_new.evt_AckEngage.dt >= Date.parse(this.json_effEngage.dt) + timeout_ms)
1145
154
  return false;
1146
155
  return true;
1147
156
  }
1148
157
  }
158
+ // Can a JSON_EffEngage follow this JSON_AckWarp? Not after a nack (it ends the exchange), and not
159
+ // after the ack of an instantaneous warp (single phase: the ack concludes it).
160
+ function isEngageAwaited_(json_ackWarp) {
161
+ return !!json_ackWarp.ack.ok && !json_ackWarp._cause.warp.instantaneous;
162
+ }
1149
163
  class StateAckWarp extends StateState {
1150
164
  constructor(idx_event, event) { super(idx_event, event); }
1151
165
  get evt_AckWarp() { return this.event; }
1152
- get json_msgAckWarp() { return this.json_msg; }
166
+ get json_ackWarp() { return this.json_msg; }
1153
167
  canChangeState(state_new) {
1154
168
  if (false === state_new instanceof StateEngage)
1155
169
  return false;
1156
- if (!this.json_msgAckWarp.ack.ok)
1157
- return false;
1158
- if (this.json_msgAckWarp._cause.warp.instantaneous)
170
+ if (!isEngageAwaited_(this.json_ackWarp))
1159
171
  return false;
1160
- // The Ack gets to live for THE ACK'S creation time + TTL*2 + STT
1161
- // +STT, so lines up with the Engage timeout
1162
- // - Engage: T0 +2TTL +RTT; RTT= STT+STT
1163
- // - AckWarp: TAckWarp +2TLL +STT; TAckWarp= T0 +STT;
1164
- // - STT: Date of the Ack minus date of the Warp.
1165
- const timeout_ms = time_ttl_rtt_(this.json_msgAckWarp._cause.warp.ttl_msec) + Date.parse(this.json_msgAckWarp.dt) - Date.parse(this.json_msgAckWarp._cause.dt);
1166
- logr_.log(l_.PROTOCOL_STATE, () => [`StateAckWarp: evt_Engage.dt@${state_new.evt_Engage.dt}, msgAckWarp.dt@${Date.parse(this.json_msgAckWarp.dt)} + ${timeout_ms}`]);
1167
- if (state_new.evt_Engage.dt >= Date.parse(this.json_msgAckWarp.dt) + timeout_ms)
172
+ // The Engage is accepted until THE ACK'S creation time + TTL*2. Nothing of phase 1 enters it: how
173
+ // long the receiver took to acknowledge the Warp is not this phase's business.
174
+ const timeout_ms = window_msec_(this.json_ackWarp._cause.warp.ttl_msec);
175
+ logr_.log(l_.PROTOCOL_STATE, () => [`StateAckWarp: evt_Engage.dt@${state_new.evt_Engage.dt}, msgAckWarp.dt@${Date.parse(this.json_ackWarp.dt)} + ${timeout_ms}`]);
176
+ if (state_new.evt_Engage.dt >= Date.parse(this.json_ackWarp.dt) + timeout_ms)
1168
177
  return false;
1169
178
  return true;
1170
179
  }
1171
180
  }
1172
181
  class StateWarp extends StateState {
182
+ // where the latest lease of a JSON_HoldWarp moved the end of the window to (epoch msec), and the event
183
+ // whose timer now guards it. null: no hold moved it.
184
+ _nr_deadline_lease = null;
185
+ _idx_event_timer = null;
1173
186
  constructor(idx_event, event) { super(idx_event, event); }
1174
187
  get evt_Warp() { return this.event; }
1175
188
  get json_msgWarp() { return this.json_msg; }
189
+ // Where a JSON_HoldWarp puts the end of the window: its OWN dt + its lease (hold.ttl_msec) + the
190
+ // warp's TTL (one for the next message to travel). NaN when its dt does not read: a lease with no anchor.
191
+ static deadline_holdWarp(json_holdWarp) {
192
+ const nr_lease = JSON_Hold.lease_epoch_msec(json_holdWarp);
193
+ return (nr_lease === null) ? NaN : nr_lease + json_holdWarp._cause.warp.ttl_msec;
194
+ }
195
+ // The last instant the JSON_AckWarp is accepted: THE WARP'S creation time + TTL*2, or where a hold
196
+ // moved it, whichever is later. The latest counts; nothing is added up.
197
+ get deadline_msec() {
198
+ const nr_deadline = Date.parse(this.json_msgWarp.dt) + window_msec_(this.json_msgWarp.warp.ttl_msec);
199
+ return (this._nr_deadline_lease !== null && this._nr_deadline_lease > nr_deadline) ? this._nr_deadline_lease : nr_deadline;
200
+ }
201
+ // the event that holds this Warp's expiry timer: the Warp's own, or the hold that last moved the window
202
+ get idx_event_timer() {
203
+ return (this._idx_event_timer !== null) ? this._idx_event_timer : this.idx_event;
204
+ }
205
+ // A hold on this Warp, logged as event idx_event. Returns whether it moved the end of the window:
206
+ // not when its lease ends no later than the window in force, nor when its dt does not read.
207
+ lease(idx_event, json_holdWarp) {
208
+ const nr_deadline = StateWarp.deadline_holdWarp(json_holdWarp);
209
+ if (!(nr_deadline > this.deadline_msec))
210
+ return false;
211
+ this._nr_deadline_lease = nr_deadline;
212
+ this._idx_event_timer = idx_event;
213
+ return true;
214
+ }
1176
215
  canChangeState(state_new) {
1177
216
  if (false === state_new instanceof StateAckWarp)
1178
217
  return false;
1179
- // The Warp gets to live for THE WARP'S creation time + TTL*2
1180
- const timeout_ms = time_ttl_rtt_(this.json_msgWarp.warp.ttl_msec);
1181
- logr_.log(l_.PROTOCOL_STATE, () => [`StateWarp: evt_AckWarp.dt@${state_new.evt_AckWarp.dt}, msgWarp.dt@${Date.parse(this.json_msgWarp.dt)} + ${timeout_ms}`]);
1182
- if (state_new.evt_AckWarp.dt >= Date.parse(this.json_msgWarp.dt) + timeout_ms)
218
+ logr_.log(l_.PROTOCOL_STATE, () => [`StateWarp: evt_AckWarp.dt@${state_new.evt_AckWarp.dt}, deadline@${this.deadline_msec}`]);
219
+ if (state_new.evt_AckWarp.dt >= this.deadline_msec)
1183
220
  return false;
1184
221
  return true;
1185
222
  }
@@ -1223,10 +260,23 @@ class ProtocolStateState {
1223
260
  return this._state;
1224
261
  }
1225
262
  canChangeState(state_new) {
263
+ // Every window is measured from a message's own dt, and the schema only asks dt to be a string.
264
+ // A step whose dt does not read as a time has no window to be inside of: never legal. (Unchecked,
265
+ // it parses to NaN, every "is it past the deadline?" answers no, and it escapes all the windows.)
266
+ // Every logged step passed here, so the states can rely on the dt of the messages they wrap.
267
+ if (!Number.isFinite(Date.parse(state_new.json_msg.dt)))
268
+ return false;
269
+ // An exchange is a dialogue: a step we RECEIVE is only legal after a step we SENT, and vice
270
+ // versa. Every participant on the ME hears every exchange, so without this a warp we merely
271
+ // heard would be "answered" by the ack its real receiver sent, and we could answer our own step.
272
+ if (!(this._state instanceof StateInitialState) && this._state.event.data.b_sent === state_new.event.data.b_sent)
273
+ return false;
1226
274
  return this._state.canChangeState(state_new);
1227
275
  }
1228
276
  }
1229
277
  //-------------------------------------------------------------------------------------------------
278
+ const kstr_EVT_DROPPED_ = '2PhW[DROPPED!]';
279
+ const kstr_EVT_HOLDWARP_ = '2PhW[JSON_HoldWarp]';
1230
280
  class TwoPhW_EventLog {
1231
281
  _eventLog;
1232
282
  constructor(eventLog) {
@@ -1234,32 +284,35 @@ class TwoPhW_EventLog {
1234
284
  }
1235
285
  _warp(json_msg) {
1236
286
  const b_Ack = json_msg.ack !== undefined;
1237
- const json = b_Ack ? json_msg["_cause"] : json_msg;
287
+ const b_Hold = !b_Ack && json_msg.hold !== undefined; // a message that carries both is an ack
288
+ const json = (b_Ack || b_Hold) ? json_msg["_cause"] : json_msg;
1238
289
  if (json.warp) {
1239
290
  return {
1240
- str_type: `2PhW[JSON_Msg${b_Ack ? 'Ack' : ''}Warp]`,
291
+ str_type: b_Ack ? '2PhW[JSON_AckWarp]' : (b_Hold ? kstr_EVT_HOLDWARP_ : '2PhW[JSON_MsgWarp]'),
1241
292
  json_msgWarp: json
1242
293
  };
1243
294
  }
1244
295
  if (json.engage) {
1245
296
  return {
1246
- str_type: `2PhW[JSON_Msg${b_Ack ? 'Ack' : ''}Engage]`,
297
+ str_type: b_Ack ? '2PhW[JSON_AckEngage]' : '2PhW[JSON_EffEngage]',
1247
298
  json_msgWarp: json["_cause"]
1248
299
  };
1249
300
  }
1250
301
  return { str_type: null, json_msgWarp: null }; // Explicit default for invalid cases
1251
302
  }
1252
303
  // _addEvent(msg: t_msg, json_msg : JSON_Msg, timeout_ms? : number, timeout_callback? : ( args? : {idx_event : number, event : EventMinimal} ) => {}) {
1253
- _addEvent(msg, json_msg, timeout_ms, timeout_callback) {
304
+ _addEvent(msg, json_msg, b_sent, timeout_ms, timeout_callback) {
1254
305
  const { str_type, json_msgWarp } = this._warp(json_msg);
1255
- const { idx } = this._eventLog.add_Event(str_type, json_msgWarp.warp.id, { msg, json_msg }, timeout_ms, timeout_callback);
306
+ const { idx } = this._eventLog.add_Event(str_type, json_msgWarp.warp.id, { msg, json_msg, b_sent }, timeout_ms, timeout_callback);
1256
307
  logr_.log(l_.PROTOCOL_STATE, () => [`_addEvent: [${idx}] timeout:${Date.now()}+${timeout_ms} `, json_msg]);
1257
308
  }
1258
- _dropEvent(json_msg) {
309
+ // Record a message we refused, for forensics: under its exchange and in the shape of every other
310
+ // 2PhW event, but never a step -- traverse_State skips it.
311
+ _dropEvent(msg, json_msg) {
1259
312
  const { json_msgWarp } = this._warp(json_msg);
1260
313
  if (!json_msgWarp)
1261
314
  return;
1262
- this._eventLog.add_Event('2PhW[DROPPED!]', json_msgWarp.warp.id, json_msg);
315
+ this._eventLog.add_Event(kstr_EVT_DROPPED_, json_msgWarp.warp.id, { msg, json_msg, b_sent: false });
1263
316
  }
1264
317
  _cancelTimeout(idx_event) {
1265
318
  logr_.log(l_.PROTOCOL_STATE, () => [`_cancelTimeout: [${idx_event}] timeout cancelled`]);
@@ -1267,25 +320,39 @@ class TwoPhW_EventLog {
1267
320
  }
1268
321
  traverse_State(json_msgWarp) {
1269
322
  const protocolState = new ProtocolStateState();
1270
- const arr_evts = this._eventLog.get_Events_by_id(json_msgWarp.warp.id, k_TTL);
323
+ // Look back over the WHOLE exchange: to the Warp's own dt (+ TTL*2: a participant logs by its own
324
+ // clock). An exchange has no limit as a whole (holds keep it open for as long as they are renewed), so
325
+ // its age says nothing; whether it is still open is decided by its windows. A Warp whose dt does not
326
+ // read has no exchange to look back over, and is refused by every caller.
327
+ const nr_age_msec = Date.now() - Date.parse(json_msgWarp.dt);
328
+ const lookback_ms = window_msec_(json_msgWarp.warp.ttl_msec) + (Number.isFinite(nr_age_msec) ? Math.max(nr_age_msec, 0) : 0);
329
+ const arr_evts = this._eventLog.get_Events_by_id(json_msgWarp.warp.id, lookback_ms);
1271
330
  logr_.log(l_.EVENTS, () => ['traverse_State: arr_evts: ', arr_evts]);
1272
- //TODO: what is the right TTL? should it be a constant or calculated
1273
331
  for (let i = arr_evts.length - 1; i >= 0; i--) {
1274
332
  const { idx, evt } = arr_evts[i];
333
+ // a dropped message is not a step: not of this exchange, and it must not poison it either
334
+ // (it may well belong to ANOTHER exchange that reused the warp id -- that is why it was dropped)
335
+ if (evt.type === kstr_EVT_DROPPED_)
336
+ continue;
1275
337
  const json_msg = evt.data.json_msg;
1276
- if (!JSON_MsgWarp.compare(json_msgWarp, this._warp(json_msg).json_msgWarp))
338
+ if (!compare_msgWarp_(json_msgWarp, this._warp(json_msg).json_msgWarp))
1277
339
  protocolState.state.changeState(new StateINVALID(idx, evt));
1278
340
  switch (evt.type) {
1279
341
  case '2PhW[JSON_MsgWarp]':
1280
342
  protocolState.state.changeState(new StateWarp(idx, evt));
1281
343
  break;
1282
- case '2PhW[JSON_MsgAckWarp]':
344
+ case kstr_EVT_HOLDWARP_:
345
+ // not a step: it changes no state, it moves the window of the Warp it is about
346
+ if (protocolState.state instanceof StateWarp)
347
+ protocolState.state.lease(idx, json_msg);
348
+ break;
349
+ case '2PhW[JSON_AckWarp]':
1283
350
  protocolState.state.changeState(new StateAckWarp(idx, evt));
1284
351
  break;
1285
- case '2PhW[JSON_MsgEngage]':
352
+ case '2PhW[JSON_EffEngage]':
1286
353
  protocolState.state.changeState(new StateEngage(idx, evt));
1287
354
  break;
1288
- case '2PhW[JSON_MsgAckEngage]':
355
+ case '2PhW[JSON_AckEngage]':
1289
356
  protocolState.state.changeState(new StateAckEngage(idx, evt));
1290
357
  break;
1291
358
  }
@@ -1312,36 +379,9 @@ class TwoPhW {
1312
379
  return this._2PhW_eventLog;
1313
380
  }
1314
381
  //-------------------------------------------------------------------------------------------------
1315
- _handler_msgOptions(cfg, msg, json_msgOptions) {
1316
- logr_.log(l_.HANDLERS, () => ['handler_msgOptions_: ...']);
1317
- /*
1318
- if (! validate_Options_delay_(json_msgOptions.options))
1319
- return false;
1320
-
1321
- if (JSON_MsgWarp.validate(json_msgOptions._cause)) {
1322
- const json_msgWarp= json_msgOptions._cause;
1323
-
1324
- const ctx= get_ctx(json_msgWarp.id);
1325
- if (!ctx )
1326
- return false;
1327
-
1328
- const ttl_msec= json_msgOptions.options.ttl_msec_incr[0];
1329
- const ttl_incr= json_msgOptions.options.ttl_msec_incr[1];
1330
-
1331
- //TODO: double check ttl_msec is the same as current accummulated ttl for idempotence.
1332
-
1333
- logr_.log(l_.HANDLERS, () => ['handler_msgOptions_: ', json_msgOptions]);
1334
-
1335
- ctx.protocol.delayTimeout(ttl_incr);
1336
-
1337
- if (cfg._callback_msgOptions)
1338
- return cfg._callback_msgOptions(msg, json_msgOptions);
1339
-
1340
- return true;
1341
- }
1342
- */
1343
- return false;
1344
- }
382
+ // The typed handlers (handler_json_<message>) are what the responder's base dispatch calls AFTER it
383
+ // validated the message as that type (generated: `JSON_AckWarp.validate(json_ack) &&
384
+ // this.handler_json_ackWarp(msg, json_ack)`). They do not validate again.
1345
385
  //-------------------------------------------------------------------------------------------------
1346
386
  // sender Source (src)
1347
387
  register_msgWarp(msg, json_msgWarp) {
@@ -1349,160 +389,275 @@ class TwoPhW {
1349
389
  const protocolState = this.eventLog.traverse_State(json_msgWarp);
1350
390
  const b_changeState = protocolState.canChangeState(new StateWarp(null, {
1351
391
  dt: Date.now(),
1352
- data: { msg, json_msg: json_msgWarp }
392
+ data: { msg, json_msg: json_msgWarp, b_sent: true }
1353
393
  }));
1354
394
  logr_.log(l_.HANDLERS | l_.SENDER, () => ['register_msgWarp: protocolState.canChangeState ', b_changeState]);
1355
395
  if (!b_changeState)
1356
396
  return false;
1357
- const timeout_ms = time_ttl_rtt_(json_msgWarp.warp.ttl_msec);
397
+ // the first answer, a hold or the ack, is due within the Warp's dt + TTL*2
398
+ const timeout_ms = window_msec_(json_msgWarp.warp.ttl_msec);
1358
399
  const elapsed_ms = Date.now() - Date.parse(json_msgWarp.dt);
1359
- this.eventLog._addEvent(msg, json_msgWarp, timeout_ms - elapsed_ms, () => {
1360
- this.config._callback_msg_sent_expired(msg, json_msgWarp);
400
+ this.eventLog._addEvent(msg, json_msgWarp, true, timeout_ms - elapsed_ms, () => {
401
+ this.config._callback_sender_sent_expired(msg, json_msgWarp);
1361
402
  });
403
+ return true;
1362
404
  }
1363
- _handler_msgAckWarp(msg, json_msgAckWarp) {
1364
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckWarp: ', json_msgAckWarp]);
1365
- const json_msgWarp = json_msgAckWarp._cause;
405
+ handler_json_ackWarp(msg, json_ackWarp) {
406
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_json_ackWarp: ', json_ackWarp]);
407
+ // no callback for this step: not ours -- before anything is logged
408
+ if (!this.config._callback_ackWarp)
409
+ return false;
410
+ const json_msgWarp = json_ackWarp._cause;
1366
411
  const protocolState = this.eventLog.traverse_State(json_msgWarp);
1367
412
  const b_changeState = protocolState.canChangeState(new StateAckWarp(null, {
1368
413
  dt: Date.now(),
1369
- data: { msg, json_msg: json_msgAckWarp }
414
+ data: { msg, json_msg: json_ackWarp, b_sent: false }
1370
415
  }));
1371
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckWarp: protocolState.canChangeState ', b_changeState]);
416
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_json_ackWarp: protocolState.canChangeState ', b_changeState]);
1372
417
  if (!b_changeState)
1373
418
  return false;
1374
- this.eventLog._cancelTimeout(protocolState.state.idx_event);
1375
- this.eventLog._addEvent(msg, json_msgAckWarp);
1376
- return this.config._callback_msgAckWarp(msg, json_msgAckWarp);
419
+ // the Warp's own timer, or the one of the hold that last moved its window
420
+ this.eventLog._cancelTimeout(protocolState.state.idx_event_timer);
421
+ this.eventLog._addEvent(msg, json_ackWarp, false);
422
+ return this.config._callback_ackWarp(msg, json_ackWarp);
423
+ }
424
+ // The receiver says it is working on a Warp we sent and has not decided yet (JSON_HoldWarp). Not a step:
425
+ // the exchange stays where it is, waiting for the JSON_AckWarp. What changes is how long we wait for it:
426
+ // the expiry of the Warp moves to the end of the hold's lease.
427
+ handler_json_holdWarp(msg, json_holdWarp) {
428
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_json_holdWarp: ', json_holdWarp]);
429
+ // the sender role is not played here: not ours -- before anything is logged
430
+ if (!this.config._callback_ackWarp)
431
+ return false;
432
+ const json_msgWarp = json_holdWarp._cause;
433
+ // ours iff it is about a Warp WE sent that is still unanswered and still inside its window. Anything
434
+ // else (a Warp we only heard, one already acknowledged or expired) is somebody else's, or too late.
435
+ const state = this.eventLog.traverse_State(json_msgWarp).state;
436
+ if (!(state instanceof StateWarp) || !state.event.data.b_sent)
437
+ return false;
438
+ const nr_now = Date.now();
439
+ if (nr_now >= state.deadline_msec)
440
+ return false;
441
+ const nr_deadline = StateWarp.deadline_holdWarp(json_holdWarp);
442
+ if (!Number.isFinite(nr_deadline))
443
+ return false; // a dt that does not read: a lease with no anchor
444
+ if (nr_deadline > state.deadline_msec) {
445
+ // the timer follows the window: the one in force is cancelled, this hold carries the new one.
446
+ // What expires is still the Warp: "the step I sent was never answered".
447
+ const { msg: msg_Warp, json_msg: json_msgWarp_sent } = state.event.data;
448
+ this.eventLog._cancelTimeout(state.idx_event_timer);
449
+ this.eventLog._addEvent(msg, json_holdWarp, false, nr_deadline - nr_now, () => {
450
+ this.config._callback_sender_sent_expired(msg_Warp, json_msgWarp_sent);
451
+ });
452
+ }
453
+ else
454
+ this.eventLog._addEvent(msg, json_holdWarp, false); // ends inside the window in force: logged, nothing moves
455
+ return this.config._callback_holdWarp ? this.config._callback_holdWarp(msg, json_holdWarp) : true;
1377
456
  }
1378
- register_msgEngage(msg, json_msgEngage) {
1379
- logr_.log(l_.SENDER, () => ['register_msgEngage: ', json_msgEngage]);
1380
- const json_msgWarp = json_msgEngage._cause;
457
+ register_effEngage(msg, json_effEngage) {
458
+ logr_.log(l_.SENDER, () => ['register_effEngage: ', json_effEngage]);
459
+ const json_msgWarp = json_effEngage._cause;
1381
460
  const protocolState = this.eventLog.traverse_State(json_msgWarp);
1382
461
  const b_changeState = protocolState.canChangeState(new StateEngage(null, {
1383
462
  dt: Date.now(),
1384
- data: { msg, json_msg: json_msgEngage }
463
+ data: { msg, json_msg: json_effEngage, b_sent: true }
1385
464
  }));
1386
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['register_msgEngage: protocolState.canChangeState ', b_changeState]);
465
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['register_effEngage: protocolState.canChangeState ', b_changeState]);
1387
466
  if (!b_changeState)
1388
467
  return false;
1389
- const timeout_ms = time_ttl_rtt_(json_msgWarp.warp.ttl_msec, json_msgEngage.engage.rtt_msec);
1390
- const elapsed_ms = Date.now() - Date.parse(json_msgWarp.dt);
1391
- this.eventLog._addEvent(msg, json_msgEngage, timeout_ms - elapsed_ms, () => {
1392
- this.config._callback_msg_sent_expired(msg, json_msgEngage);
468
+ // the AckEngage is due within the Engage's own dt + TTL*2
469
+ const timeout_ms = window_msec_(json_msgWarp.warp.ttl_msec);
470
+ const elapsed_ms = Date.now() - Date.parse(json_effEngage.dt);
471
+ this.eventLog._addEvent(msg, json_effEngage, true, timeout_ms - elapsed_ms, () => {
472
+ this.config._callback_sender_sent_expired(msg, json_effEngage);
1393
473
  });
474
+ return true;
1394
475
  }
1395
- _handler_msgAckEngage(msg, json_msgAckEngage) {
1396
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckEngage: ', json_msgAckEngage]);
1397
- const json_msgWarp = json_msgAckEngage._cause._cause;
476
+ handler_json_ackEngage(msg, json_ackEngage) {
477
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_json_ackEngage: ', json_ackEngage]);
478
+ // no callback for this step: not ours -- before anything is logged
479
+ if (!this.config._callback_ackEngage)
480
+ return false;
481
+ const json_msgWarp = json_ackEngage._cause._cause;
1398
482
  const protocolState = this.eventLog.traverse_State(json_msgWarp);
1399
483
  const b_changeState = protocolState.canChangeState(new StateAckEngage(null, {
1400
484
  dt: Date.now(),
1401
- data: { msg, json_msg: json_msgAckEngage }
485
+ data: { msg, json_msg: json_ackEngage, b_sent: false }
1402
486
  }));
1403
- logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_msgAckEngage_: protocolState.canChangeState ', b_changeState]);
487
+ logr_.log(l_.HANDLERS | l_.SENDER, () => ['handler_json_ackEngage: protocolState.canChangeState ', b_changeState]);
1404
488
  if (!b_changeState)
1405
489
  return false;
1406
490
  this.eventLog._cancelTimeout(protocolState.state.idx_event);
1407
- this.eventLog._addEvent(msg, json_msgAckEngage);
1408
- return this.config._callback_msgAckEngage(msg, json_msgAckEngage);
491
+ this.eventLog._addEvent(msg, json_ackEngage, false);
492
+ return this.config._callback_ackEngage(msg, json_ackEngage);
1409
493
  }
1410
494
  //-------------------------------------------------------------------------------------------------
1411
495
  // receiver Destination (dst)
1412
- _handler_msgWarp(msg, json_msgWarp) {
1413
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_msgWarp: ', json_msgWarp]);
496
+ handler_json_msgWarp(msg, json_msgWarp) {
497
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_json_msgWarp: ', json_msgWarp]);
498
+ // no callback for this step: not ours -- before anything is logged
499
+ if (!this.config._callback_msgWarp)
500
+ return false;
1414
501
  const protocolState = this.eventLog.traverse_State(json_msgWarp);
1415
502
  const b_changeState = protocolState.canChangeState(new StateWarp(null, {
1416
503
  dt: Date.now(),
1417
- data: { msg, json_msg: json_msgWarp }
504
+ data: { msg, json_msg: json_msgWarp, b_sent: false }
1418
505
  }));
1419
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_msgWarp: protocolState.canChangeState: ', b_changeState]);
506
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_json_msgWarp: protocolState.canChangeState: ', b_changeState]);
1420
507
  if (!b_changeState)
1421
508
  return false;
1422
- this.eventLog._addEvent(msg, json_msgWarp);
509
+ this.eventLog._addEvent(msg, json_msgWarp, false);
1423
510
  return this.config._callback_msgWarp(msg, json_msgWarp);
1424
511
  }
1425
- register_msgAckWarp(msg, json_msgAckWarp) {
1426
- logr_.log(l_.RECVER, () => ['register_msgAckWarp: ', json_msgAckWarp]);
1427
- const json_msgWarp = json_msgAckWarp._cause;
512
+ // Register a JSON_HoldWarp we are about to publish: "this Warp is being worked on, wait for the ack until
513
+ // my lease ends". Legal only for a Warp we RECEIVED, have not answered, and whose window is still open
514
+ // (a window that has closed cannot be reopened). It is what lets register_ackWarp succeed later than the
515
+ // Warp's own dt + TTL*2. Returns true, or false when it is not legal now: then do not publish it.
516
+ register_holdWarp(msg, json_holdWarp) {
517
+ logr_.log(l_.RECVER, () => ['register_holdWarp: ', json_holdWarp]);
518
+ const json_msgWarp = json_holdWarp._cause;
519
+ const state = this.eventLog.traverse_State(json_msgWarp).state;
520
+ if (!(state instanceof StateWarp) || state.event.data.b_sent)
521
+ return false;
522
+ if (Date.now() >= state.deadline_msec)
523
+ return false;
524
+ if (!Number.isFinite(StateWarp.deadline_holdWarp(json_holdWarp)))
525
+ return false;
526
+ this.eventLog._addEvent(msg, json_holdWarp, true);
527
+ return true;
528
+ }
529
+ register_ackWarp(msg, json_ackWarp) {
530
+ logr_.log(l_.RECVER, () => ['register_ackWarp: ', json_ackWarp]);
531
+ const json_msgWarp = json_ackWarp._cause;
1428
532
  const protocolState = this.eventLog.traverse_State(json_msgWarp);
1429
533
  const b_changeState = protocolState.canChangeState(new StateAckWarp(null, {
1430
534
  dt: Date.now(),
1431
- data: { msg, json_msg: json_msgAckWarp }
535
+ data: { msg, json_msg: json_ackWarp, b_sent: true }
1432
536
  }));
1433
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['register_msgAckWarp: protocolState.canChangeState: ', b_changeState]);
537
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['register_ackWarp: protocolState.canChangeState: ', b_changeState]);
1434
538
  if (!b_changeState)
1435
539
  return false;
1436
- const elapsed_ms = Date.now() - Date.parse(json_msgAckWarp.dt);
1437
- const timeout_ms = time_ttl_rtt_(json_msgWarp.warp.ttl_msec) + Date.parse(json_msgAckWarp.dt) - Date.parse(json_msgWarp.dt);
1438
- this.eventLog._addEvent(msg, json_msgAckWarp, timeout_ms - elapsed_ms, () => {
1439
- this.config._callback_msg_sent_expired(msg, json_msgAckWarp);
540
+ // The expiry means "the Engage I was waiting for never came". An ack no Engage can follow
541
+ // concludes the exchange and awaits nothing: logged, with no timer.
542
+ if (!isEngageAwaited_(json_ackWarp)) {
543
+ this.eventLog._addEvent(msg, json_ackWarp, true);
544
+ return true;
545
+ }
546
+ // the Engage is due within the ack's own dt + TTL*2
547
+ const elapsed_ms = Date.now() - Date.parse(json_ackWarp.dt);
548
+ const timeout_ms = window_msec_(json_msgWarp.warp.ttl_msec);
549
+ this.eventLog._addEvent(msg, json_ackWarp, true, timeout_ms - elapsed_ms, () => {
550
+ this.config._callback_receiver_sent_expired(msg, json_ackWarp);
1440
551
  });
552
+ return true;
1441
553
  }
1442
- _handler_msgEngage(msg, json_msgEngage) {
1443
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_msgEngage: ', json_msgEngage]);
1444
- const json_msgWarp = json_msgEngage._cause;
554
+ handler_json_effEngage(msg, json_effEngage) {
555
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_json_effEngage: ', json_effEngage]);
556
+ // no callback for this step: not ours -- before anything is logged
557
+ if (!this.config._callback_effEngage)
558
+ return false;
559
+ const json_msgWarp = json_effEngage._cause;
1445
560
  const protocolState = this.eventLog.traverse_State(json_msgWarp);
1446
561
  const b_changeState = protocolState.canChangeState(new StateEngage(null, {
1447
562
  dt: Date.now(),
1448
- data: { msg, json_msg: json_msgEngage }
563
+ data: { msg, json_msg: json_effEngage, b_sent: false }
1449
564
  }));
1450
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_msgEngage: protocolState.canChangeState: ', b_changeState]);
565
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['handler_json_effEngage: protocolState.canChangeState: ', b_changeState]);
1451
566
  if (!b_changeState)
1452
567
  return false;
1453
568
  this.eventLog._cancelTimeout(protocolState.state.idx_event);
1454
- this.eventLog._addEvent(msg, json_msgEngage);
1455
- return this.config._callback_msgEngage(msg, json_msgEngage);
569
+ this.eventLog._addEvent(msg, json_effEngage, false);
570
+ return this.config._callback_effEngage(msg, json_effEngage);
1456
571
  }
1457
- register_msgAckEngage(msg, json_msgAckEngage) {
1458
- logr_.log(l_.RECVER, () => ['register_msgAckEngage: ', json_msgAckEngage]);
1459
- const json_msgWarp = json_msgAckEngage._cause._cause;
572
+ register_ackEngage(msg, json_ackEngage) {
573
+ logr_.log(l_.RECVER, () => ['register_ackEngage: ', json_ackEngage]);
574
+ const json_msgWarp = json_ackEngage._cause._cause;
1460
575
  const protocolState = this.eventLog.traverse_State(json_msgWarp);
1461
576
  const b_changeState = protocolState.canChangeState(new StateAckEngage(null, {
1462
577
  dt: Date.now(),
1463
- data: { msg, json_msg: json_msgAckEngage }
578
+ data: { msg, json_msg: json_ackEngage, b_sent: true }
1464
579
  }));
1465
- logr_.log(l_.HANDLERS | l_.RECVER, () => ['register_msgAckEngage: protocolState.canChangeState: ', b_changeState]);
580
+ logr_.log(l_.HANDLERS | l_.RECVER, () => ['register_ackEngage: protocolState.canChangeState: ', b_changeState]);
1466
581
  if (!b_changeState)
1467
582
  return false;
1468
- this.eventLog._addEvent(msg, json_msgAckEngage);
1469
- }
1470
- //-------------------------------------------------------------------------------------------------
1471
- handler_json_msgAck(msg, json_msgAck) {
1472
- logr_.log(l_.HANDLERS, () => ['TwoPhW: handler_json_msgAck: ', json_msgAck]);
1473
- if (JSON_MsgAckWarp.validate(json_msgAck) && this._handler_msgAckWarp(msg, json_msgAck))
1474
- return true;
1475
- if (JSON_MsgAckEngage.validate(json_msgAck) && this._handler_msgAckEngage(msg, json_msgAck))
1476
- return true;
1477
- return false;
1478
- }
1479
- handler_json_msgEffect(msg, json_msgEffect) {
1480
- logr_.log(l_.HANDLERS, () => ['TwoPhW: handler_json_msgEffect: ', json_msgEffect]);
1481
- // if (JSON_MsgAck.validate(json_msgEffect) && this.handler_json_msgAck(msg, json_msgEffect) )
1482
- // return true;
1483
- if (JSON_MsgEngage.validate(json_msgEffect) && this._handler_msgEngage(msg, json_msgEffect))
1484
- return true;
1485
- // if (JSON_MsgOptions.validate(json_msg) && this.handler_msgOptions_(this._config, msg, json_msg))
1486
- // return true;
1487
- return false;
1488
- }
1489
- handler_json_msg(msg, json_msg) {
1490
- logr_.log(l_.HANDLERS, () => ['TwoPhW: handler_json_msg: ', json_msg]);
1491
- if (JSON_MsgWarp.validate(json_msg) && this._handler_msgWarp(msg, json_msg))
1492
- return true;
1493
- // https://attacomsian.com/blog/javascript-iterate-objects
1494
- // Object.keys(json_msg).forEach((key, index) => {
1495
- // if (key == 'dt')
1496
- // return;
1497
- // if (key == 'referer')
1498
- // return;
1499
- // console.log(`${key}: ${json_msg[key]}`);
1500
- // });
1501
- return false;
583
+ this.eventLog._addEvent(msg, json_ackEngage, true);
584
+ return true;
1502
585
  }
1503
586
  }
587
+ // Bind the protocol to the HOST's generated interface. Called once, where the responder is set up:
588
+ //
589
+ // import * as iface_TwoPhW from '../generated/iface-TwoPhW';
590
+ // const { TwoPhW, JSON_MsgWarp, JSON_EffEngage, JSON_AckWarp, JSON_HoldWarp, JSON_AckEngage } = protocol_TwoPhW(iface_TwoPhW);
591
+ //
592
+ // Returns the state machine and, per message, the generated namespace (validate + merge /
593
+ // create_with_cause_merge; the validators are delta-only: the base is validated upstream, in the
594
+ // responder chain) extended with what the schema cannot express: the protocol's own constructors.
595
+ // Whatever is built through them carries the interface's own VERSION, so the package cannot speak
596
+ // another version of 2PhW than its host validates.
597
+ function protocol_TwoPhW(iface_TwoPhW) {
598
+ // What was handed in is the host's to get right: a wrong import (the module's default export, another
599
+ // interface) must fail here, where it is made, not as an undefined deep inside an exchange.
600
+ const arr_str_missing = [
601
+ ['VERSION', typeof iface_TwoPhW?.VERSION === 'string'],
602
+ ['JSON_MsgWarp.validate', typeof iface_TwoPhW?.JSON_MsgWarp?.validate === 'function'],
603
+ ['JSON_MsgWarp.merge', typeof iface_TwoPhW?.JSON_MsgWarp?.merge === 'function'],
604
+ ['JSON_AckWarp.validate', typeof iface_TwoPhW?.JSON_AckWarp?.validate === 'function'],
605
+ ['JSON_HoldWarp.validate', typeof iface_TwoPhW?.JSON_HoldWarp?.validate === 'function'],
606
+ ['JSON_HoldWarp.create_with_cause_ttl', typeof iface_TwoPhW?.JSON_HoldWarp?.create_with_cause_ttl === 'function'],
607
+ ['JSON_EffEngage.validate', typeof iface_TwoPhW?.JSON_EffEngage?.validate === 'function'],
608
+ ['JSON_EffEngage.create_with_cause_merge', typeof iface_TwoPhW?.JSON_EffEngage?.create_with_cause_merge === 'function'],
609
+ ['JSON_AckEngage.validate', typeof iface_TwoPhW?.JSON_AckEngage?.validate === 'function']
610
+ ].filter(([_str_member, b_present]) => !b_present).map(([str_member]) => str_member);
611
+ if (arr_str_missing.length)
612
+ throw new Error(`protocol_TwoPhW: not a generated 2PhW interface, it lacks: ${arr_str_missing.join(', ')}`);
613
+ const k_VERSION = iface_TwoPhW.VERSION;
614
+ const JSON_MsgWarp = {
615
+ ...iface_TwoPhW.JSON_MsgWarp,
616
+ create_with_id_user_hyperport: function (json_warp_id, json_user, json_hyperport, nr_ttl_msec) {
617
+ return iface_TwoPhW.JSON_MsgWarp.merge({
618
+ id: json_warp_id,
619
+ user: json_user,
620
+ hyperport: json_hyperport,
621
+ ttl_msec: nr_ttl_msec
622
+ });
623
+ },
624
+ compare: compare_msgWarp_
625
+ };
626
+ const JSON_EffEngage = {
627
+ ...iface_TwoPhW.JSON_EffEngage,
628
+ create_with_Warp: function (json_msgWarp) {
629
+ console.assert(json_msgWarp.ack === undefined, "Engage with a Warp, not an Ack");
630
+ return iface_TwoPhW.JSON_EffEngage.create_with_cause_merge(json_msgWarp, {
631
+ "ok": true
632
+ });
633
+ }
634
+ };
635
+ // iface-gen emits no constructor for a JSON_Ack: build the base ack, stamp the protocol marker
636
+ const JSON_AckWarp = {
637
+ ...iface_TwoPhW.JSON_AckWarp,
638
+ create_with_Warp_Ok: function (json_msgWarp, b_ok = true) {
639
+ const json_ack = JSON_Ack.create_with_cause_Ok(json_msgWarp, b_ok);
640
+ json_ack["2PhW"] = k_VERSION;
641
+ return json_ack;
642
+ }
643
+ };
644
+ const JSON_AckEngage = {
645
+ ...iface_TwoPhW.JSON_AckEngage,
646
+ create_with_Engage_Ok: function (json_effEngage, b_ok = true) {
647
+ const json_ack = JSON_Ack.create_with_cause_Ok(json_effEngage, b_ok);
648
+ json_ack["2PhW"] = k_VERSION;
649
+ return json_ack;
650
+ }
651
+ };
652
+ return {
653
+ TwoPhW,
654
+ VERSION: k_VERSION,
655
+ JSON_MsgWarp,
656
+ JSON_EffEngage,
657
+ JSON_AckWarp,
658
+ JSON_HoldWarp: iface_TwoPhW.JSON_HoldWarp, // as generated: its constructor is built from the lease already
659
+ JSON_AckEngage
660
+ };
661
+ }
1504
662
 
1505
- var JSON_Msg = jsonMsg_cjsExports.JSON_Msg;
1506
- var JSON_MsgAck = jsonMsg_cjsExports.JSON_MsgAck;
1507
- var JSON_MsgEffect = jsonMsg_cjsExports.JSON_MsgEffect;
1508
- export { JSON_Msg, JSON_MsgAck, JSON_MsgAckEngage, JSON_MsgAckWarp, JSON_MsgEffect, JSON_MsgEngage, JSON_MsgOptions, JSON_MsgWarp, StateAckEngage, StateAckWarp, StateEngage, StateINVALID, StateInitialState, StateWarp, TwoPhW, logr_ as logr, time_ttl_rtt_ as t_ttl_rtt };
663
+ export { StateAckEngage, StateAckWarp, StateEngage, StateINVALID, StateInitialState, StateWarp, logr_ as logr, protocol_TwoPhW, window_msec_ as window_msec };