hyoo_sync_client 0.0.604 → 0.0.606

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.
package/node.mjs CHANGED
@@ -30,10 +30,9 @@ $.$$ = $
30
30
 
31
31
  ;
32
32
  "use strict";
33
-
34
- ;
35
- "use strict";
36
- let $hyoo_sync_revision = "echo";
33
+ // namespace $ {
34
+ // $mol_report_bugsnag = '18acf016ed2a2a4cc4445daa9dd2dd3c'
35
+ // }
37
36
 
38
37
  ;
39
38
  "use strict";
@@ -51,6 +50,11 @@ var $;
51
50
  var $;
52
51
  (function ($) {
53
52
  const instances = new WeakSet();
53
+ /**
54
+ * Proxy that delegates all to lazy returned target.
55
+ *
56
+ * $mol_delegate( Array.prototype , ()=> fetch_array() )
57
+ */
54
58
  function $mol_delegate(proto, target) {
55
59
  const proxy = new Proxy(proto, {
56
60
  get: (_, field) => {
@@ -154,7 +158,7 @@ var $;
154
158
  var $;
155
159
  (function ($) {
156
160
  function $mol_fail_hidden(error) {
157
- throw error;
161
+ throw error; /// Use 'Never Pause Here' breakpoint in DevTools or simply blackbox this script
158
162
  }
159
163
  $.$mol_fail_hidden = $mol_fail_hidden;
160
164
  })($ || ($ = {}));
@@ -198,6 +202,16 @@ var $;
198
202
  "use strict";
199
203
  var $;
200
204
  (function ($) {
205
+ $.$mol_key_handle = Symbol.for('$mol_key_handle');
206
+ $.$mol_key_store = new WeakMap();
207
+ })($ || ($ = {}));
208
+
209
+ ;
210
+ "use strict";
211
+ var $;
212
+ (function ($) {
213
+ if (!Symbol.dispose)
214
+ Symbol.dispose = Symbol('Symbol.dispose');
201
215
  class $mol_object2 {
202
216
  static $ = $;
203
217
  [Symbol.toStringTag];
@@ -206,7 +220,7 @@ var $;
206
220
  if (this[$mol_ambient_ref])
207
221
  return this[$mol_ambient_ref];
208
222
  const owner = $mol_owning_get(this);
209
- return this[$mol_ambient_ref] = owner?.$ || $mol_object2.$;
223
+ return this[$mol_ambient_ref] = owner?.$ || this.constructor.$ || $mol_object2.$;
210
224
  }
211
225
  set $(next) {
212
226
  if (this[$mol_ambient_ref])
@@ -228,8 +242,17 @@ var $;
228
242
  static toJSON() {
229
243
  return this.toString();
230
244
  }
245
+ static [$mol_key_handle]() {
246
+ return this.toString();
247
+ }
231
248
  destructor() { }
232
249
  static destructor() { }
250
+ [Symbol.dispose]() {
251
+ this.destructor();
252
+ }
253
+ //[ Symbol.toPrimitive ]( hint: string ) {
254
+ // return hint === 'number' ? this.valueOf() : this.toString()
255
+ //}
233
256
  toString() {
234
257
  return this[Symbol.toStringTag] || this.constructor.name + '<>';
235
258
  }
@@ -239,107 +262,158 @@ var $;
239
262
 
240
263
  ;
241
264
  "use strict";
265
+ var $;
266
+ (function ($) {
267
+ let buf = new Uint8Array(2 ** 12); // 4KB Mem Page
268
+ /** Temporary buffer. Recursive usage isn't supported. */
269
+ function $mol_charset_buffer(size) {
270
+ if (buf.byteLength < size)
271
+ buf = new Uint8Array(size);
272
+ return buf;
273
+ }
274
+ $.$mol_charset_buffer = $mol_charset_buffer;
275
+ })($ || ($ = {}));
242
276
 
243
277
  ;
244
278
  "use strict";
245
279
  var $;
246
280
  (function ($) {
247
- function $mol_promise_like(val) {
248
- try {
249
- return val && typeof val === 'object' && 'then' in val && typeof val.then === 'function';
250
- }
251
- catch {
252
- return false;
281
+ function $mol_charset_encode(str) {
282
+ const buf = $mol_charset_buffer(str.length * 3);
283
+ return buf.slice(0, $mol_charset_encode_to(str, buf));
284
+ }
285
+ $.$mol_charset_encode = $mol_charset_encode;
286
+ function $mol_charset_encode_to(str, buf, from = 0) {
287
+ let pos = from;
288
+ for (let i = 0; i < str.length; i++) {
289
+ let code = str.charCodeAt(i);
290
+ if (code < 0x80) { // ASCII - 1 octet
291
+ buf[pos++] = code;
292
+ }
293
+ else if (code < 0x800) { // 2 octet
294
+ buf[pos++] = 0xc0 | (code >> 6);
295
+ buf[pos++] = 0x80 | (code & 0x3f);
296
+ }
297
+ else if (code < 0xd800 || code >= 0xe000) { // 3 octet
298
+ buf[pos++] = 0xe0 | (code >> 12);
299
+ buf[pos++] = 0x80 | ((code >> 6) & 0x3f);
300
+ buf[pos++] = 0x80 | (code & 0x3f);
301
+ }
302
+ else { // surrogate pair
303
+ const point = ((code - 0xd800) << 10) + str.charCodeAt(++i) + 0x2400;
304
+ buf[pos++] = 0xf0 | (point >> 18);
305
+ buf[pos++] = 0x80 | ((point >> 12) & 0x3f);
306
+ buf[pos++] = 0x80 | ((point >> 6) & 0x3f);
307
+ buf[pos++] = 0x80 | (point & 0x3f);
308
+ }
309
+ }
310
+ return pos - from;
311
+ }
312
+ $.$mol_charset_encode_to = $mol_charset_encode_to;
313
+ function $mol_charset_encode_size(str) {
314
+ let size = 0;
315
+ for (let i = 0; i < str.length; i++) {
316
+ let code = str.charCodeAt(i);
317
+ if (code < 0x80)
318
+ size += 1;
319
+ else if (code < 0x800)
320
+ size += 2;
321
+ else if (code < 0xd800 || code >= 0xe000)
322
+ size += 3;
323
+ else
324
+ size += 4;
253
325
  }
326
+ return size;
254
327
  }
255
- $.$mol_promise_like = $mol_promise_like;
328
+ $.$mol_charset_encode_size = $mol_charset_encode_size;
256
329
  })($ || ($ = {}));
257
330
 
258
331
  ;
259
332
  "use strict";
260
333
  var $;
261
334
  (function ($) {
262
- const catched = new WeakMap();
263
- function $mol_fail_catch(error) {
264
- if (typeof error !== 'object')
265
- return false;
266
- if ($mol_promise_like(error))
267
- $mol_fail_hidden(error);
268
- if (catched.get(error))
269
- return false;
270
- catched.set(error, true);
271
- return true;
335
+ function $mol_int62_string_ensure(str) {
336
+ if (typeof str !== 'string')
337
+ return null;
338
+ return $mol_int62_from_string(str) && str;
272
339
  }
273
- $.$mol_fail_catch = $mol_fail_catch;
340
+ $.$mol_int62_string_ensure = $mol_int62_string_ensure;
341
+ $.$mol_int62_max = (2 ** 30) - 1;
342
+ $.$mol_int62_min = -(2 ** 30);
343
+ $.$mol_int62_range = $.$mol_int62_max - $.$mol_int62_min + 1;
344
+ function $mol_int62_to_string({ lo, hi }) {
345
+ lo = (lo + $.$mol_int62_range) % $.$mol_int62_range;
346
+ hi = (hi + $.$mol_int62_range) % $.$mol_int62_range;
347
+ return lo.toString(36) + '_' + hi.toString(36);
348
+ }
349
+ $.$mol_int62_to_string = $mol_int62_to_string;
350
+ function $mol_int62_from_string(str) {
351
+ const [str_lo, str_hi] = str.split('_');
352
+ const int_lo = parseInt(str_lo, 36);
353
+ const int_hi = parseInt(str_hi, 36);
354
+ if (int_lo.toString(36) !== str_lo || int_hi.toString(36) !== str_hi) {
355
+ return null;
356
+ }
357
+ return {
358
+ lo: (int_lo - $.$mol_int62_min) % $.$mol_int62_range + $.$mol_int62_min,
359
+ hi: (int_hi - $.$mol_int62_min) % $.$mol_int62_range + $.$mol_int62_min,
360
+ };
361
+ }
362
+ $.$mol_int62_from_string = $mol_int62_from_string;
363
+ function $mol_int62_compare(left_lo, left_hi, right_lo, right_hi) {
364
+ return (right_hi - left_hi) || (right_lo - left_lo);
365
+ }
366
+ $.$mol_int62_compare = $mol_int62_compare;
367
+ function $mol_int62_inc(lo, hi, max = $.$mol_int62_max) {
368
+ if (lo === max) {
369
+ return { lo: -max, hi: hi + 1 };
370
+ }
371
+ else {
372
+ return { lo: lo + 1, hi };
373
+ }
374
+ }
375
+ $.$mol_int62_inc = $mol_int62_inc;
376
+ function $mol_int62_random() {
377
+ return {
378
+ lo: Math.floor(Math.random() * $.$mol_int62_range + $.$mol_int62_min),
379
+ hi: Math.floor(Math.random() * $.$mol_int62_range + $.$mol_int62_min),
380
+ };
381
+ }
382
+ $.$mol_int62_random = $mol_int62_random;
383
+ function $mol_int62_hash_string(str) {
384
+ return $mol_int62_to_string($mol_int62_hash_buffer($mol_charset_encode(str)));
385
+ }
386
+ $.$mol_int62_hash_string = $mol_int62_hash_string;
387
+ function $mol_int62_hash_buffer(buf, seed = { lo: 0, hi: 0 }) {
388
+ let h1 = 0xdeadbeef ^ seed.lo;
389
+ let h2 = 0x41c6ce57 ^ seed.hi;
390
+ for (const byte of buf) {
391
+ h1 = Math.imul(h1 ^ byte, 2654435761);
392
+ h2 = Math.imul(h2 ^ byte, 1597334677);
393
+ }
394
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
395
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
396
+ return { lo: h1 << 1 >> 1, hi: h2 << 1 >> 1 };
397
+ }
398
+ $.$mol_int62_hash_buffer = $mol_int62_hash_buffer;
274
399
  })($ || ($ = {}));
275
400
 
401
+ ;
402
+ "use strict";
403
+
276
404
  ;
277
405
  "use strict";
278
406
  var $;
279
407
  (function ($) {
280
- function $mol_fail_log(error) {
281
- if ($mol_promise_like(error))
282
- return false;
283
- if (!$mol_fail_catch(error))
284
- return false;
285
- console.error(error);
286
- return true;
408
+ function $mol_data_setup(value, config) {
409
+ return Object.assign(value, {
410
+ config,
411
+ Value: null
412
+ });
287
413
  }
288
- $.$mol_fail_log = $mol_fail_log;
414
+ $.$mol_data_setup = $mol_data_setup;
289
415
  })($ || ($ = {}));
290
416
 
291
- ;
292
- "use strict";
293
- var $node = new Proxy({ require }, {
294
- get(target, name, wrapper) {
295
- if (target[name])
296
- return target[name];
297
- if (name.startsWith('node:'))
298
- return target.require(name);
299
- if (name[0] === '.')
300
- return target.require(name);
301
- const mod = target.require('module');
302
- if (mod.builtinModules.indexOf(name) >= 0)
303
- return target.require(name);
304
- try {
305
- target.require.resolve(name);
306
- }
307
- catch {
308
- const $$ = $;
309
- $$.$mol_exec('.', 'npm', 'install', '--omit=dev', name);
310
- try {
311
- $$.$mol_exec('.', 'npm', 'install', '--omit=dev', '@types/' + name);
312
- }
313
- catch (e) {
314
- if ($$.$mol_fail_catch(e)) {
315
- $$.$mol_fail_log(e);
316
- }
317
- }
318
- }
319
- try {
320
- return target.require(name);
321
- }
322
- catch (error) {
323
- if ($.$mol_fail_catch(error) && error.code === 'ERR_REQUIRE_ESM') {
324
- const module = cache.get(name);
325
- if (module)
326
- return module;
327
- throw import(name).then(module => cache.set(name, module));
328
- }
329
- $.$mol_fail_log(error);
330
- return null;
331
- }
332
- },
333
- set(target, name, value) {
334
- target[name] = value;
335
- return true;
336
- },
337
- });
338
- const cache = new Map();
339
- require = (req => Object.assign(function require(name) {
340
- return $node[name];
341
- }, req))(require);
342
-
343
417
  ;
344
418
  "use strict";
345
419
  var $;
@@ -367,11 +441,12 @@ var $;
367
441
  get: () => stack_get() + '\n' + [
368
442
  this.cause ?? 'no cause',
369
443
  ...this.errors.flatMap(e => [
370
- e.stack,
444
+ String(e.stack),
371
445
  ...e instanceof $mol_error_mix || !e.cause ? [] : [e.cause]
372
446
  ])
373
447
  ].map(frame_normalize).join('\n')
374
448
  });
449
+ // в nodejs, что б не дублировалось cause в консоли
375
450
  Object.defineProperty(this, 'cause', {
376
451
  get: () => cause
377
452
  });
@@ -389,6 +464,169 @@ var $;
389
464
  $.$mol_error_mix = $mol_error_mix;
390
465
  })($ || ($ = {}));
391
466
 
467
+ ;
468
+ "use strict";
469
+ var $;
470
+ (function ($) {
471
+ class $mol_data_error extends $mol_error_mix {
472
+ }
473
+ $.$mol_data_error = $mol_data_error;
474
+ })($ || ($ = {}));
475
+
476
+ ;
477
+ "use strict";
478
+ var $;
479
+ (function ($) {
480
+ /**
481
+ * Checks for value of given enum and returns expected type.
482
+ * @see https://mol.hyoo.ru/#!section=demos/demo=mol_data_enum_demo
483
+ */
484
+ function $mol_data_enum(name, dict) {
485
+ const index = {};
486
+ for (let key in dict) {
487
+ if (Number.isNaN(Number(key))) {
488
+ index[dict[key]] = key;
489
+ }
490
+ }
491
+ return $mol_data_setup((value) => {
492
+ if (typeof index[value] !== 'string') {
493
+ return $mol_fail(new $mol_data_error(`${value} is not value of ${name} enum`));
494
+ }
495
+ return value;
496
+ }, { name, dict });
497
+ }
498
+ $.$mol_data_enum = $mol_data_enum;
499
+ })($ || ($ = {}));
500
+
501
+ ;
502
+ "use strict";
503
+
504
+ ;
505
+ "use strict";
506
+ var $;
507
+ (function ($) {
508
+ const mod = require /****/('module');
509
+ const internals = mod.builtinModules;
510
+ function $node_internal_check(name) {
511
+ if (name.startsWith('node:'))
512
+ return true;
513
+ return internals.includes(name);
514
+ }
515
+ $.$node_internal_check = $node_internal_check;
516
+ })($ || ($ = {}));
517
+
518
+ ;
519
+ "use strict";
520
+ var $;
521
+ (function ($) {
522
+ function $mol_promise_like(val) {
523
+ try {
524
+ return val && typeof val === 'object' && 'then' in val && typeof val.then === 'function';
525
+ }
526
+ catch {
527
+ return false;
528
+ }
529
+ }
530
+ $.$mol_promise_like = $mol_promise_like;
531
+ })($ || ($ = {}));
532
+
533
+ ;
534
+ "use strict";
535
+ var $;
536
+ (function ($) {
537
+ const catched = new WeakSet();
538
+ function $mol_fail_catch(error) {
539
+ if (typeof error !== 'object')
540
+ return false;
541
+ if ($mol_promise_like(error))
542
+ $mol_fail_hidden(error);
543
+ if (catched.has(error))
544
+ return false;
545
+ catched.add(error);
546
+ return true;
547
+ }
548
+ $.$mol_fail_catch = $mol_fail_catch;
549
+ })($ || ($ = {}));
550
+
551
+ ;
552
+ "use strict";
553
+ var $;
554
+ (function ($) {
555
+ function $mol_try(handler) {
556
+ try {
557
+ return handler();
558
+ }
559
+ catch (error) {
560
+ console.error(error);
561
+ return error;
562
+ }
563
+ }
564
+ $.$mol_try = $mol_try;
565
+ })($ || ($ = {}));
566
+
567
+ ;
568
+ "use strict";
569
+ var $;
570
+ (function ($) {
571
+ function $mol_fail_log(error) {
572
+ if ($mol_promise_like(error))
573
+ return false;
574
+ if (!$mol_fail_catch(error))
575
+ return false;
576
+ $mol_try(() => { $mol_fail_hidden(error); });
577
+ return true;
578
+ }
579
+ $.$mol_fail_log = $mol_fail_log;
580
+ })($ || ($ = {}));
581
+
582
+ ;
583
+ "use strict";
584
+ var $;
585
+ (function ($) {
586
+ const path = require /****/('path');
587
+ const mod = require /****/('module');
588
+ const localRequire = mod.createRequire(path.join(process.cwd(), 'package.json'));
589
+ function $node_autoinstall(name) {
590
+ try {
591
+ localRequire.resolve(name);
592
+ }
593
+ catch {
594
+ this.$mol_run.spawn({ command: ['npm', 'install', '--omit=dev', name], dir: '.' });
595
+ try {
596
+ this.$mol_run.spawn({ command: ['npm', 'install', '--omit=dev', '@types/' + name], dir: '.' });
597
+ }
598
+ catch (e) {
599
+ if (this.$mol_promise_like(e))
600
+ this.$mol_fail_hidden(e);
601
+ this.$mol_fail_log(e);
602
+ }
603
+ }
604
+ }
605
+ $.$node_autoinstall = $node_autoinstall;
606
+ })($ || ($ = {}));
607
+
608
+ ;
609
+ "use strict";
610
+ var $node = new Proxy({ require }, {
611
+ get(target, name, wrapper) {
612
+ if (target[name])
613
+ return target[name];
614
+ if ($.$node_internal_check(name))
615
+ return target.require(name);
616
+ if (name[0] === '.')
617
+ return target.require(name);
618
+ $.$node_autoinstall(name);
619
+ return target.require(name);
620
+ },
621
+ set(target, name, value) {
622
+ target[name] = value;
623
+ return true;
624
+ },
625
+ });
626
+ require = (req => Object.assign(function require(name) {
627
+ return $node[name];
628
+ }, req))(require);
629
+
392
630
  ;
393
631
  "use strict";
394
632
  var $;
@@ -432,11 +670,32 @@ var $;
432
670
  "use strict";
433
671
  var $;
434
672
  (function ($) {
673
+ /** Generates unique identifier. */
674
+ function $mol_guid(length = 8, exists = () => false) {
675
+ for (;;) {
676
+ let id = Math.random().toString(36).substring(2, length + 2).toUpperCase();
677
+ if (exists(id))
678
+ continue;
679
+ return id;
680
+ }
681
+ }
682
+ $.$mol_guid = $mol_guid;
683
+ })($ || ($ = {}));
684
+
685
+ ;
686
+ "use strict";
687
+ var $;
688
+ (function ($) {
689
+ /** Special status statuses. */
435
690
  let $mol_wire_cursor;
436
691
  (function ($mol_wire_cursor) {
692
+ /** Update required. */
437
693
  $mol_wire_cursor[$mol_wire_cursor["stale"] = -1] = "stale";
694
+ /** Some of (transitive) pub update required. */
438
695
  $mol_wire_cursor[$mol_wire_cursor["doubt"] = -2] = "doubt";
696
+ /** Actual state but may be dropped. */
439
697
  $mol_wire_cursor[$mol_wire_cursor["fresh"] = -3] = "fresh";
698
+ /** State will never be changed. */
440
699
  $mol_wire_cursor[$mol_wire_cursor["final"] = -4] = "final";
441
700
  })($mol_wire_cursor = $.$mol_wire_cursor || ($.$mol_wire_cursor = {}));
442
701
  })($ || ($ = {}));
@@ -445,12 +704,27 @@ var $;
445
704
  "use strict";
446
705
  var $;
447
706
  (function ($) {
707
+ /**
708
+ * Collects subscribers in compact array. 28B
709
+ */
448
710
  class $mol_wire_pub extends Object {
711
+ constructor(id = `$mol_wire_pub:${$mol_guid()}`) {
712
+ super();
713
+ this[Symbol.toStringTag] = id;
714
+ }
715
+ [Symbol.toStringTag];
449
716
  data = [];
717
+ // Derived objects should be Arrays.
450
718
  static get [Symbol.species]() {
451
719
  return Array;
452
720
  }
453
- sub_from = 0;
721
+ /**
722
+ * Index of first subscriber.
723
+ */
724
+ sub_from = 0; // 4B
725
+ /**
726
+ * All current subscribers.
727
+ */
454
728
  get sub_list() {
455
729
  const res = [];
456
730
  for (let i = this.sub_from; i < this.data.length; i += 2) {
@@ -458,14 +732,23 @@ var $;
458
732
  }
459
733
  return res;
460
734
  }
735
+ /**
736
+ * Has any subscribers or not.
737
+ */
461
738
  get sub_empty() {
462
739
  return this.sub_from === this.data.length;
463
740
  }
741
+ /**
742
+ * Subscribe subscriber to this publisher events and return position of subscriber that required to unsubscribe.
743
+ */
464
744
  sub_on(sub, pub_pos) {
465
745
  const pos = this.data.length;
466
746
  this.data.push(sub, pub_pos);
467
747
  return pos;
468
748
  }
749
+ /**
750
+ * Unsubscribe subscriber from this publisher events by subscriber position provided by `on(pub)`.
751
+ */
469
752
  sub_off(sub_pos) {
470
753
  if (!(sub_pos < this.data.length)) {
471
754
  $mol_fail(new Error(`Wrong pos ${sub_pos}`));
@@ -478,21 +761,39 @@ var $;
478
761
  if (end === this.sub_from)
479
762
  this.reap();
480
763
  }
764
+ /**
765
+ * Called when last sub was unsubscribed.
766
+ **/
481
767
  reap() { }
768
+ /**
769
+ * Autowire this publisher with current subscriber.
770
+ **/
482
771
  promote() {
483
772
  $mol_wire_auto()?.track_next(this);
484
773
  }
774
+ /**
775
+ * Enforce actualization. Should not throw errors.
776
+ */
485
777
  fresh() { }
778
+ /**
779
+ * Allow to put data to caches in the subtree.
780
+ */
486
781
  complete() { }
487
782
  get incompleted() {
488
783
  return false;
489
784
  }
785
+ /**
786
+ * Notify subscribers about self changes.
787
+ */
490
788
  emit(quant = $mol_wire_cursor.stale) {
491
789
  for (let i = this.sub_from; i < this.data.length; i += 2) {
492
790
  ;
493
- this.data[i].absorb(quant);
791
+ this.data[i].absorb(quant, this.data[i + 1]);
494
792
  }
495
793
  }
794
+ /**
795
+ * Moves peer from one position to another. Doesn't clear data at old position!
796
+ */
496
797
  peer_move(from_pos, to_pos) {
497
798
  const peer = this.data[from_pos];
498
799
  const self_pos = this.data[from_pos + 1];
@@ -500,6 +801,9 @@ var $;
500
801
  this.data[to_pos + 1] = self_pos;
501
802
  peer.peer_repos(self_pos, to_pos);
502
803
  }
804
+ /**
805
+ * Updates self position in the peer.
806
+ */
503
807
  peer_repos(peer_pos, self_pos) {
504
808
  this.data[peer_pos + 1] = self_pos;
505
809
  }
@@ -515,10 +819,16 @@ var $;
515
819
  var $;
516
820
  (function ($) {
517
821
  $.$mol_wire_auto_sub = null;
822
+ /**
823
+ * When fulfilled, all publishers are promoted to this subscriber on access to its.
824
+ */
518
825
  function $mol_wire_auto(next = $.$mol_wire_auto_sub) {
519
826
  return $.$mol_wire_auto_sub = next;
520
827
  }
521
828
  $.$mol_wire_auto = $mol_wire_auto;
829
+ /**
830
+ * Affection queue. Used to prevent accidental stack overflow on emit.
831
+ */
522
832
  $.$mol_wire_affected = [];
523
833
  })($ || ($ = {}));
524
834
 
@@ -526,6 +836,7 @@ var $;
526
836
  "use strict";
527
837
  var $;
528
838
  (function ($) {
839
+ // https://docs.google.com/document/d/1FTascZXT9cxfetuPRT2eXPQKXui4nWFivUnS_335T3U/preview#
529
840
  $['devtoolsFormatters'] ||= [];
530
841
  function $mol_dev_format_register(config) {
531
842
  $['devtoolsFormatters'].push(config);
@@ -533,6 +844,17 @@ var $;
533
844
  $.$mol_dev_format_register = $mol_dev_format_register;
534
845
  $.$mol_dev_format_head = Symbol('$mol_dev_format_head');
535
846
  $.$mol_dev_format_body = Symbol('$mol_dev_format_body');
847
+ function $mol_dev_format_button(label, click) {
848
+ return $mol_dev_format_auto({
849
+ [$.$mol_dev_format_head]() {
850
+ return $.$mol_dev_format_span({ color: 'cornflowerblue' }, label);
851
+ },
852
+ [$.$mol_dev_format_body]() {
853
+ Promise.resolve().then(click);
854
+ return $.$mol_dev_format_span({});
855
+ }
856
+ });
857
+ }
536
858
  $mol_dev_format_register({
537
859
  header: (val, config = false) => {
538
860
  if (config)
@@ -550,17 +872,50 @@ var $;
550
872
  if (typeof val === 'function') {
551
873
  return $mol_dev_format_native(val);
552
874
  }
875
+ if (val instanceof Error) {
876
+ return $.$mol_dev_format_span({}, $mol_dev_format_native(val), ' ', $mol_dev_format_button('throw', () => $mol_fail_hidden(val)));
877
+ }
878
+ if (val instanceof Promise) {
879
+ return $.$mol_dev_format_shade($mol_dev_format_native(val), ' ', val[Symbol.toStringTag] ?? '');
880
+ }
553
881
  if (Symbol.toStringTag in val) {
554
882
  return $mol_dev_format_native(val);
555
883
  }
556
884
  return null;
557
885
  },
558
- hasBody: val => val[$.$mol_dev_format_body],
559
- body: val => val[$.$mol_dev_format_body](),
886
+ hasBody: (val, config = false) => {
887
+ if (config)
888
+ return false;
889
+ if (!val)
890
+ return false;
891
+ // if( Error.isError( val ) ) true
892
+ if (val[$.$mol_dev_format_body])
893
+ return true;
894
+ return false;
895
+ },
896
+ body: (val, config = false) => {
897
+ if (config)
898
+ return null;
899
+ if (!val)
900
+ return null;
901
+ if ($.$mol_dev_format_body in val) {
902
+ try {
903
+ return val[$.$mol_dev_format_body]();
904
+ }
905
+ catch (error) {
906
+ return $.$mol_dev_format_accent($mol_dev_format_native(val), '💨', $mol_dev_format_native(error), '');
907
+ }
908
+ }
909
+ // if( Error.isError( val ) ) {
910
+ // return $mol_dev_format_native( val )
911
+ // }
912
+ return null;
913
+ },
560
914
  });
561
915
  function $mol_dev_format_native(obj) {
562
916
  if (typeof obj === 'undefined')
563
917
  return $.$mol_dev_format_shade('undefined');
918
+ // if( ![ 'object', 'function', 'symbol' ].includes( typeof obj ) ) return obj
564
919
  return [
565
920
  'object',
566
921
  {
@@ -595,42 +950,117 @@ var $;
595
950
  ];
596
951
  }
597
952
  $.$mol_dev_format_element = $mol_dev_format_element;
598
- function $mol_dev_format_span(style, ...content) {
599
- return $mol_dev_format_element('span', {
600
- ...style,
601
- }, ...content);
602
- }
603
- $.$mol_dev_format_span = $mol_dev_format_span;
953
+ $.$mol_dev_format_span = $mol_dev_format_element.bind(null, 'span');
604
954
  $.$mol_dev_format_div = $mol_dev_format_element.bind(null, 'div');
605
955
  $.$mol_dev_format_ol = $mol_dev_format_element.bind(null, 'ol');
606
956
  $.$mol_dev_format_li = $mol_dev_format_element.bind(null, 'li');
607
957
  $.$mol_dev_format_table = $mol_dev_format_element.bind(null, 'table');
608
958
  $.$mol_dev_format_tr = $mol_dev_format_element.bind(null, 'tr');
609
959
  $.$mol_dev_format_td = $mol_dev_format_element.bind(null, 'td');
610
- $.$mol_dev_format_accent = $mol_dev_format_span.bind(null, {
960
+ $.$mol_dev_format_accent = $.$mol_dev_format_span.bind(null, {
611
961
  'color': 'magenta',
612
962
  });
613
- $.$mol_dev_format_strong = $mol_dev_format_span.bind(null, {
963
+ $.$mol_dev_format_strong = $.$mol_dev_format_span.bind(null, {
614
964
  'font-weight': 'bold',
615
965
  });
616
- $.$mol_dev_format_string = $mol_dev_format_span.bind(null, {
966
+ $.$mol_dev_format_string = $.$mol_dev_format_span.bind(null, {
617
967
  'color': 'green',
618
968
  });
619
- $.$mol_dev_format_shade = $mol_dev_format_span.bind(null, {
969
+ $.$mol_dev_format_shade = $.$mol_dev_format_span.bind(null, {
620
970
  'color': 'gray',
621
971
  });
622
972
  $.$mol_dev_format_indent = $.$mol_dev_format_div.bind(null, {
623
- 'margin-left': '13px'
973
+ 'margin-inline-start': '13px'
624
974
  });
975
+ class Stack extends Array {
976
+ // [ Symbol.toPrimitive ]() {
977
+ // return this.toString()
978
+ // }
979
+ match(...args) {
980
+ return this.toString().match(...args);
981
+ }
982
+ split(...args) {
983
+ return this.toString().split(...args);
984
+ }
985
+ toString() {
986
+ return this.join('\n');
987
+ }
988
+ }
989
+ class Call extends Object {
990
+ type;
991
+ function;
992
+ method;
993
+ eval;
994
+ source;
995
+ offset;
996
+ pos;
997
+ object;
998
+ flags;
999
+ [Symbol.toStringTag];
1000
+ constructor(call) {
1001
+ super();
1002
+ this.type = call.getTypeName() ?? '';
1003
+ this.function = call.getFunctionName() ?? '';
1004
+ this.method = call.getMethodName() ?? '';
1005
+ if (this.method === this.function)
1006
+ this.method = '';
1007
+ // const func = c.getFunction()
1008
+ this.pos = [call.getEnclosingLineNumber() ?? 0, call.getEnclosingColumnNumber() ?? 0];
1009
+ this.eval = call.getEvalOrigin() ?? '';
1010
+ this.source = call.getScriptNameOrSourceURL() ?? '';
1011
+ this.object = call.getThis();
1012
+ this.offset = call.getPosition();
1013
+ const flags = [];
1014
+ if (call.isAsync())
1015
+ flags.push('async');
1016
+ if (call.isConstructor())
1017
+ flags.push('constructor');
1018
+ if (call.isEval())
1019
+ flags.push('eval');
1020
+ if (call.isNative())
1021
+ flags.push('native');
1022
+ if (call.isPromiseAll())
1023
+ flags.push('PromiseAll');
1024
+ if (call.isToplevel())
1025
+ flags.push('top');
1026
+ this.flags = flags;
1027
+ const type = this.type ? this.type + '.' : '';
1028
+ const func = this.function || '<anon>';
1029
+ const method = this.method ? ' [' + this.method + '] ' : '';
1030
+ this[Symbol.toStringTag] = `${type}${func}${method}`;
1031
+ }
1032
+ [Symbol.toPrimitive]() {
1033
+ return this.toString();
1034
+ }
1035
+ toString() {
1036
+ const object = this.object || '';
1037
+ const label = this[Symbol.toStringTag];
1038
+ const source = `${this.source}:${this.pos.join(':')} #${this.offset}`;
1039
+ return `\tat ${object}${label} (${source})`;
1040
+ }
1041
+ [$.$mol_dev_format_head]() {
1042
+ return $.$mol_dev_format_div({}, $mol_dev_format_native(this), $.$mol_dev_format_shade(' '), ...this.object ? [
1043
+ $mol_dev_format_native(this.object),
1044
+ ] : [], ...this.method ? [$.$mol_dev_format_shade(' ', ' [', this.method, ']')] : [], $.$mol_dev_format_shade(' ', this.flags.join(', ')));
1045
+ }
1046
+ }
1047
+ Error.prepareStackTrace ??= (error, stack) => new Stack(...stack.map(call => new Call(call)));
625
1048
  })($ || ($ = {}));
626
1049
 
627
1050
  ;
628
1051
  "use strict";
629
1052
  var $;
630
1053
  (function ($) {
1054
+ /**
1055
+ * Publisher that can auto collect other publishers. 32B
1056
+ *
1057
+ * P1 P2 P3 P4 S1 S2 S3
1058
+ * ^ ^
1059
+ * pubs_from subs_from
1060
+ */
631
1061
  class $mol_wire_pub_sub extends $mol_wire_pub {
632
- pub_from = 0;
633
- cursor = $mol_wire_cursor.stale;
1062
+ pub_from = 0; // 4B
1063
+ cursor = $mol_wire_cursor.stale; // 4B
634
1064
  get temp() {
635
1065
  return false;
636
1066
  }
@@ -711,7 +1141,7 @@ var $;
711
1141
  this.data.length = this.sub_from;
712
1142
  this.cursor = this.pub_from;
713
1143
  this.track_cut();
714
- this.cursor = $mol_wire_cursor.final;
1144
+ this.cursor = $mol_wire_cursor.stale;
715
1145
  }
716
1146
  track_cut() {
717
1147
  if (this.cursor < this.pub_from) {
@@ -741,17 +1171,34 @@ var $;
741
1171
  pub?.complete();
742
1172
  }
743
1173
  }
744
- absorb(quant = $mol_wire_cursor.stale) {
1174
+ absorb(quant = $mol_wire_cursor.stale, pos = -1) {
745
1175
  if (this.cursor === $mol_wire_cursor.final)
746
1176
  return;
747
1177
  if (this.cursor >= quant)
748
1178
  return;
749
1179
  this.cursor = quant;
750
1180
  this.emit($mol_wire_cursor.doubt);
1181
+ // if( pos >= 0 && pos < this.sub_from - 2 ) {
1182
+ // const pub = this.data[ pos ] as $mol_wire_pub
1183
+ // if( pub instanceof $mol_wire_task ) return
1184
+ // for(
1185
+ // let cursor = this.pub_from;
1186
+ // cursor < this.sub_from;
1187
+ // cursor += 2
1188
+ // ) {
1189
+ // const pub = this.data[ cursor ] as $mol_wire_pub
1190
+ // if( pub instanceof $mol_wire_task ) {
1191
+ // pub.destructor()
1192
+ // }
1193
+ // }
1194
+ // }
751
1195
  }
752
1196
  [$mol_dev_format_head]() {
753
1197
  return $mol_dev_format_native(this);
754
1198
  }
1199
+ /**
1200
+ * Is subscribed to any publisher or not.
1201
+ */
755
1202
  get pub_empty() {
756
1203
  return this.sub_from === this.pub_from;
757
1204
  }
@@ -792,6 +1239,13 @@ var $;
792
1239
  var $;
793
1240
  (function ($) {
794
1241
  const wrappers = new WeakMap();
1242
+ /**
1243
+ * Suspendable task with support both sync/async api.
1244
+ *
1245
+ * A1 A2 A3 A4 P1 P2 P3 P4 S1 S2 S3
1246
+ * ^ ^ ^
1247
+ * args_from pubs_from subs_from
1248
+ **/
795
1249
  class $mol_wire_fiber extends $mol_wire_pub_sub {
796
1250
  task;
797
1251
  host;
@@ -812,6 +1266,7 @@ var $;
812
1266
  });
813
1267
  }
814
1268
  static sync() {
1269
+ // Sync whole fiber graph
815
1270
  while (this.planning.size) {
816
1271
  for (const fiber of this.planning) {
817
1272
  this.planning.delete(fiber);
@@ -822,6 +1277,7 @@ var $;
822
1277
  fiber.fresh();
823
1278
  }
824
1279
  }
1280
+ // Collect garbage
825
1281
  while (this.reaping.size) {
826
1282
  const fibers = this.reaping;
827
1283
  this.reaping = new Set;
@@ -832,7 +1288,6 @@ var $;
832
1288
  }
833
1289
  }
834
1290
  }
835
- [Symbol.toStringTag];
836
1291
  cache = undefined;
837
1292
  get args() {
838
1293
  return this.data.slice(0, this.pub_from);
@@ -848,16 +1303,15 @@ var $;
848
1303
  return $mol_promise_like(this.cache);
849
1304
  }
850
1305
  field() {
851
- return this.task.name + '<>';
1306
+ return this.task.name + '()';
852
1307
  }
853
1308
  constructor(id, task, host, args) {
854
- super();
1309
+ super(id);
855
1310
  this.task = task;
856
1311
  this.host = host;
857
1312
  if (args)
858
1313
  this.data.push(...args);
859
1314
  this.pub_from = this.sub_from = args?.length ?? 0;
860
- this[Symbol.toStringTag] = id;
861
1315
  }
862
1316
  plan() {
863
1317
  $mol_wire_fiber.planning.add(this);
@@ -882,12 +1336,10 @@ var $;
882
1336
  [$mol_wire_cursor.final]: '🔵',
883
1337
  }[this.cursor] ?? this.cursor.toString();
884
1338
  return $mol_dev_format_div({}, $mol_owning_check(this, this.cache)
885
- ? $mol_dev_format_auto({
886
- [$mol_dev_format_head]: () => $mol_dev_format_shade(cursor),
887
- [$mol_dev_format_body]: () => $mol_dev_format_native(this),
888
- })
889
- : $mol_dev_format_shade($mol_dev_format_native(this), cursor), $mol_dev_format_auto(this.cache));
1339
+ ? $mol_dev_format_shade(cursor)
1340
+ : $mol_dev_format_shade(this[Symbol.toStringTag], cursor), $mol_dev_format_auto(this.cache));
890
1341
  }
1342
+ [$mol_dev_format_body]() { return null; }
891
1343
  get $() {
892
1344
  return (this.host ?? this.task)['$'];
893
1345
  }
@@ -955,10 +1407,12 @@ var $;
955
1407
  result = wrappers.get(result);
956
1408
  }
957
1409
  else {
958
- wrappers.set(result, result = Object.assign(result.finally(() => {
1410
+ const put = (v) => {
959
1411
  if (this.cache === result)
960
1412
  this.absorb();
961
- }), { destructor: result.destructor || (() => { }) }));
1413
+ return v;
1414
+ };
1415
+ wrappers.set(result, result = Object.assign(result.then(put, put), { destructor: result.destructor || (() => { }) }));
962
1416
  const error = new Error(`Promise in ${this}`);
963
1417
  Object.defineProperty(result, 'stack', { get: () => error.stack });
964
1418
  }
@@ -975,6 +1429,10 @@ var $;
975
1429
  this.cursor = $mol_wire_cursor.stale;
976
1430
  this.fresh();
977
1431
  }
1432
+ /**
1433
+ * Synchronous execution. Throws Promise when waits async task (SuspenseAPI provider).
1434
+ * Should be called inside SuspenseAPI consumer (ie fiber).
1435
+ */
978
1436
  sync() {
979
1437
  if (!$mol_wire_fiber.warm) {
980
1438
  return this.result();
@@ -989,6 +1447,10 @@ var $;
989
1447
  }
990
1448
  return this.cache;
991
1449
  }
1450
+ /**
1451
+ * Asynchronous execution.
1452
+ * It's SuspenseAPI consumer. So SuspenseAPI providers can be called inside.
1453
+ */
992
1454
  async async_raw() {
993
1455
  while (true) {
994
1456
  this.fresh();
@@ -1001,6 +1463,7 @@ var $;
1001
1463
  if (!$mol_promise_like(this.cache))
1002
1464
  return this.cache;
1003
1465
  if (this.cursor === $mol_wire_cursor.final) {
1466
+ // never ends on destructed fiber
1004
1467
  await new Promise(() => { });
1005
1468
  }
1006
1469
  }
@@ -1025,9 +1488,19 @@ var $;
1025
1488
  }
1026
1489
  destructor() {
1027
1490
  super.destructor();
1028
- if ($mol_owning_check(this, this.cache)) {
1491
+ $mol_wire_fiber.planning.delete(this);
1492
+ if (!$mol_owning_check(this, this.cache))
1493
+ return;
1494
+ try {
1029
1495
  this.cache.destructor();
1030
1496
  }
1497
+ catch (result) {
1498
+ if ($mol_promise_like(result)) {
1499
+ const error = new Error(`Promise in ${this}.destructor()`);
1500
+ Object.defineProperty(result, 'stack', { get: () => error.stack });
1501
+ }
1502
+ $mol_fail_hidden(result);
1503
+ }
1031
1504
  }
1032
1505
  }
1033
1506
  $.$mol_wire_fiber = $mol_wire_fiber;
@@ -1038,6 +1511,10 @@ var $;
1038
1511
  var $;
1039
1512
  (function ($) {
1040
1513
  $.$mol_compare_deep_cache = new WeakMap();
1514
+ /**
1515
+ * Deeply compares two values. Returns true if equal.
1516
+ * Define `Symbol.toPrimitive` to customize.
1517
+ */
1041
1518
  function $mol_compare_deep(left, right) {
1042
1519
  if (Object.is(left, right))
1043
1520
  return true;
@@ -1064,7 +1541,7 @@ var $;
1064
1541
  if (left instanceof RegExp)
1065
1542
  return left.source === right.source && left.flags === right.flags;
1066
1543
  if (left instanceof Error)
1067
- return left.message === right.message && left.stack === right.stack;
1544
+ return left.message === right.message && $mol_compare_deep(left.stack, right.stack);
1068
1545
  let left_cache = $.$mol_compare_deep_cache.get(left);
1069
1546
  if (left_cache) {
1070
1547
  const right_cache = left_cache.get(right);
@@ -1118,7 +1595,7 @@ var $;
1118
1595
  if (len !== right.byteLength)
1119
1596
  return false;
1120
1597
  if (left instanceof DataView)
1121
- return compare_buffer(new Uint8Array(left.buffer, left.byteOffset, left.byteLength), new Uint8Array(right.buffer, left.byteOffset, left.byteLength));
1598
+ return compare_buffer(new Uint8Array(left.buffer, left.byteOffset, left.byteLength), new Uint8Array(right.buffer, right.byteOffset, right.byteLength));
1122
1599
  for (let i = 0; i < len; ++i) {
1123
1600
  if (left[i] !== right[i])
1124
1601
  return false;
@@ -1177,8 +1654,9 @@ var $;
1177
1654
  "use strict";
1178
1655
  var $;
1179
1656
  (function ($) {
1657
+ /** Log begin of collapsed group only when some logged inside, returns func to close group */
1180
1658
  function $mol_log3_area_lazy(event) {
1181
- const self = this;
1659
+ const self = this.$;
1182
1660
  const stack = self.$mol_log3_stack;
1183
1661
  const deep = stack.length;
1184
1662
  let logged = false;
@@ -1201,6 +1679,7 @@ var $;
1201
1679
  "use strict";
1202
1680
  var $;
1203
1681
  (function ($) {
1682
+ /** Position in any resource. */
1204
1683
  class $mol_span extends $mol_object2 {
1205
1684
  uri;
1206
1685
  source;
@@ -1216,13 +1695,17 @@ var $;
1216
1695
  this.length = length;
1217
1696
  this[Symbol.toStringTag] = this.uri + ('#' + this.row + ':' + this.col + '/' + this.length);
1218
1697
  }
1698
+ /** Span for begin of unknown resource */
1219
1699
  static unknown = $mol_span.begin('?');
1700
+ /** Makes new span for begin of resource. */
1220
1701
  static begin(uri, source = '') {
1221
1702
  return new $mol_span(uri, source, 1, 1, 0);
1222
1703
  }
1704
+ /** Makes new span for end of resource. */
1223
1705
  static end(uri, source) {
1224
1706
  return new $mol_span(uri, source, 1, source.length + 1, 0);
1225
1707
  }
1708
+ /** Makes new span for entire resource. */
1226
1709
  static entire(uri, source) {
1227
1710
  return new $mol_span(uri, source, 1, 1, source.length);
1228
1711
  }
@@ -1237,15 +1720,19 @@ var $;
1237
1720
  length: this.length
1238
1721
  };
1239
1722
  }
1723
+ /** Makes new error for this span. */
1240
1724
  error(message, Class = Error) {
1241
1725
  return new Class(`${message} (${this})`);
1242
1726
  }
1727
+ /** Makes new span for same uri. */
1243
1728
  span(row, col, length) {
1244
1729
  return new $mol_span(this.uri, this.source, row, col, length);
1245
1730
  }
1731
+ /** Makes new span after end of this. */
1246
1732
  after(length = 0) {
1247
1733
  return new $mol_span(this.uri, this.source, this.row, this.col + this.length, length);
1248
1734
  }
1735
+ /** Makes new span between begin and end. */
1249
1736
  slice(begin, end = -1) {
1250
1737
  let len = this.length;
1251
1738
  if (begin < 0)
@@ -1268,6 +1755,7 @@ var $;
1268
1755
  "use strict";
1269
1756
  var $;
1270
1757
  (function ($) {
1758
+ /** Serializes tree to string in tree format. */
1271
1759
  function $mol_tree2_to_string(tree) {
1272
1760
  let output = [];
1273
1761
  function dump(tree, prefix = '') {
@@ -1301,12 +1789,35 @@ var $;
1301
1789
  "use strict";
1302
1790
  var $;
1303
1791
  (function ($) {
1792
+ function $mol_maybe(value) {
1793
+ return (value == null) ? [] : [value];
1794
+ }
1795
+ $.$mol_maybe = $mol_maybe;
1796
+ })($ || ($ = {}));
1797
+
1798
+ ;
1799
+ "use strict";
1800
+ var $;
1801
+ (function ($) {
1802
+ /**
1803
+ * Abstract Syntax Tree with human readable serialization.
1804
+ * Avoid direct instantiation. Use static factories instead.
1805
+ * @see https://github.com/nin-jin/tree.d
1806
+ */
1304
1807
  class $mol_tree2 extends Object {
1305
1808
  type;
1306
1809
  value;
1307
1810
  kids;
1308
1811
  span;
1309
- constructor(type, value, kids, span) {
1812
+ constructor(
1813
+ /** Type of structural node, `value` should be empty */
1814
+ type,
1815
+ /** Content of data node, `type` should be empty */
1816
+ value,
1817
+ /** Child nodes */
1818
+ kids,
1819
+ /** Position in most far source resource */
1820
+ span) {
1310
1821
  super();
1311
1822
  this.type = type;
1312
1823
  this.value = value;
@@ -1314,12 +1825,15 @@ var $;
1314
1825
  this.span = span;
1315
1826
  this[Symbol.toStringTag] = type || '\\' + value;
1316
1827
  }
1828
+ /** Makes collection node. */
1317
1829
  static list(kids, span = $mol_span.unknown) {
1318
1830
  return new $mol_tree2('', '', kids, span);
1319
1831
  }
1832
+ /** Makes new derived collection node. */
1320
1833
  list(kids) {
1321
1834
  return $mol_tree2.list(kids, this.span);
1322
1835
  }
1836
+ /** Makes data node for any string. */
1323
1837
  static data(value, kids = [], span = $mol_span.unknown) {
1324
1838
  const chunks = value.split('\n');
1325
1839
  if (chunks.length > 1) {
@@ -1333,21 +1847,26 @@ var $;
1333
1847
  }
1334
1848
  return new $mol_tree2('', value, kids, span);
1335
1849
  }
1850
+ /** Makes new derived data node. */
1336
1851
  data(value, kids = []) {
1337
1852
  return $mol_tree2.data(value, kids, this.span);
1338
1853
  }
1854
+ /** Makes struct node. */
1339
1855
  static struct(type, kids = [], span = $mol_span.unknown) {
1340
1856
  if (/[ \n\t\\]/.test(type)) {
1341
1857
  $$.$mol_fail(span.error(`Wrong type ${JSON.stringify(type)}`));
1342
1858
  }
1343
1859
  return new $mol_tree2(type, '', kids, span);
1344
1860
  }
1861
+ /** Makes new derived structural node. */
1345
1862
  struct(type, kids = []) {
1346
1863
  return $mol_tree2.struct(type, kids, this.span);
1347
1864
  }
1865
+ /** Makes new derived node with different kids id defined. */
1348
1866
  clone(kids, span = this.span) {
1349
1867
  return new $mol_tree2(this.type, this.value, kids, span);
1350
1868
  }
1869
+ /** Returns multiline text content. */
1351
1870
  text() {
1352
1871
  var values = [];
1353
1872
  for (var kid of this.kids) {
@@ -1357,42 +1876,53 @@ var $;
1357
1876
  }
1358
1877
  return this.value + values.join('\n');
1359
1878
  }
1879
+ /** Parses tree format. */
1880
+ /** @deprecated Use $mol_tree2_from_string */
1360
1881
  static fromString(str, uri = 'unknown') {
1361
1882
  return $$.$mol_tree2_from_string(str, uri);
1362
1883
  }
1884
+ /** Serializes to tree format. */
1363
1885
  toString() {
1364
1886
  return $$.$mol_tree2_to_string(this);
1365
1887
  }
1888
+ /** Makes new tree with node overrided by path. */
1366
1889
  insert(value, ...path) {
1890
+ return this.update($mol_maybe(value), ...path)[0];
1891
+ }
1892
+ /** Makes new tree with node overrided by path. */
1893
+ update(value, ...path) {
1367
1894
  if (path.length === 0)
1368
1895
  return value;
1369
1896
  const type = path[0];
1370
1897
  if (typeof type === 'string') {
1371
1898
  let replaced = false;
1372
- const sub = this.kids.map((item, index) => {
1899
+ const sub = this.kids.flatMap((item, index) => {
1373
1900
  if (item.type !== type)
1374
1901
  return item;
1375
1902
  replaced = true;
1376
- return item.insert(value, ...path.slice(1));
1903
+ return item.update(value, ...path.slice(1));
1377
1904
  }).filter(Boolean);
1378
1905
  if (!replaced && value) {
1379
- sub.push(this.struct(type, []).insert(value, ...path.slice(1)));
1906
+ sub.push(...this.struct(type, []).update(value, ...path.slice(1)));
1380
1907
  }
1381
- return this.clone(sub);
1908
+ return [this.clone(sub)];
1382
1909
  }
1383
1910
  else if (typeof type === 'number') {
1384
- const sub = this.kids.slice();
1385
- sub[type] = (sub[type] || this.list([]))
1386
- .insert(value, ...path.slice(1));
1387
- return this.clone(sub.filter(Boolean));
1911
+ const ins = (this.kids[type] || this.list([]))
1912
+ .update(value, ...path.slice(1));
1913
+ return [this.clone([
1914
+ ...this.kids.slice(0, type),
1915
+ ...ins,
1916
+ ...this.kids.slice(type + 1),
1917
+ ])];
1388
1918
  }
1389
1919
  else {
1390
1920
  const kids = ((this.kids.length === 0) ? [this.list([])] : this.kids)
1391
- .map(item => item.insert(value, ...path.slice(1)))
1392
- .filter(Boolean);
1393
- return this.clone(kids);
1921
+ .flatMap(item => item.update(value, ...path.slice(1)));
1922
+ return [this.clone(kids)];
1394
1923
  }
1395
1924
  }
1925
+ /** Query nodes by path. */
1396
1926
  select(...path) {
1397
1927
  let next = [this];
1398
1928
  for (const type of path) {
@@ -1419,6 +1949,7 @@ var $;
1419
1949
  }
1420
1950
  return this.list(next);
1421
1951
  }
1952
+ /** Filter kids by path or value. */
1422
1953
  filter(path, value) {
1423
1954
  const sub = this.kids.filter(item => {
1424
1955
  var found = item.select(...path);
@@ -1446,9 +1977,11 @@ var $;
1446
1977
  $mol_fail_hidden(error);
1447
1978
  }
1448
1979
  }
1980
+ /** Transform tree through context with transformers */
1449
1981
  hack(belt, context = {}) {
1450
1982
  return [].concat(...this.kids.map(child => child.hack_self(belt, context)));
1451
1983
  }
1984
+ /** Makes Error with node coordinates. */
1452
1985
  error(message, Class = Error) {
1453
1986
  return this.span.error(`${message}\n${this.clone([])}`, Class);
1454
1987
  }
@@ -1466,6 +1999,7 @@ var $;
1466
1999
  "use strict";
1467
2000
  var $;
1468
2001
  (function ($) {
2002
+ /** Syntax error with cordinates and source line snippet. */
1469
2003
  class $mol_error_syntax extends SyntaxError {
1470
2004
  reason;
1471
2005
  line;
@@ -1484,6 +2018,7 @@ var $;
1484
2018
  "use strict";
1485
2019
  var $;
1486
2020
  (function ($) {
2021
+ /** Parses tree format from string. */
1487
2022
  function $mol_tree2_from_string(str, uri = '?') {
1488
2023
  const span = $mol_span.entire(uri, str);
1489
2024
  var root = $mol_tree2.list([], span);
@@ -1493,6 +2028,7 @@ var $;
1493
2028
  var indent = 0;
1494
2029
  var line_start = pos;
1495
2030
  row++;
2031
+ // read indent
1496
2032
  while (str.length > pos && str[pos] == '\t') {
1497
2033
  indent++;
1498
2034
  pos++;
@@ -1501,8 +2037,10 @@ var $;
1501
2037
  min_indent = indent;
1502
2038
  }
1503
2039
  indent -= min_indent;
2040
+ // invalid tab size
1504
2041
  if (indent < 0 || indent >= stack.length) {
1505
2042
  const sp = span.span(row, 1, pos - line_start);
2043
+ // skip error line
1506
2044
  while (str.length > pos && str[pos] != '\n') {
1507
2045
  pos++;
1508
2046
  }
@@ -1517,7 +2055,9 @@ var $;
1517
2055
  }
1518
2056
  stack.length = indent + 1;
1519
2057
  var parent = stack[indent];
2058
+ // parse types
1520
2059
  while (str.length > pos && str[pos] != '\\' && str[pos] != '\n') {
2060
+ // type can not contain space and tab
1521
2061
  var error_start = pos;
1522
2062
  while (str.length > pos && (str[pos] == ' ' || str[pos] == '\t')) {
1523
2063
  pos++;
@@ -1529,6 +2069,7 @@ var $;
1529
2069
  const sp = span.span(row, error_start - line_start + 1, pos - error_start);
1530
2070
  this.$mol_fail(new this.$mol_error_syntax(`Wrong nodes separator`, str.substring(line_start, line_end), sp));
1531
2071
  }
2072
+ // read type
1532
2073
  var type_start = pos;
1533
2074
  while (str.length > pos &&
1534
2075
  str[pos] != '\\' &&
@@ -1543,10 +2084,12 @@ var $;
1543
2084
  parent_kids.push(next);
1544
2085
  parent = next;
1545
2086
  }
2087
+ // read one space if exists
1546
2088
  if (str.length > pos && str[pos] == ' ') {
1547
2089
  pos++;
1548
2090
  }
1549
2091
  }
2092
+ // read data
1550
2093
  if (str.length > pos && str[pos] == '\\') {
1551
2094
  var data_start = pos;
1552
2095
  while (str.length > pos && str[pos] != '\n') {
@@ -1557,6 +2100,7 @@ var $;
1557
2100
  parent_kids.push(next);
1558
2101
  parent = next;
1559
2102
  }
2103
+ // now must be end of text
1560
2104
  if (str.length === pos && stack.length > 0) {
1561
2105
  const sp = span.span(row, pos - line_start + 1, 1);
1562
2106
  this.$mol_fail(new this.$mol_error_syntax(`Unexpected EOF, LF required`, str.substring(line_start, str.length), sp));
@@ -1569,6 +2113,30 @@ var $;
1569
2113
  $.$mol_tree2_from_string = $mol_tree2_from_string;
1570
2114
  })($ || ($ = {}));
1571
2115
 
2116
+ ;
2117
+ "use strict";
2118
+ var $;
2119
+ (function ($) {
2120
+ function $mol_array_chunks(array, rule) {
2121
+ const br = typeof rule === 'number' ? (_, i) => i % rule === 0 : rule;
2122
+ let chunk = [];
2123
+ const chunks = [];
2124
+ for (let i = 0; i < array.length; ++i) {
2125
+ const item = array[i];
2126
+ if (br(item, i)) {
2127
+ if (chunk.length)
2128
+ chunks.push(chunk);
2129
+ chunk = [];
2130
+ }
2131
+ chunk.push(item);
2132
+ }
2133
+ if (chunk.length)
2134
+ chunks.push(chunk);
2135
+ return chunks;
2136
+ }
2137
+ $.$mol_array_chunks = $mol_array_chunks;
2138
+ })($ || ($ = {}));
2139
+
1572
2140
  ;
1573
2141
  "use strict";
1574
2142
  var $;
@@ -1589,7 +2157,9 @@ var $;
1589
2157
  }
1590
2158
  if (ArrayBuffer.isView(json)) {
1591
2159
  const buf = new Uint8Array(json.buffer, json.byteOffset, json.byteLength);
1592
- return $mol_tree2.data(String.fromCharCode(...buf), [], span);
2160
+ const codes = [...buf].map(b => b.toString(16).toUpperCase().padStart(2, '0'));
2161
+ const str = $mol_array_chunks(codes, 8).map(c => c.join(' ')).join('\n');
2162
+ return $mol_tree2.data(str, [], span);
1593
2163
  }
1594
2164
  if (json instanceof Date) {
1595
2165
  return new $mol_tree2('', json.toISOString(), [], span);
@@ -1623,6 +2193,7 @@ var $;
1623
2193
  "use strict";
1624
2194
  var $;
1625
2195
  (function ($) {
2196
+ /** Module for working with terminal. Text coloring when output in terminal */
1626
2197
  class $mol_term_color {
1627
2198
  static reset = this.ansi(0, 0);
1628
2199
  static bold = this.ansi(1, 22);
@@ -1672,7 +2243,7 @@ var $;
1672
2243
  function $mol_log3_node_make(level, output, type, color) {
1673
2244
  return function $mol_log3_logger(event) {
1674
2245
  if (!event.time)
1675
- event = { time: new Date().toISOString(), ...event };
2246
+ event = { ...event, time: new Date().toISOString() };
1676
2247
  let tree = this.$mol_tree2_from_json(event);
1677
2248
  tree = tree.struct(type, tree.kids);
1678
2249
  let str = color(tree.toString());
@@ -1694,32 +2265,41 @@ var $;
1694
2265
  "use strict";
1695
2266
  var $;
1696
2267
  (function ($) {
2268
+ /** One-shot fiber */
1697
2269
  class $mol_wire_task extends $mol_wire_fiber {
1698
2270
  static getter(task) {
1699
2271
  return function $mol_wire_task_get(host, args) {
1700
2272
  const sub = $mol_wire_auto();
1701
2273
  const existen = sub?.track_next();
2274
+ let cause = '';
1702
2275
  reuse: if (existen) {
1703
2276
  if (!existen.temp)
1704
2277
  break reuse;
1705
- if (existen.host !== host)
2278
+ if (existen.host !== host) {
2279
+ cause = 'host';
1706
2280
  break reuse;
1707
- if (existen.task !== task)
2281
+ }
2282
+ if (existen.task !== task) {
2283
+ cause = 'task';
1708
2284
  break reuse;
1709
- if (!$mol_compare_deep(existen.args, args))
2285
+ }
2286
+ if (!$mol_compare_deep(existen.args, args)) {
2287
+ cause = 'args';
1710
2288
  break reuse;
2289
+ }
1711
2290
  return existen;
1712
2291
  }
1713
2292
  const key = (host?.[Symbol.toStringTag] ?? host) + ('.' + task.name + '<#>');
1714
2293
  const next = new $mol_wire_task(key, task, host, args);
2294
+ // Disabled because non-idempotency is required for try-catch
1715
2295
  if (existen?.temp) {
1716
2296
  $$.$mol_log3_warn({
1717
2297
  place: '$mol_wire_task',
1718
- message: `Non idempotency`,
2298
+ message: `Different ${cause} on restart`,
1719
2299
  sub,
1720
- pubs: [...sub?.pub_list ?? [], existen],
2300
+ prev: existen,
1721
2301
  next,
1722
- hint: 'Ignore it',
2302
+ hint: 'Maybe required additional memoization',
1723
2303
  });
1724
2304
  }
1725
2305
  return next;
@@ -1744,7 +2324,7 @@ var $;
1744
2324
  try {
1745
2325
  next[Symbol.toStringTag] = this[Symbol.toStringTag];
1746
2326
  }
1747
- catch {
2327
+ catch { // Promises throw in strict mode
1748
2328
  Object.defineProperty(next, Symbol.toStringTag, { value: this[Symbol.toStringTag] });
1749
2329
  }
1750
2330
  }
@@ -1757,6 +2337,10 @@ var $;
1757
2337
  this.emit();
1758
2338
  return next;
1759
2339
  }
2340
+ destructor() {
2341
+ super.destructor();
2342
+ this.cursor = $mol_wire_cursor.final;
2343
+ }
1760
2344
  }
1761
2345
  $.$mol_wire_task = $mol_wire_task;
1762
2346
  })($ || ($ = {}));
@@ -1774,18 +2358,46 @@ var $;
1774
2358
  factories.set(val, make);
1775
2359
  return make;
1776
2360
  }
2361
+ const getters = new WeakMap();
2362
+ function get_prop(host, field) {
2363
+ let props = getters.get(host);
2364
+ let get_val = props?.[field];
2365
+ if (get_val)
2366
+ return get_val;
2367
+ get_val = (next) => {
2368
+ if (next !== undefined)
2369
+ host[field] = next;
2370
+ return host[field];
2371
+ };
2372
+ Object.defineProperty(get_val, 'name', { value: field });
2373
+ if (!props) {
2374
+ props = {};
2375
+ getters.set(host, props);
2376
+ }
2377
+ props[field] = get_val;
2378
+ return get_val;
2379
+ }
2380
+ /**
2381
+ * Convert asynchronous (promise-based) API to synchronous by wrapping function and method calls in a fiber.
2382
+ * @see https://mol.hyoo.ru/#!section=docs/=1fcpsq_1wh0h2
2383
+ */
1777
2384
  function $mol_wire_sync(obj) {
1778
2385
  return new Proxy(obj, {
1779
2386
  get(obj, field) {
1780
2387
  let val = obj[field];
2388
+ const temp = $mol_wire_task.getter(typeof val === 'function' ? val : get_prop(obj, field));
1781
2389
  if (typeof val !== 'function')
1782
- return val;
1783
- const temp = $mol_wire_task.getter(val);
2390
+ return temp(obj, []).sync();
1784
2391
  return function $mol_wire_sync(...args) {
1785
2392
  const fiber = temp(obj, args);
1786
2393
  return fiber.sync();
1787
2394
  };
1788
2395
  },
2396
+ set(obj, field, next) {
2397
+ const temp = $mol_wire_task.getter(get_prop(obj, field));
2398
+ temp(obj, [next]).sync();
2399
+ return true;
2400
+ },
1789
2401
  construct(obj, args) {
1790
2402
  const temp = $mol_wire_task.getter(factory(obj));
1791
2403
  return temp(obj, args).sync();
@@ -1899,162 +2511,24 @@ var $;
1899
2511
  return fail(new $mol_run_error(this.error_message(res) + (timeout_kill ? ', timeout' : ''), { ...log_object, pid, status, signal, timeout_kill }, ...error ? [error] : []));
1900
2512
  this.$.$mol_log3_done({
1901
2513
  ...log_object,
1902
- pid,
1903
- });
1904
- done(res);
1905
- };
1906
- sub.on('disconnect', () => close(new Error('Disconnected')));
1907
- sub.on('error', err => close(err));
1908
- sub.on('exit', (status, signal) => close(null, status, signal));
1909
- });
1910
- return Object.assign(result_promise, { destructor: () => {
1911
- clearTimeout(timer);
1912
- sub.kill('SIGKILL');
1913
- } });
1914
- }
1915
- static error_message(res) {
1916
- return res?.stderr.toString() || res?.stdout.toString() || 'Run error';
1917
- }
1918
- }
1919
- $.$mol_run = $mol_run;
1920
- })($ || ($ = {}));
1921
-
1922
- ;
1923
- "use strict";
1924
- var $;
1925
- (function ($) {
1926
- function $mol_exec(dir, command, ...args) {
1927
- return this.$mol_run.spawn({ command: [command, ...args], dir });
1928
- }
1929
- $.$mol_exec = $mol_exec;
1930
- })($ || ($ = {}));
1931
-
1932
- ;
1933
- "use strict";
1934
- var $;
1935
- (function ($) {
1936
- const TextEncoder = globalThis.TextEncoder ?? $node.util.TextEncoder;
1937
- const encoder = new TextEncoder();
1938
- function $mol_charset_encode(value) {
1939
- return encoder.encode(value);
1940
- }
1941
- $.$mol_charset_encode = $mol_charset_encode;
1942
- })($ || ($ = {}));
1943
-
1944
- ;
1945
- "use strict";
1946
- var $;
1947
- (function ($) {
1948
- function $mol_int62_string_ensure(str) {
1949
- if (typeof str !== 'string')
1950
- return null;
1951
- return $mol_int62_from_string(str) && str;
1952
- }
1953
- $.$mol_int62_string_ensure = $mol_int62_string_ensure;
1954
- $.$mol_int62_max = (2 ** 30) - 1;
1955
- $.$mol_int62_min = -(2 ** 30);
1956
- $.$mol_int62_range = $.$mol_int62_max - $.$mol_int62_min + 1;
1957
- function $mol_int62_to_string({ lo, hi }) {
1958
- lo = (lo + $.$mol_int62_range) % $.$mol_int62_range;
1959
- hi = (hi + $.$mol_int62_range) % $.$mol_int62_range;
1960
- return lo.toString(36) + '_' + hi.toString(36);
1961
- }
1962
- $.$mol_int62_to_string = $mol_int62_to_string;
1963
- function $mol_int62_from_string(str) {
1964
- const [str_lo, str_hi] = str.split('_');
1965
- const int_lo = parseInt(str_lo, 36);
1966
- const int_hi = parseInt(str_hi, 36);
1967
- if (int_lo.toString(36) !== str_lo || int_hi.toString(36) !== str_hi) {
1968
- return null;
1969
- }
1970
- return {
1971
- lo: (int_lo - $.$mol_int62_min) % $.$mol_int62_range + $.$mol_int62_min,
1972
- hi: (int_hi - $.$mol_int62_min) % $.$mol_int62_range + $.$mol_int62_min,
1973
- };
1974
- }
1975
- $.$mol_int62_from_string = $mol_int62_from_string;
1976
- function $mol_int62_compare(left_lo, left_hi, right_lo, right_hi) {
1977
- return (right_hi - left_hi) || (right_lo - left_lo);
1978
- }
1979
- $.$mol_int62_compare = $mol_int62_compare;
1980
- function $mol_int62_inc(lo, hi, max = $.$mol_int62_max) {
1981
- if (lo === max) {
1982
- return { lo: -max, hi: hi + 1 };
1983
- }
1984
- else {
1985
- return { lo: lo + 1, hi };
1986
- }
1987
- }
1988
- $.$mol_int62_inc = $mol_int62_inc;
1989
- function $mol_int62_random() {
1990
- return {
1991
- lo: Math.floor(Math.random() * $.$mol_int62_range + $.$mol_int62_min),
1992
- hi: Math.floor(Math.random() * $.$mol_int62_range + $.$mol_int62_min),
1993
- };
1994
- }
1995
- $.$mol_int62_random = $mol_int62_random;
1996
- function $mol_int62_hash_string(str) {
1997
- return $mol_int62_to_string($mol_int62_hash_buffer($mol_charset_encode(str)));
1998
- }
1999
- $.$mol_int62_hash_string = $mol_int62_hash_string;
2000
- function $mol_int62_hash_buffer(buf, seed = { lo: 0, hi: 0 }) {
2001
- let h1 = 0xdeadbeef ^ seed.lo;
2002
- let h2 = 0x41c6ce57 ^ seed.hi;
2003
- for (const byte of buf) {
2004
- h1 = Math.imul(h1 ^ byte, 2654435761);
2005
- h2 = Math.imul(h2 ^ byte, 1597334677);
2514
+ pid,
2515
+ });
2516
+ done(res);
2517
+ };
2518
+ sub.on('disconnect', () => close(new Error('Disconnected')));
2519
+ sub.on('error', err => close(err));
2520
+ sub.on('exit', (status, signal) => close(null, status, signal));
2521
+ });
2522
+ return Object.assign(result_promise, { destructor: () => {
2523
+ clearTimeout(timer);
2524
+ sub.kill('SIGKILL');
2525
+ } });
2006
2526
  }
2007
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
2008
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
2009
- return { lo: h1 << 1 >> 1, hi: h2 << 1 >> 1 };
2010
- }
2011
- $.$mol_int62_hash_buffer = $mol_int62_hash_buffer;
2012
- })($ || ($ = {}));
2013
-
2014
- ;
2015
- "use strict";
2016
-
2017
- ;
2018
- "use strict";
2019
- var $;
2020
- (function ($) {
2021
- function $mol_data_setup(value, config) {
2022
- return Object.assign(value, {
2023
- config,
2024
- Value: null
2025
- });
2026
- }
2027
- $.$mol_data_setup = $mol_data_setup;
2028
- })($ || ($ = {}));
2029
-
2030
- ;
2031
- "use strict";
2032
- var $;
2033
- (function ($) {
2034
- class $mol_data_error extends $mol_error_mix {
2035
- }
2036
- $.$mol_data_error = $mol_data_error;
2037
- })($ || ($ = {}));
2038
-
2039
- ;
2040
- "use strict";
2041
- var $;
2042
- (function ($) {
2043
- function $mol_data_enum(name, dict) {
2044
- const index = {};
2045
- for (let key in dict) {
2046
- if (Number.isNaN(Number(key))) {
2047
- index[dict[key]] = key;
2048
- }
2527
+ static error_message(res) {
2528
+ return res?.stderr.toString() || res?.stdout.toString() || 'Run error';
2049
2529
  }
2050
- return $mol_data_setup((value) => {
2051
- if (typeof index[value] !== 'string') {
2052
- return $mol_fail(new $mol_data_error(`${value} is not value of ${name} enum`));
2053
- }
2054
- return value;
2055
- }, { name, dict });
2056
2530
  }
2057
- $.$mol_data_enum = $mol_data_enum;
2531
+ $.$mol_run = $mol_run;
2058
2532
  })($ || ($ = {}));
2059
2533
 
2060
2534
  ;
@@ -2068,73 +2542,52 @@ var $;
2068
2542
  "use strict";
2069
2543
  var $;
2070
2544
  (function ($) {
2071
- function $mol_base64_encode(src) {
2072
- throw new Error('Not implemented');
2545
+ function $mol_base64_url_encode(buffer) {
2546
+ return buffer.toBase64({ alphabet: 'base64url', omitPadding: true });
2547
+ }
2548
+ $.$mol_base64_url_encode = $mol_base64_url_encode;
2549
+ function $mol_base64_url_decode(str) {
2550
+ return Uint8Array.fromBase64(str, { alphabet: 'base64url' });
2073
2551
  }
2074
- $.$mol_base64_encode = $mol_base64_encode;
2552
+ $.$mol_base64_url_decode = $mol_base64_url_decode;
2075
2553
  })($ || ($ = {}));
2076
2554
 
2077
2555
  ;
2078
2556
  "use strict";
2079
2557
  var $;
2080
2558
  (function ($) {
2081
- function $mol_base64_encode_node(str) {
2559
+ function $mol_base64_url_encode_node(str) {
2082
2560
  if (!str)
2083
2561
  return '';
2084
- if (Buffer.isBuffer(str))
2085
- return str.toString('base64');
2086
- return Buffer.from(str).toString('base64');
2562
+ const buf = Buffer.isBuffer(str) ? str : Buffer.from(str);
2563
+ return buf.toString('base64url').replace(/=/g, '');
2087
2564
  }
2088
- $.$mol_base64_encode_node = $mol_base64_encode_node;
2089
- $.$mol_base64_encode = $mol_base64_encode_node;
2090
- })($ || ($ = {}));
2091
-
2092
- ;
2093
- "use strict";
2094
- var $;
2095
- (function ($) {
2096
- function $mol_base64_decode(base64) {
2097
- throw new Error('Not implemented');
2565
+ $.$mol_base64_url_encode_node = $mol_base64_url_encode_node;
2566
+ if (!('toBase64' in Uint8Array.prototype)) {
2567
+ $.$mol_base64_url_encode = $mol_base64_url_encode_node;
2098
2568
  }
2099
- $.$mol_base64_decode = $mol_base64_decode;
2100
- })($ || ($ = {}));
2101
-
2102
- ;
2103
- "use strict";
2104
- var $;
2105
- (function ($) {
2106
- function $mol_base64_decode_node(base64Str) {
2107
- base64Str = base64Str.replace(/-/g, '+').replace(/_/g, '/');
2108
- const buffer = Buffer.from(base64Str, 'base64');
2569
+ function $mol_base64_url_decode_node(str) {
2570
+ // without Uint8Array breaks $mol_compare_deep
2571
+ const buffer = Buffer.from(str, 'base64url');
2109
2572
  return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
2110
2573
  }
2111
- $.$mol_base64_decode_node = $mol_base64_decode_node;
2112
- $.$mol_base64_decode = $mol_base64_decode_node;
2113
- })($ || ($ = {}));
2114
-
2115
- ;
2116
- "use strict";
2117
- var $;
2118
- (function ($) {
2119
- function $mol_base64_url_encode(buffer) {
2120
- return $mol_base64_encode(buffer).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
2121
- }
2122
- $.$mol_base64_url_encode = $mol_base64_url_encode;
2123
- function $mol_base64_url_decode(str) {
2124
- return $mol_base64_decode(str.replace(/-/g, '+').replace(/_/g, '/'));
2574
+ $.$mol_base64_url_decode_node = $mol_base64_url_decode_node;
2575
+ if (!('fromBase64' in Uint8Array)) {
2576
+ $.$mol_base64_url_decode = $mol_base64_url_decode_node;
2125
2577
  }
2126
- $.$mol_base64_url_decode = $mol_base64_url_decode;
2127
2578
  })($ || ($ = {}));
2128
2579
 
2129
2580
  ;
2130
2581
  "use strict";
2131
2582
  var $;
2132
2583
  (function ($) {
2584
+ /** @FIXME Need polyfill for Safari and Node (https://github.com/microsoft/MSR-JavaScript-Crypto/) */
2133
2585
  const algorithm = {
2134
2586
  name: 'ECDSA',
2135
2587
  hash: 'SHA-256',
2136
2588
  namedCurve: "P-256",
2137
2589
  };
2590
+ /** Asymmetric signing pair with shortest payload */
2138
2591
  async function $mol_crypto_auditor_pair() {
2139
2592
  const pair = await $mol_crypto_native.subtle.generateKey(algorithm, true, ['sign', 'verify']);
2140
2593
  return {
@@ -2143,8 +2596,10 @@ var $;
2143
2596
  };
2144
2597
  }
2145
2598
  $.$mol_crypto_auditor_pair = $mol_crypto_auditor_pair;
2599
+ /** Asymmetric signing public key wrapper with shortest payload */
2146
2600
  class $mol_crypto_auditor_public extends Object {
2147
2601
  native;
2602
+ /** Key size in bytes. */
2148
2603
  static size_str = 86;
2149
2604
  static size_bin = 64;
2150
2605
  constructor(native) {
@@ -2165,10 +2620,12 @@ var $;
2165
2620
  y: serial.slice(43, 86),
2166
2621
  }, algorithm, true, ['verify']));
2167
2622
  }
2623
+ /** 86 bytes */
2168
2624
  async serial() {
2169
2625
  const { x, y } = await $mol_crypto_native.subtle.exportKey('jwk', this.native);
2170
2626
  return x + y;
2171
2627
  }
2628
+ /** 64 bytes */
2172
2629
  async toArray() {
2173
2630
  const { x, y, d } = await $mol_crypto_native.subtle.exportKey('jwk', this.native);
2174
2631
  return new Uint8Array([
@@ -2181,8 +2638,10 @@ var $;
2181
2638
  }
2182
2639
  }
2183
2640
  $.$mol_crypto_auditor_public = $mol_crypto_auditor_public;
2641
+ /** Asymmetric signing private key wrapper with shortest payload */
2184
2642
  class $mol_crypto_auditor_private extends Object {
2185
2643
  native;
2644
+ /** Key size in bytes. */
2186
2645
  static size_str = 129;
2187
2646
  static size_bin = 96;
2188
2647
  constructor(native) {
@@ -2205,10 +2664,12 @@ var $;
2205
2664
  d: serial.slice(86, 129),
2206
2665
  }, algorithm, true, ['sign']));
2207
2666
  }
2667
+ /** 129 bytes */
2208
2668
  async serial() {
2209
2669
  const { x, y, d } = await $mol_crypto_native.subtle.exportKey('jwk', this.native);
2210
2670
  return x + y + d;
2211
2671
  }
2672
+ /** 96 bytes */
2212
2673
  async toArray() {
2213
2674
  const { x, y, d } = await $mol_crypto_native.subtle.exportKey('jwk', this.native);
2214
2675
  return new Uint8Array([
@@ -2217,14 +2678,17 @@ var $;
2217
2678
  ...$mol_base64_url_decode(d),
2218
2679
  ]);
2219
2680
  }
2681
+ /** 64 bytes */
2220
2682
  async sign(data) {
2221
2683
  return await $mol_crypto_native.subtle.sign(algorithm, this.native, data);
2222
2684
  }
2685
+ /** Makes public key from private */
2223
2686
  async public() {
2224
2687
  return await $mol_crypto_auditor_public.from($mol_crypto_auditor_private_to_public(await this.serial()));
2225
2688
  }
2226
2689
  }
2227
2690
  $.$mol_crypto_auditor_private = $mol_crypto_auditor_private;
2691
+ /** Sign size in bytes. */
2228
2692
  $.$mol_crypto_auditor_sign_size = 64;
2229
2693
  function $mol_crypto_auditor_private_to_public(serial) {
2230
2694
  return serial.slice(0, 86);
@@ -2293,16 +2757,23 @@ var $;
2293
2757
  const level = $mol_data_enum('level', $hyoo_crowd_peer_level);
2294
2758
  let $hyoo_crowd_unit_kind;
2295
2759
  (function ($hyoo_crowd_unit_kind) {
2760
+ /** Grab Land by King */
2296
2761
  $hyoo_crowd_unit_kind[$hyoo_crowd_unit_kind["grab"] = 0] = "grab";
2762
+ /** Join Peer to Land */
2297
2763
  $hyoo_crowd_unit_kind[$hyoo_crowd_unit_kind["join"] = 1] = "join";
2764
+ /* Give Level for Peer for Land */
2298
2765
  $hyoo_crowd_unit_kind[$hyoo_crowd_unit_kind["give"] = 2] = "give";
2766
+ /** Add Data to Land by joined Peer with right Level */
2299
2767
  $hyoo_crowd_unit_kind[$hyoo_crowd_unit_kind["data"] = 3] = "data";
2300
2768
  })($hyoo_crowd_unit_kind = $.$hyoo_crowd_unit_kind || ($.$hyoo_crowd_unit_kind = {}));
2301
2769
  let $hyoo_crowd_unit_group;
2302
2770
  (function ($hyoo_crowd_unit_group) {
2771
+ /** Join and Give units */
2303
2772
  $hyoo_crowd_unit_group[$hyoo_crowd_unit_group["auth"] = 0] = "auth";
2773
+ /** Data units */
2304
2774
  $hyoo_crowd_unit_group[$hyoo_crowd_unit_group["data"] = 1] = "data";
2305
2775
  })($hyoo_crowd_unit_group = $.$hyoo_crowd_unit_group || ($.$hyoo_crowd_unit_group = {}));
2776
+ /** Independent part of data. */
2306
2777
  class $hyoo_crowd_unit extends Object {
2307
2778
  land;
2308
2779
  auth;
@@ -2313,7 +2784,24 @@ var $;
2313
2784
  time;
2314
2785
  data;
2315
2786
  bin;
2316
- constructor(land, auth, head, self, next, prev, time, data, bin) {
2787
+ constructor(
2788
+ /** Identifier of land. */
2789
+ land,
2790
+ /** Identifier of auth. */
2791
+ auth,
2792
+ /** Identifier of head node. */
2793
+ head,
2794
+ /** Self identifier inside head after prev before next. */
2795
+ self,
2796
+ /** Identifier of next node. */
2797
+ next,
2798
+ /** Identifier of prev node. */
2799
+ prev,
2800
+ /** Monotonic real clock. 4B / info = 31b */
2801
+ time,
2802
+ /** type-size = bin<0 | null=0 | json>0 */
2803
+ /** Associated atomic data. mem = 4B+ / bin = (0|8B)+ / type-size-info = 16b */
2804
+ data, bin) {
2317
2805
  super();
2318
2806
  this.land = land;
2319
2807
  this.auth = auth;
@@ -2441,9 +2929,28 @@ var $;
2441
2929
  buff.set(next);
2442
2930
  return buff;
2443
2931
  }
2932
+ // land( next?: $mol_int62_pair ) {
2933
+ // if( next ) {
2934
+ // this.setInt32( offset.land_lo, next.lo, true )
2935
+ // this.setInt32( offset.land_hi, next.hi, true )
2936
+ // return next
2937
+ // } else {
2938
+ // return {
2939
+ // lo: this.getInt32( offset.land_lo, true ),
2940
+ // hi: this.getInt32( offset.land_hi, true ),
2941
+ // }
2942
+ // }
2943
+ // }
2444
2944
  size() {
2445
2945
  return Math.ceil(Math.abs(this.getInt16(offset.size, true)) / 8) * 8 + offset.data + $mol_crypto_auditor_sign_size;
2446
2946
  }
2947
+ // data() {
2948
+ // const info = this.getUint16( offset.data )
2949
+ // const size = Math.abs( info )
2950
+ // const buf = new Uint8Array( this.buffer, this.byteOffset + offset.sens, size )
2951
+ // const data = info > 0 ? JSON.parse( $mol_charset_decode( buf ) ) : info < 0 ? buf : null
2952
+ // return data
2953
+ // }
2447
2954
  sens() {
2448
2955
  return new Uint8Array(this.buffer, this.byteOffset, this.size() - $mol_crypto_auditor_sign_size);
2449
2956
  }
@@ -2509,61 +3016,51 @@ var $;
2509
3016
  "use strict";
2510
3017
  var $;
2511
3018
  (function ($) {
2512
- function $mol_guid(length = 8, exists = () => false) {
2513
- for (;;) {
2514
- let id = Math.random().toString(36).substring(2, length + 2).toUpperCase();
2515
- if (exists(id))
2516
- continue;
2517
- return id;
2518
- }
2519
- }
2520
- $.$mol_guid = $mol_guid;
2521
- })($ || ($ = {}));
2522
-
2523
- ;
2524
- "use strict";
2525
- var $;
2526
- (function ($) {
2527
- $.$mol_key_store = new WeakMap();
2528
3019
  const TypedArray = Object.getPrototypeOf(Uint8Array);
3020
+ /** Returns string key for any value. */
2529
3021
  function $mol_key(value) {
2530
- if (typeof value === 'bigint')
2531
- return value.toString() + 'n';
2532
- if (typeof value === 'symbol')
2533
- return value.description;
2534
- if (!value)
2535
- return JSON.stringify(value);
2536
- if (typeof value !== 'object' && typeof value !== 'function')
2537
- return JSON.stringify(value);
2538
- return JSON.stringify(value, (field, value) => {
3022
+ primitives: {
2539
3023
  if (typeof value === 'bigint')
2540
3024
  return value.toString() + 'n';
2541
3025
  if (typeof value === 'symbol')
2542
- return value.description;
3026
+ return `Symbol(${value.description})`;
2543
3027
  if (!value)
2544
- return value;
3028
+ return JSON.stringify(value); // 0, null, ""
2545
3029
  if (typeof value !== 'object' && typeof value !== 'function')
2546
- return value;
3030
+ return JSON.stringify(value); // boolean, number, string
3031
+ }
3032
+ caching: {
3033
+ let key = $mol_key_store.get(value);
3034
+ if (key)
3035
+ return key;
3036
+ }
3037
+ objects: {
3038
+ if (value instanceof TypedArray) {
3039
+ return `${value[Symbol.toStringTag]}([${[...value].map(v => $mol_key(v))}])`;
3040
+ }
2547
3041
  if (Array.isArray(value))
2548
- return value;
2549
- const proto = Reflect.getPrototypeOf(value);
2550
- if (!proto)
2551
- return value;
2552
- if (Reflect.getPrototypeOf(proto) === null)
2553
- return value;
2554
- if ('toJSON' in value)
2555
- return value;
3042
+ return `[${value.map(v => $mol_key(v))}]`;
2556
3043
  if (value instanceof RegExp)
2557
3044
  return value.toString();
2558
- if (value instanceof TypedArray)
2559
- return [...value];
2560
- let key = $.$mol_key_store.get(value);
2561
- if (key)
2562
- return key;
2563
- key = $mol_guid();
2564
- $.$mol_key_store.set(value, key);
3045
+ if (value instanceof Date)
3046
+ return `Date(${value.valueOf()})`;
3047
+ }
3048
+ structures: {
3049
+ const proto = Reflect.getPrototypeOf(value);
3050
+ if (!proto || !Reflect.getPrototypeOf(proto)) {
3051
+ return `{${Object.entries(value).map(([k, v]) => JSON.stringify(k) + ':' + $mol_key(v))}}`;
3052
+ }
3053
+ }
3054
+ handlers: {
3055
+ if ($mol_key_handle in value) {
3056
+ return value[$mol_key_handle]();
3057
+ }
3058
+ }
3059
+ containers: {
3060
+ const key = JSON.stringify('#' + $mol_guid());
3061
+ $mol_key_store.set(value, key);
2565
3062
  return key;
2566
- });
3063
+ }
2567
3064
  }
2568
3065
  $.$mol_key = $mol_key;
2569
3066
  })($ || ($ = {}));
@@ -2607,6 +3104,9 @@ var $;
2607
3104
  "use strict";
2608
3105
  var $;
2609
3106
  (function ($) {
3107
+ /**
3108
+ * Decorates method to fiber to ensure it is executed only once inside other fiber.
3109
+ */
2610
3110
  function $mol_wire_method(host, field, descr) {
2611
3111
  if (!descr)
2612
3112
  descr = Reflect.getOwnPropertyDescriptor(host, field);
@@ -2639,20 +3139,21 @@ var $;
2639
3139
  "use strict";
2640
3140
  var $;
2641
3141
  (function ($) {
3142
+ /** Long-living fiber. */
2642
3143
  class $mol_wire_atom extends $mol_wire_fiber {
2643
3144
  static solo(host, task) {
2644
- const field = task.name + '<>';
3145
+ const field = task.name + '()';
2645
3146
  const existen = Object.getOwnPropertyDescriptor(host ?? task, field)?.value;
2646
3147
  if (existen)
2647
3148
  return existen;
2648
3149
  const prefix = host?.[Symbol.toStringTag] ?? (host instanceof Function ? $$.$mol_func_name(host) : host);
2649
- const key = prefix + ('.' + field);
3150
+ const key = prefix + ('.' + task.name + '<>');
2650
3151
  const fiber = new $mol_wire_atom(key, task, host, []);
2651
3152
  (host ?? task)[field] = fiber;
2652
3153
  return fiber;
2653
3154
  }
2654
3155
  static plex(host, task, key) {
2655
- const field = task.name + '<>';
3156
+ const field = task.name + '()';
2656
3157
  let dict = Object.getOwnPropertyDescriptor(host ?? task, field)?.value;
2657
3158
  const prefix = host?.[Symbol.toStringTag] ?? (host instanceof Function ? $$.$mol_func_name(host) : host);
2658
3159
  const key_str = $mol_key(key);
@@ -2689,7 +3190,17 @@ var $;
2689
3190
  }
2690
3191
  $mol_wire_atom.watching.add(this);
2691
3192
  }
3193
+ /**
3194
+ * Update atom value through another temp fiber.
3195
+ */
2692
3196
  resync(args) {
3197
+ // enforce pulling tasks abort
3198
+ for (let cursor = this.pub_from; cursor < this.sub_from; cursor += 2) {
3199
+ const pub = this.data[cursor];
3200
+ if (pub && pub instanceof $mol_wire_task) {
3201
+ pub.destructor();
3202
+ }
3203
+ }
2693
3204
  return this.put(this.task.call(this.host, ...args));
2694
3205
  }
2695
3206
  once() {
@@ -2716,8 +3227,15 @@ var $;
2716
3227
  (this.host ?? this.task)[this.field()] = null;
2717
3228
  }
2718
3229
  else {
2719
- ;
2720
- (this.host ?? this.task)[this.field()].delete($mol_key(this.args[0]));
3230
+ const key = $mol_key(this.args[0]);
3231
+ const map = (this.host ?? this.task)[this.field()];
3232
+ if (!map.has(key))
3233
+ this.$.$mol_log3_warn({
3234
+ place: this,
3235
+ message: 'Absent key on destruction',
3236
+ hint: 'Check for $mol_key(key) is not changed',
3237
+ });
3238
+ map.delete(key);
2721
3239
  }
2722
3240
  }
2723
3241
  put(next) {
@@ -2737,7 +3255,7 @@ var $;
2737
3255
  try {
2738
3256
  next[Symbol.toStringTag] = this[Symbol.toStringTag];
2739
3257
  }
2740
- catch {
3258
+ catch { // Promises throw in strict mode
2741
3259
  Object.defineProperty(next, Symbol.toStringTag, { value: this[Symbol.toStringTag] });
2742
3260
  }
2743
3261
  }
@@ -2765,6 +3283,7 @@ var $;
2765
3283
  "use strict";
2766
3284
  var $;
2767
3285
  (function ($) {
3286
+ /** Decorates solo object channel to [mol_wire_atom](../atom/atom.ts). */
2768
3287
  function $mol_wire_solo(host, field, descr) {
2769
3288
  if (!descr)
2770
3289
  descr = Reflect.getOwnPropertyDescriptor(host, field);
@@ -2803,6 +3322,7 @@ var $;
2803
3322
  "use strict";
2804
3323
  var $;
2805
3324
  (function ($) {
3325
+ /** Reactive memoizing multiplexed property decorator. */
2806
3326
  function $mol_wire_plex(host, field, descr) {
2807
3327
  if (!descr)
2808
3328
  descr = Reflect.getOwnPropertyDescriptor(host, field);
@@ -2841,7 +3361,25 @@ var $;
2841
3361
  "use strict";
2842
3362
  var $;
2843
3363
  (function ($) {
3364
+ /**
3365
+ * Reactive memoizing solo property decorator from [mol_wire](../wire/README.md)
3366
+ * @example
3367
+ * '@' $mol_mem
3368
+ * name(next?: string) {
3369
+ * return next ?? 'default'
3370
+ * }
3371
+ * @see https://mol.hyoo.ru/#!section=docs/=qxmh6t_sinbmb
3372
+ */
2844
3373
  $.$mol_mem = $mol_wire_solo;
3374
+ /**
3375
+ * Reactive memoizing multiplexed property decorator [mol_wire](../wire/README.md)
3376
+ * @example
3377
+ * '@' $mol_mem_key
3378
+ * name(id: number, next?: string) {
3379
+ * return next ?? 'default'
3380
+ * }
3381
+ * @see https://mol.hyoo.ru/#!section=docs/=qxmh6t_sinbmb
3382
+ */
2845
3383
  $.$mol_mem_key = $mol_wire_plex;
2846
3384
  })($ || ($ = {}));
2847
3385
 
@@ -2855,104 +3393,115 @@ var $;
2855
3393
  "use strict";
2856
3394
  var $;
2857
3395
  (function ($) {
2858
- $.$mol_dom_context = new $node.jsdom.JSDOM('', { url: 'https://localhost/' }).window;
3396
+ $.$mol_dom_context = new $node.jsdom.JSDOM('', { url: `http://${process.env.DOMAIN || 'localhost'}/` }).window;
2859
3397
  })($ || ($ = {}));
2860
3398
 
2861
3399
  ;
2862
3400
  "use strict";
2863
3401
  var $;
2864
3402
  (function ($) {
2865
- function $mol_wire_solid() {
2866
- let current = $mol_wire_auto();
2867
- if (current.temp)
2868
- current = current.host;
2869
- if (current.reap !== nothing) {
2870
- current?.sub_on(sub, sub.data.length);
3403
+ class $mol_storage extends $mol_object2 {
3404
+ /** Is storage a long term. */
3405
+ static persisted(next) {
3406
+ return false;
3407
+ }
3408
+ /** Total storage quota in bytes. */
3409
+ static total() {
3410
+ return 0;
3411
+ }
3412
+ /** Total storage usage in bytes. */
3413
+ static used() {
3414
+ return 0;
3415
+ }
3416
+ /** Minimum available free space in bytes. */
3417
+ static free() {
3418
+ return this.total() - this.used();
3419
+ }
3420
+ /** Fulfillness of storage. */
3421
+ static portion() {
3422
+ const total = this.total();
3423
+ if (!total)
3424
+ return 1;
3425
+ return this.used() / total;
3426
+ }
3427
+ /**
3428
+ * Fulfillness logarithmic level.
3429
+ * `0` - empty
3430
+ * `1` - half free
3431
+ * `2` - quart free
3432
+ * `Infinity` - fulfilled
3433
+ */
3434
+ static level() {
3435
+ return Math.floor(-Math.log2(1 - this.portion()));
2871
3436
  }
2872
- current.reap = nothing;
2873
3437
  }
2874
- $.$mol_wire_solid = $mol_wire_solid;
2875
- const nothing = () => { };
2876
- const sub = new $mol_wire_pub_sub;
2877
- })($ || ($ = {}));
2878
-
2879
- ;
2880
- "use strict";
2881
- var $;
2882
- (function ($) {
2883
- $.$mol_mem_persist = $mol_wire_solid;
3438
+ $.$mol_storage = $mol_storage;
2884
3439
  })($ || ($ = {}));
2885
3440
 
2886
3441
  ;
2887
3442
  "use strict";
2888
3443
  var $;
2889
3444
  (function ($) {
2890
- function $mol_wire_probe(task, def) {
2891
- const warm = $mol_wire_fiber.warm;
2892
- try {
2893
- $mol_wire_fiber.warm = false;
2894
- const res = task();
2895
- if (res === undefined)
2896
- return def;
2897
- return res;
3445
+ /** State of time moment */
3446
+ class $mol_state_time extends $mol_object {
3447
+ static task(precision, reset) {
3448
+ if (precision) {
3449
+ return new $mol_after_timeout(precision, () => this.task(precision, null));
3450
+ }
3451
+ else {
3452
+ return new $mol_after_frame(() => this.task(precision, null));
3453
+ }
2898
3454
  }
2899
- finally {
2900
- $mol_wire_fiber.warm = warm;
3455
+ static now(precision) {
3456
+ this.task(precision);
3457
+ return Date.now();
2901
3458
  }
2902
3459
  }
2903
- $.$mol_wire_probe = $mol_wire_probe;
2904
- })($ || ($ = {}));
2905
-
2906
- ;
2907
- "use strict";
2908
- var $;
2909
- (function ($) {
2910
- $.$mol_mem_cached = $mol_wire_probe;
3460
+ __decorate([
3461
+ $mol_mem_key
3462
+ ], $mol_state_time, "task", null);
3463
+ __decorate([
3464
+ $mol_mem_key
3465
+ ], $mol_state_time, "now", null);
3466
+ $.$mol_state_time = $mol_state_time;
2911
3467
  })($ || ($ = {}));
2912
3468
 
2913
3469
  ;
2914
3470
  "use strict";
2915
3471
  var $;
2916
3472
  (function ($) {
2917
- class $mol_storage extends $mol_object2 {
2918
- static native() {
2919
- return this.$.$mol_dom_context.navigator.storage ?? {
2920
- persisted: async () => false,
2921
- persist: async () => false,
2922
- estimate: async () => ({}),
2923
- getDirectory: async () => null,
2924
- };
3473
+ class $mol_storage_node extends $mol_storage {
3474
+ static persisted() {
3475
+ return true;
2925
3476
  }
2926
- static persisted(next, cache) {
2927
- $mol_mem_persist();
2928
- if (cache)
2929
- return Boolean(next);
2930
- const native = this.native();
2931
- if (next && !$mol_mem_cached(() => this.persisted())) {
2932
- native.persist().then(actual => {
2933
- setTimeout(() => this.persisted(actual, 'cache'), 5000);
2934
- if (actual)
2935
- this.$.$mol_log3_done({ place: `$mol_storage`, message: `Persist: Yes` });
2936
- else
2937
- this.$.$mol_log3_fail({ place: `$mol_storage`, message: `Persist: No` });
2938
- });
2939
- }
2940
- return next ?? $mol_wire_sync(native).persisted();
3477
+ static stats() {
3478
+ $mol_state_time.now(1000);
3479
+ return $node.fs.statfsSync('.');
2941
3480
  }
2942
- static estimate() {
2943
- return $mol_wire_sync(this.native() ?? {}).estimate();
3481
+ static total() {
3482
+ const { blocks, bsize } = this.stats();
3483
+ return blocks * bsize;
2944
3484
  }
2945
- static dir() {
2946
- return $mol_wire_sync(this.native()).getDirectory();
3485
+ static used() {
3486
+ const { blocks, bfree, bsize } = this.stats();
3487
+ return (blocks - bfree) * bsize;
3488
+ }
3489
+ static free() {
3490
+ const { bfree, bsize } = this.stats();
3491
+ return bfree * bsize;
3492
+ }
3493
+ static portion() {
3494
+ const { blocks, bfree } = this.stats();
3495
+ if (!blocks)
3496
+ return 1;
3497
+ return (blocks - bfree) / blocks;
2947
3498
  }
2948
3499
  }
2949
3500
  __decorate([
2950
3501
  $mol_mem
2951
- ], $mol_storage, "native", null);
2952
- __decorate([
2953
- $mol_mem
2954
- ], $mol_storage, "persisted", null);
2955
- $.$mol_storage = $mol_storage;
3502
+ ], $mol_storage_node, "stats", null);
3503
+ $.$mol_storage_node = $mol_storage_node;
3504
+ $.$mol_storage = $.$mol_storage_node;
2956
3505
  })($ || ($ = {}));
2957
3506
 
2958
3507
  ;
@@ -3019,6 +3568,11 @@ var $;
3019
3568
  "use strict";
3020
3569
  var $;
3021
3570
  (function ($) {
3571
+ /**
3572
+ * Returns closure that returns constant value.
3573
+ * @example
3574
+ * const rnd = $mol_const( Math.random() )
3575
+ */
3022
3576
  function $mol_const(value) {
3023
3577
  const getter = (() => value);
3024
3578
  getter['()'] = value;
@@ -3033,6 +3587,10 @@ var $;
3033
3587
  "use strict";
3034
3588
  var $;
3035
3589
  (function ($) {
3590
+ /**
3591
+ * Decorates method to fiber to ensure it is executed only once inside other fiber from [mol_wire](../wire/README.md)
3592
+ * @see https://mol.hyoo.ru/#!section=docs/=1fcpsq_1wh0h2
3593
+ */
3036
3594
  $.$mol_action = $mol_wire_method;
3037
3595
  })($ || ($ = {}));
3038
3596
 
@@ -3040,6 +3598,7 @@ var $;
3040
3598
  "use strict";
3041
3599
  var $;
3042
3600
  (function ($) {
3601
+ /** Convert a pseudo-synchronous (Suspense API) API to an explicit asynchronous one (for integrating with external systems). */
3043
3602
  function $mol_wire_async(obj) {
3044
3603
  let fiber;
3045
3604
  const temp = $mol_wire_task.getter(obj);
@@ -3066,6 +3625,27 @@ var $;
3066
3625
  $.$mol_wire_async = $mol_wire_async;
3067
3626
  })($ || ($ = {}));
3068
3627
 
3628
+ ;
3629
+ "use strict";
3630
+ var $;
3631
+ (function ($) {
3632
+ /** Run code without state changes */
3633
+ function $mol_wire_probe(task, def) {
3634
+ const warm = $mol_wire_fiber.warm;
3635
+ try {
3636
+ $mol_wire_fiber.warm = false;
3637
+ const res = task();
3638
+ if (res === undefined)
3639
+ return def;
3640
+ return res;
3641
+ }
3642
+ finally {
3643
+ $mol_wire_fiber.warm = warm;
3644
+ }
3645
+ }
3646
+ $.$mol_wire_probe = $mol_wire_probe;
3647
+ })($ || ($ = {}));
3648
+
3069
3649
  ;
3070
3650
  "use strict";
3071
3651
  var $;
@@ -3099,6 +3679,13 @@ var $;
3099
3679
  $.$mol_lock = $mol_lock;
3100
3680
  })($ || ($ = {}));
3101
3681
 
3682
+ ;
3683
+ "use strict";
3684
+ var $;
3685
+ (function ($) {
3686
+ $.$mol_mem_cached = $mol_wire_probe;
3687
+ })($ || ($ = {}));
3688
+
3102
3689
  ;
3103
3690
  "use strict";
3104
3691
  var $;
@@ -3126,13 +3713,20 @@ var $;
3126
3713
  path() { return ''; }
3127
3714
  modes() { return []; }
3128
3715
  write(options) {
3129
- return 0;
3716
+ throw new Error('Not implemented');
3130
3717
  }
3131
3718
  read() {
3132
- return new Uint8Array();
3719
+ throw new Error('Not implemented');
3720
+ }
3721
+ truncate(size) {
3722
+ throw new Error('Not implemented');
3723
+ }
3724
+ flush() {
3725
+ throw new Error('Not implemented');
3726
+ }
3727
+ close() {
3728
+ throw new Error('Not implemented');
3133
3729
  }
3134
- truncate(size) { }
3135
- close() { }
3136
3730
  destructor() {
3137
3731
  this.close();
3138
3732
  }
@@ -3140,18 +3734,43 @@ var $;
3140
3734
  $.$mol_file_transaction = $mol_file_transaction;
3141
3735
  })($ || ($ = {}));
3142
3736
 
3737
+ ;
3738
+ "use strict";
3739
+ var $;
3740
+ (function ($) {
3741
+ /**
3742
+ * Disable reaping of current subscriber
3743
+ */
3744
+ function $mol_wire_solid() {
3745
+ let current = $mol_wire_auto();
3746
+ if (current.temp)
3747
+ current = current.host;
3748
+ if (current.reap !== nothing) {
3749
+ current?.sub_on(sub, sub.data.length);
3750
+ }
3751
+ current.reap = nothing;
3752
+ }
3753
+ $.$mol_wire_solid = $mol_wire_solid;
3754
+ const nothing = () => { };
3755
+ const sub = new $mol_wire_pub_sub;
3756
+ })($ || ($ = {}));
3757
+
3143
3758
  ;
3144
3759
  "use strict";
3145
3760
  var $;
3146
3761
  (function ($) {
3147
3762
  let file_modes;
3148
3763
  (function (file_modes) {
3764
+ /** create if it doesn't already exist */
3149
3765
  file_modes[file_modes["create"] = $node.fs.constants.O_CREAT] = "create";
3766
+ /** truncate to zero size if it already exists */
3150
3767
  file_modes[file_modes["exists_truncate"] = $node.fs.constants.O_TRUNC] = "exists_truncate";
3768
+ /** throw exception if it already exists */
3151
3769
  file_modes[file_modes["exists_fail"] = $node.fs.constants.O_EXCL] = "exists_fail";
3152
3770
  file_modes[file_modes["read_only"] = $node.fs.constants.O_RDONLY] = "read_only";
3153
3771
  file_modes[file_modes["write_only"] = $node.fs.constants.O_WRONLY] = "write_only";
3154
3772
  file_modes[file_modes["read_write"] = $node.fs.constants.O_RDWR] = "read_write";
3773
+ /** data will be appended to the end */
3155
3774
  file_modes[file_modes["append"] = $node.fs.constants.O_APPEND] = "append";
3156
3775
  })(file_modes || (file_modes = {}));
3157
3776
  function mode_mask(modes) {
@@ -3178,6 +3797,9 @@ var $;
3178
3797
  read() {
3179
3798
  return $mol_file_node_buffer_normalize($node.fs.readFileSync(this.descr()));
3180
3799
  }
3800
+ flush() {
3801
+ $node.fs.fsyncSync(this.descr());
3802
+ }
3181
3803
  close() {
3182
3804
  $node.fs.closeSync(this.descr());
3183
3805
  }
@@ -3213,12 +3835,24 @@ var $;
3213
3835
  root() {
3214
3836
  const path = this.path();
3215
3837
  const base = this.constructor.base;
3838
+ // Если путь выше или равен base или если parent такойже как и this - считаем это корнем
3216
3839
  return base.startsWith(path) || this == this.parent();
3217
3840
  }
3218
3841
  stat(next, virt) {
3219
3842
  const path = this.path();
3220
3843
  const parent = this.parent();
3844
+ // Отслеживать проверку наличия родительской папки не стоит до корня диска
3845
+ // Лучше ограничить mam-ом
3221
3846
  if (!this.root()) {
3847
+ /*
3848
+ Если parent папка удалилась, надо ресетнуть все объекты в ней на любой глубине.
3849
+ Например, rm -rf с последующим git pull: parent папка может удалиться, потом создасться,
3850
+ а текущая папка успеет только удалиться до момента выполнения stat.
3851
+ Поэтому parent.exists() не запустит перевычисления, нужна именно parent.version()
3852
+
3853
+ Однако, parent.version() меняется не только при удалении, будет ложное срабатывание
3854
+ С этим придется мириться, красивого решения пока нет.
3855
+ */
3222
3856
  parent.version();
3223
3857
  }
3224
3858
  parent.watcher();
@@ -3232,9 +3866,19 @@ var $;
3232
3866
  if (/([\/\\]\.|___$)/.test(path))
3233
3867
  return;
3234
3868
  const file = this.relative(path.at(-1) === '/' ? path.slice(0, -1) : path);
3869
+ // console.log(type, path)
3870
+ // add (change): добавился файл - у parent надо обновить список sub, если он был заюзан
3871
+ // change, unlink (rename): обновился или удалился файл - ресетим
3872
+ // addDir (change), добавилась папка, у parent обновляем список директорий в sub
3873
+ // дочерние ресетим
3874
+ // unlinkDir (rename), удалилась папка, ресетим ее
3875
+ // stat у всех дочерних обновится сам, т.к. связан с parent.version()
3235
3876
  this.changed.add(file);
3236
3877
  if (!this.watching)
3237
3878
  return;
3879
+ // throttle, пока события поступают не сбрасываем.
3880
+ // аналог awaitWriteFinish из chokidar
3881
+ // интервалы между change-сообщениями модифицируемого файла должны быть меньше watch_debounce
3238
3882
  this.frame?.destructor();
3239
3883
  this.frame = new this.$.$mol_after_timeout(this.watch_debounce(), () => {
3240
3884
  if (!this.watching)
@@ -3243,8 +3887,16 @@ var $;
3243
3887
  $mol_wire_async(this).flush();
3244
3888
  });
3245
3889
  }
3890
+ /**
3891
+ * Должно быть больше, чем время между событиями от вотчера при записи внешним процессом.
3892
+ * Иначе запуск ресетов паралельно с изменением может привести к неконсистентности.
3893
+ */
3246
3894
  static watch_debounce() { return 500; }
3247
3895
  static flush() {
3896
+ // Пока flush работает, вотчер сюда не заходит, но может добавлять новые изменения
3897
+ // на каждом перезапуске они применятся
3898
+ // Пока run выполняется, изменения накапливаются, в конце run вызывается flush
3899
+ // Пока применяются изменения, run должен ожидать конца flush
3248
3900
  for (const file of this.changed) {
3249
3901
  const parent = file.parent();
3250
3902
  try {
@@ -3259,16 +3911,32 @@ var $;
3259
3911
  }
3260
3912
  this.changed.clear();
3261
3913
  this.watching = true;
3914
+ // this.watch_wd?.destructor()
3915
+ // this.watch_wd = null
3262
3916
  }
3263
3917
  static watching = true;
3264
3918
  static lock = new $mol_lock;
3265
3919
  static watch_off(path) {
3266
3920
  this.watching = false;
3921
+ // run должен ожидать конца flush
3267
3922
  this.flush();
3268
3923
  this.watching = false;
3924
+ /*
3925
+ watch запаздывает и событие может прилететь через 3 сек после окончания сайд эффекта
3926
+ поэтому добавляем папку, которую меняет side_effect
3927
+ Когда дойдет до выполнения flush, он ресетнет ее
3928
+
3929
+ Иначе будут лишние срабатывания
3930
+ Например, удалили hyoo/board, watch ресетит и exists начинает отдавать false, срабатывает git clone
3931
+ Сразу после него событие addDir еще не успело прийти,
3932
+ на следующем перезапуске вызывается git pull, т.к.
3933
+ с точки зрения реактивной системы hyoo/board еще не существует.
3934
+ */
3269
3935
  this.changed.add(this.absolute(path));
3270
3936
  }
3937
+ // protected static watch_wd = null as null | $mol_after_timeout
3271
3938
  static unwatched(side_effect, affected_dir) {
3939
+ // ждем, пока выполнится предыдущий unwatched
3272
3940
  const unlock = this.lock.grab();
3273
3941
  this.watch_off(affected_dir);
3274
3942
  try {
@@ -3291,6 +3959,7 @@ var $;
3291
3959
  modified() { return this.stat()?.mtime ?? null; }
3292
3960
  version() {
3293
3961
  const next = this.stat()?.mtime.getTime().toString(36).toUpperCase() ?? '';
3962
+ // console.log('version', next, this.path())
3294
3963
  return next;
3295
3964
  }
3296
3965
  info(path) { return null; }
@@ -3308,15 +3977,19 @@ var $;
3308
3977
  writable(opts) {
3309
3978
  return new WritableStream;
3310
3979
  }
3980
+ // open( ... modes: readonly $mol_file_mode[] ) { return 0 }
3311
3981
  buffer(next) {
3982
+ // Если версия пустая - возвращаем пустой буфер
3312
3983
  let readed = new Uint8Array();
3313
3984
  if (next === undefined) {
3985
+ // Если меняется версия файла, буфер надо перечитать
3314
3986
  if (this.version())
3315
3987
  readed = this.read();
3316
3988
  }
3317
3989
  const prev = $mol_mem_cached(() => this.buffer());
3318
3990
  const changed = prev === undefined || !$mol_compare_array(prev, next ?? readed);
3319
3991
  if (prev !== undefined && changed) {
3992
+ // Логируем, если повторно читаем/пишем и буфер поменялся
3320
3993
  this.$.$mol_log3_rise({
3321
3994
  place: `$mol_file_node.buffer()`,
3322
3995
  message: 'Changed',
@@ -3325,6 +3998,11 @@ var $;
3325
3998
  }
3326
3999
  if (next === undefined)
3327
4000
  return changed ? readed : prev;
4001
+ // Если буфер при записи не поменялся и файл не удаляли перед этим - не записываем новую версию.
4002
+ // Если записывать, это приведет к смене mtime и вотчер снова триггернется, даже если содержимое файла не поменялось.
4003
+ // В этом алгоритме есть изъян.
4004
+ // Если файл записали, потом отключили вотчер, кто-то из вне его поменял, потом включили вотчер, снова записали тот же буфер,
4005
+ // то буфер не запишется на диск, т.к. кэш не консистентен с диском.
3328
4006
  if (!changed && this.exists())
3329
4007
  return prev;
3330
4008
  this.parent().exists(true);
@@ -3360,13 +4038,21 @@ var $;
3360
4038
  }
3361
4039
  return null;
3362
4040
  }
4041
+ // static watch_root = ''
4042
+ // static watcher_warned = false
3363
4043
  watcher() {
4044
+ // const constructor = this.constructor as typeof $mol_file_base
4045
+ // if (! constructor.watcher_warned) {
4046
+ // console.warn(`${constructor}.watcher() not implemented`)
4047
+ // constructor.watcher_warned = true
4048
+ // }
3364
4049
  return {
3365
4050
  destructor() { }
3366
4051
  };
3367
4052
  }
3368
4053
  exists(next) {
3369
4054
  const exists = Boolean(this.stat());
4055
+ // console.log('exists current', exists, 'next', next, this.path())
3370
4056
  if (next === undefined)
3371
4057
  return exists;
3372
4058
  if (next === exists)
@@ -3392,6 +4078,10 @@ var $;
3392
4078
  return match ? match[1].substring(1) : '';
3393
4079
  }
3394
4080
  text(next, virt) {
4081
+ // Если записываем text, и вотчер ресетнул записанный файл,
4082
+ // то надо снова его обновить, вызвать логику, которая делала пуш в text.
4083
+ // Например файл удалили, потом снова создали, версия поменялась - перезаписываем
4084
+ // Если использовать version, то вновь созданный файл, через вотчер запустит свое пересоздание
3395
4085
  if (next !== undefined)
3396
4086
  this.exists();
3397
4087
  return this.text_int(next, virt);
@@ -3416,6 +4106,7 @@ var $;
3416
4106
  if (this.type() !== 'dir')
3417
4107
  return [];
3418
4108
  this.version();
4109
+ // Если дочерний file удалился, список надо обновить
3419
4110
  return this.kids().filter(file => file.exists());
3420
4111
  }
3421
4112
  resolve(path) {
@@ -3560,10 +4251,15 @@ var $;
3560
4251
  watcher(reset) {
3561
4252
  const path = this.path();
3562
4253
  const root = this.root();
4254
+ // Если папки/файла нет, watch упадет с ошибкой
4255
+ // exists обратится к parent.version и parent.watcher
4256
+ // Поэтому у root-папки и выше не надо вызывать exists, иначе поднимется выше base до корня диска
4257
+ // exists вызывать надо, что б пересоздавать вотчер при появлении папки или файла
3563
4258
  if (!root && !this.exists())
3564
4259
  return super.watcher();
3565
4260
  let watcher;
3566
4261
  try {
4262
+ // Между exists и watch файл может удалиться, в любом случае надо обрабатывать ENOENT
3567
4263
  watcher = $node.fs.watch(path);
3568
4264
  }
3569
4265
  catch (error) {
@@ -3573,6 +4269,8 @@ var $;
3573
4269
  if (root || error.code !== 'ENOENT') {
3574
4270
  this.$.$mol_fail_log(error);
3575
4271
  }
4272
+ // Если файла нет - вотчер не создается, создастся потом, когда exists поменяется на true.
4273
+ // Если создание упало с другой ошибкой - не ломаем работу mol_file, деградируем до не реактивной fs.
3576
4274
  return super.watcher();
3577
4275
  }
3578
4276
  watcher.on('change', (type, name) => {
@@ -3584,6 +4282,7 @@ var $;
3584
4282
  watcher.on('error', e => this.$.$mol_fail_log(e));
3585
4283
  let destructed = false;
3586
4284
  watcher.on('close', () => {
4285
+ // Если в процессе работы вотчер сам закрылся, надо его переоткрыть
3587
4286
  if (!destructed)
3588
4287
  setTimeout(() => $mol_wire_async(this).watcher(null), 500);
3589
4288
  });
@@ -3602,6 +4301,8 @@ var $;
3602
4301
  if (this.$.$mol_fail_catch(error)) {
3603
4302
  if (error.code === 'ENOENT')
3604
4303
  return null;
4304
+ if (error.code === 'EPERM')
4305
+ return null;
3605
4306
  error.message += '\n' + path;
3606
4307
  this.$.$mol_fail_hidden(error);
3607
4308
  }
@@ -3805,13 +4506,13 @@ var $;
3805
4506
  };
3806
4507
  }
3807
4508
  static get method() {
3808
- return (obj, name, descr) => {
4509
+ return (obj, name, descr = Reflect.getOwnPropertyDescriptor(obj, name)) => {
3809
4510
  descr.value = this.func(descr.value);
3810
4511
  return descr;
3811
4512
  };
3812
4513
  }
3813
4514
  static get field() {
3814
- return (obj, name, descr) => {
4515
+ return (obj, name, descr = Reflect.getOwnPropertyDescriptor(obj, name)) => {
3815
4516
  descr.get = descr.set = this.func(descr.get);
3816
4517
  return descr;
3817
4518
  };
@@ -3828,10 +4529,10 @@ var $;
3828
4529
  static wrap(task) {
3829
4530
  const store = new WeakMap();
3830
4531
  const fun = function (next) {
3831
- if (next === undefined && store.has(this))
3832
- return store.get(this);
4532
+ if (next === undefined && store.has(this ?? fun))
4533
+ return store.get(this ?? fun);
3833
4534
  const val = task.call(this, next) ?? next;
3834
- store.set(this, val);
4535
+ store.set(this ?? fun, val);
3835
4536
  return val;
3836
4537
  };
3837
4538
  Reflect.defineProperty(fun, 'name', { value: task.name + ' ' });
@@ -3845,10 +4546,12 @@ var $;
3845
4546
  "use strict";
3846
4547
  var $;
3847
4548
  (function ($) {
4549
+ /** Internal int31 representation of current time. */
3848
4550
  function $hyoo_crowd_time_now() {
3849
4551
  return Math.floor(Date.now() / 100) - 1767e7;
3850
4552
  }
3851
4553
  $.$hyoo_crowd_time_now = $hyoo_crowd_time_now;
4554
+ /** Returns unix timestamp for internal time representation. */
3852
4555
  function $hyoo_crowd_time_stamp(time) {
3853
4556
  return 1767e9 + time * 100;
3854
4557
  }
@@ -3859,8 +4562,10 @@ var $;
3859
4562
  "use strict";
3860
4563
  var $;
3861
4564
  (function ($) {
4565
+ /** Vector clock. Stores real timestamps. */
3862
4566
  class $hyoo_crowd_clock extends Map {
3863
4567
  static begin = -1 * 2 ** 30;
4568
+ /** Maximum time for all peers. */
3864
4569
  last_time = $hyoo_crowd_clock.begin;
3865
4570
  constructor(entries) {
3866
4571
  super(entries);
@@ -3870,16 +4575,19 @@ var $;
3870
4575
  this.see_time(time);
3871
4576
  }
3872
4577
  }
4578
+ /** Synchronize this clock with another. */
3873
4579
  sync(right) {
3874
4580
  for (const [peer, time] of right) {
3875
4581
  this.see_peer(peer, time);
3876
4582
  }
3877
4583
  }
4584
+ /** Increase `last` to latest. */
3878
4585
  see_time(time) {
3879
4586
  if (time < this.last_time)
3880
4587
  return;
3881
4588
  this.last_time = time;
3882
4589
  }
4590
+ /** Add new `time` for `peer` and increase `last`. */
3883
4591
  see_peer(peer, time) {
3884
4592
  if (!this.fresh(peer, time))
3885
4593
  return;
@@ -3894,9 +4602,11 @@ var $;
3894
4602
  }), bin.getInt32(cursor + 8 + 4 * group, true));
3895
4603
  }
3896
4604
  }
4605
+ /** Checks if time from future. */
3897
4606
  fresh(peer, time) {
3898
4607
  return time > this.time(peer);
3899
4608
  }
4609
+ /** Checks if this clock from future of another. */
3900
4610
  ahead(clock) {
3901
4611
  for (const [peer, time] of this) {
3902
4612
  if (clock.fresh(peer, time))
@@ -3913,6 +4623,7 @@ var $;
3913
4623
  last_stamp() {
3914
4624
  return $hyoo_crowd_time_stamp(this.last_time);
3915
4625
  }
4626
+ /** Gererates new time for peer that greater then other seen. */
3916
4627
  tick(peer) {
3917
4628
  let time = this.now();
3918
4629
  if (time <= this.last_time) {
@@ -3969,6 +4680,7 @@ var $;
3969
4680
  "use strict";
3970
4681
  var $;
3971
4682
  (function ($) {
4683
+ /** Stateless non-unique adapter to CROWD Tree for given Head. */
3972
4684
  class $hyoo_crowd_node extends $mol_object2 {
3973
4685
  land;
3974
4686
  head;
@@ -3991,16 +4703,20 @@ var $;
3991
4703
  world() {
3992
4704
  return this.land.world();
3993
4705
  }
4706
+ /** Returns another representation of this node. */
3994
4707
  as(Node) {
3995
4708
  return this.world()?.Fund(Node).Item(`${this.land.id()}!${this.head}`) ?? new Node(this.land, this.head);
3996
4709
  }
4710
+ /** Ordered inner alive Units. */
3997
4711
  units() {
3998
4712
  return this.land.unit_alives(this.head);
3999
4713
  }
4714
+ /** Ordered inner alive Node. */
4000
4715
  nodes(Node) {
4001
4716
  const fund = this.world()?.Fund(Node);
4002
4717
  return this.units().map(unit => fund?.Item(`${this.land.id()}!${unit.self}`) ?? new Node(this.land, unit.self));
4003
4718
  }
4719
+ /** Returns true when node value is never changed. */
4004
4720
  virgin() {
4005
4721
  return this.land.unit_list(this.head).length === 0;
4006
4722
  }
@@ -4028,6 +4744,7 @@ var $;
4028
4744
  var $;
4029
4745
  (function ($) {
4030
4746
  class $hyoo_crowd_reg extends $hyoo_crowd_node {
4747
+ /** Atomic value. */
4031
4748
  value(next) {
4032
4749
  const unit = this.units().at(-1);
4033
4750
  if (next === undefined)
@@ -4037,12 +4754,15 @@ var $;
4037
4754
  this.land.put(this.head, unit?.self ?? this.land.id_new(), '0_0', next);
4038
4755
  return next;
4039
4756
  }
4757
+ /** Atomic string. */
4040
4758
  str(next) {
4041
4759
  return String(this.value(next) ?? '');
4042
4760
  }
4761
+ /** Atomic number. */
4043
4762
  numb(next) {
4044
4763
  return Number(this.value(next));
4045
4764
  }
4765
+ /** Atomic boolean. */
4046
4766
  bool(next) {
4047
4767
  return Boolean(this.value(next));
4048
4768
  }
@@ -4067,6 +4787,7 @@ var $;
4067
4787
  var $;
4068
4788
  (function ($) {
4069
4789
  class $hyoo_crowd_struct extends $hyoo_crowd_node {
4790
+ /** Returns inner node for key. */
4070
4791
  sub(key, Node) {
4071
4792
  const head = $mol_int62_hash_string(key + '\n' + this.head);
4072
4793
  return this.world()?.Fund(Node).Item(`${this.land.id()}!${head}`) ?? new Node(this.land, head);
@@ -4083,6 +4804,7 @@ var $;
4083
4804
  "use strict";
4084
4805
  var $;
4085
4806
  (function ($) {
4807
+ /** Conflict-free Reinterpretable Ordered Washed Data Tree */
4086
4808
  class $hyoo_crowd_land extends $mol_object {
4087
4809
  id() {
4088
4810
  return $mol_int62_to_string($mol_int62_random());
@@ -4116,21 +4838,26 @@ var $;
4116
4838
  }
4117
4839
  pub = new $mol_wire_pub;
4118
4840
  _clocks = [new $hyoo_crowd_clock, new $hyoo_crowd_clock];
4841
+ /** unit by head + self */
4119
4842
  _unit_all = new Map();
4120
4843
  unit(head, self) {
4121
4844
  return this._unit_all.get(`${head}!${self}`);
4122
4845
  }
4846
+ /** units by head */
4123
4847
  _unit_lists = new Map();
4848
+ /** Units by Head without tombstones */
4124
4849
  _unit_alives = new Map();
4125
4850
  size() {
4126
4851
  return this._unit_all.size;
4127
4852
  }
4853
+ /** Returns list of all Units for Node. */
4128
4854
  unit_list(head) {
4129
4855
  let kids = this._unit_lists.get(head);
4130
4856
  if (!kids)
4131
4857
  this._unit_lists.set(head, kids = Object.assign([], { dirty: false }));
4132
4858
  return kids;
4133
4859
  }
4860
+ /** Returns list of alive Units for Node. */
4134
4861
  unit_alives(head) {
4135
4862
  this.pub.promote();
4136
4863
  let kids = this._unit_alives.get(head);
@@ -4143,23 +4870,27 @@ var $;
4143
4870
  }
4144
4871
  return kids;
4145
4872
  }
4873
+ /** Node by id and type. */
4146
4874
  node(head, Node) {
4147
4875
  return new Node(this, head);
4148
4876
  }
4877
+ /** Root Node. */
4149
4878
  chief = this.node('0_0', $hyoo_crowd_struct);
4879
+ /** Generates new identifier. */
4150
4880
  id_new() {
4151
4881
  for (let i = 0; i < 1000; ++i) {
4152
4882
  const id = $mol_int62_to_string($mol_int62_random());
4153
4883
  if (id === '0_0')
4154
- continue;
4884
+ continue; // zero reserved for empty
4155
4885
  if (id === this.id())
4156
- continue;
4886
+ continue; // reserved for rights
4157
4887
  if (this._unit_lists.has(id))
4158
- continue;
4888
+ continue; // skip already exists
4159
4889
  return id;
4160
4890
  }
4161
4891
  throw new Error(`Can't generate ID after 1000 times`);
4162
4892
  }
4893
+ /** Makes independent clone with defined peer. */
4163
4894
  fork(auth) {
4164
4895
  const fork = $hyoo_crowd_land.make({
4165
4896
  id: $mol_const(this.id()),
@@ -4167,6 +4898,7 @@ var $;
4167
4898
  });
4168
4899
  return fork.apply(this.delta());
4169
4900
  }
4901
+ /** Makes Delta bettween Clock and now. */
4170
4902
  delta(clocks = [new $hyoo_crowd_clock, new $hyoo_crowd_clock]) {
4171
4903
  this.pub.promote();
4172
4904
  const delta = [];
@@ -4227,6 +4959,7 @@ var $;
4227
4959
  kids.dirty = false;
4228
4960
  return kids;
4229
4961
  }
4962
+ /** Applies Delta to current state. */
4230
4963
  apply(delta) {
4231
4964
  for (const next of delta) {
4232
4965
  this._clocks[next.group()].see_peer(next.auth, next.time);
@@ -4250,6 +4983,7 @@ var $;
4250
4983
  return this;
4251
4984
  }
4252
4985
  _joined = false;
4986
+ /** Register public key of current peer **/
4253
4987
  join() {
4254
4988
  if (this._joined)
4255
4989
  return;
@@ -4268,6 +5002,7 @@ var $;
4268
5002
  this._joined = true;
4269
5003
  this.pub.emit();
4270
5004
  }
5005
+ /** Unregister public key of current peer **/
4271
5006
  leave() {
4272
5007
  const auth = this.peer();
4273
5008
  if (!auth)
@@ -4296,6 +5031,7 @@ var $;
4296
5031
  level_base(next) {
4297
5032
  this.level('0_0', next);
4298
5033
  }
5034
+ /** Access level for peer. Use empty string for current peer. **/
4299
5035
  level(peer, next) {
4300
5036
  if (next)
4301
5037
  this.join();
@@ -4326,6 +5062,7 @@ var $;
4326
5062
  this.pub.promote();
4327
5063
  return this._unit_all.size > 0;
4328
5064
  }
5065
+ /** All peers who have special rights to write o land. */
4329
5066
  peers() {
4330
5067
  this.pub.promote();
4331
5068
  const lords = [];
@@ -4338,6 +5075,7 @@ var $;
4338
5075
  }
4339
5076
  return lords;
4340
5077
  }
5078
+ /** All peers who joined to land except king. */
4341
5079
  residents() {
4342
5080
  this.pub.promote();
4343
5081
  const lords = [];
@@ -4350,6 +5088,7 @@ var $;
4350
5088
  }
4351
5089
  return lords;
4352
5090
  }
5091
+ /** All peers who have alive data inside land. */
4353
5092
  authors() {
4354
5093
  this.pub.promote();
4355
5094
  const authors = new Set();
@@ -4381,6 +5120,7 @@ var $;
4381
5120
  selection(peer) {
4382
5121
  return this.world().land_sync(peer).chief.sub('$hyoo_crowd_land..selection', $hyoo_crowd_reg);
4383
5122
  }
5123
+ /** Places data to tree. */
4384
5124
  put(head, self, prev, data) {
4385
5125
  this.join();
4386
5126
  const old_id = `${head}!${self}`;
@@ -4398,18 +5138,25 @@ var $;
4398
5138
  const unit_new = new $hyoo_crowd_unit(this.id(), auth, head, self, next, prev, time, data, null);
4399
5139
  this._unit_all.set(old_id, unit_new);
4400
5140
  unit_list.splice(seat, 0, unit_new);
5141
+ // unit_list.dirty = true
4401
5142
  this._unit_alives.set(head, undefined);
5143
+ // this.apply([ unit_new ])
4402
5144
  this.pub.emit();
4403
5145
  return unit_new;
4404
5146
  }
5147
+ /** Marks unit as deleted and wipes its data. */
4405
5148
  wipe(unit) {
4406
5149
  if (unit.data === null)
4407
5150
  return unit;
5151
+ // for( const kid of this.unit_list( unit.self ) ) {
5152
+ // this.wipe( kid )
5153
+ // }
4408
5154
  const unit_list = this.unit_list(unit.head);
4409
5155
  const seat = unit_list.indexOf(unit);
4410
5156
  const prev = seat > 0 ? unit_list[seat - 1].self : seat < 0 ? unit.prev : '0_0';
4411
5157
  return this.put(unit.head, unit.self, prev, null);
4412
5158
  }
5159
+ /** Moves Unit after another Prev inside some Head. */
4413
5160
  move(unit, head, prev) {
4414
5161
  const unit_list = this.unit_list(unit.head);
4415
5162
  const seat = unit_list.indexOf(unit);
@@ -4419,6 +5166,7 @@ var $;
4419
5166
  this.put(next.head, next.self, unit_list[unit_list.indexOf(next) - 2]?.self ?? '0_0', next.data);
4420
5167
  this.put(head, unit.self, prev, unit.data);
4421
5168
  }
5169
+ /** Moves Unit at given Seat inside given Head. */
4422
5170
  insert(unit, head, seat) {
4423
5171
  const list = this.unit_list(head);
4424
5172
  const prev = seat ? list[seat - 1].self : '0_0';
@@ -4438,6 +5186,7 @@ var $;
4438
5186
  "use strict";
4439
5187
  var $;
4440
5188
  (function ($) {
5189
+ /** Registry of nodes as domain entities. */
4441
5190
  class $hyoo_crowd_fund extends $mol_object {
4442
5191
  world;
4443
5192
  node_class;
@@ -4470,7 +5219,11 @@ var $;
4470
5219
  "use strict";
4471
5220
  var $;
4472
5221
  (function ($) {
5222
+ /** @deprecated */
4473
5223
  $.$mol_dict_key = $mol_key;
5224
+ /**
5225
+ * Dictionary with extended keys support
5226
+ */
4474
5227
  class $mol_dict extends Map {
4475
5228
  get(key) {
4476
5229
  return super.get($mol_key(key));
@@ -4517,6 +5270,7 @@ var $;
4517
5270
  if (iteration.done)
4518
5271
  return iteration;
4519
5272
  iteration.value = [JSON.parse(iteration.value[0]), iteration.value[1]];
5273
+ // iteration.value[0] = JSON.parse( iteration.value[0] as any as string )
4520
5274
  return iteration;
4521
5275
  }
4522
5276
  };
@@ -4573,6 +5327,7 @@ var $;
4573
5327
  _knights = new $mol_dict();
4574
5328
  _signs = new WeakMap();
4575
5329
  async grab(law = [''], mod = [], add = []) {
5330
+ // if( !law.length && !mod.length && !add.length ) $mol_fail( new Error( 'Grabbing dead land' ) )
4576
5331
  const knight = await $hyoo_crowd_peer.generate();
4577
5332
  this._knights.set(knight.id, knight);
4578
5333
  const land_inner = this.land(knight.id);
@@ -4653,7 +5408,7 @@ var $;
4653
5408
  }
4654
5409
  async audit_delta(land, delta) {
4655
5410
  const all = new Map();
4656
- const desync = 60 * 60 * 10;
5411
+ const desync = 60 * 60 * 10; // 1 hour
4657
5412
  const deadline = land.clock_data.now() + desync;
4658
5413
  const get_unit = (id) => {
4659
5414
  return all.get(id) ?? land._unit_all.get(id);
@@ -4792,6 +5547,7 @@ var $;
4792
5547
  "use strict";
4793
5548
  var $;
4794
5549
  (function ($) {
5550
+ /** Starts subtasks concurrently instead of serial. */
4795
5551
  function $mol_wire_race(...tasks) {
4796
5552
  const results = tasks.map(task => {
4797
5553
  try {
@@ -4818,7 +5574,7 @@ var $;
4818
5574
  (function ($) {
4819
5575
  $.$hyoo_sync_masters = [
4820
5576
  `sync.hyoo.ru`,
4821
- `sync-pmzz.onrender.com`,
5577
+ //`sync-pmzz.onrender.com`,
4822
5578
  ];
4823
5579
  })($ || ($ = {}));
4824
5580
 
@@ -4939,6 +5695,12 @@ var $;
4939
5695
  $mol_wire_sync(this).db_land_save(land, units);
4940
5696
  for (const unit of units)
4941
5697
  this.db_unit_persisted.add(unit);
5698
+ // this.$.$mol_log3_rise({
5699
+ // place: this,
5700
+ // land: land.id(),
5701
+ // message: 'Base Save',
5702
+ // units: this.log_pack( units ),
5703
+ // })
4942
5704
  }
4943
5705
  db_land_init(land) {
4944
5706
  try {
@@ -4958,6 +5720,12 @@ var $;
4958
5720
  this.db_unit_persisted.add(unit);
4959
5721
  units.sort($hyoo_crowd_unit_compare);
4960
5722
  land.apply(units);
5723
+ // this.$.$mol_log3_rise({
5724
+ // place: this,
5725
+ // land: land.id(),
5726
+ // message: 'Base Load',
5727
+ // units: this.log_pack( units ),
5728
+ // })
4961
5729
  }
4962
5730
  async db_land_load(land) {
4963
5731
  return [];
@@ -4990,6 +5758,11 @@ var $;
4990
5758
  }
4991
5759
  line_land_clocks({ line, land }, next) {
4992
5760
  $mol_wire_solid();
5761
+ // try{
5762
+ // this.master()
5763
+ // } catch( error ) {
5764
+ // $mol_fail_log( error )
5765
+ // }
4993
5766
  return next;
4994
5767
  }
4995
5768
  line_sync(line) {
@@ -5004,13 +5777,29 @@ var $;
5004
5777
  if (!units.length)
5005
5778
  return;
5006
5779
  this.line_send_units(line, units);
5780
+ /*this.$.$mol_log3_rise({
5781
+ place: this,
5782
+ land: land.id(),
5783
+ message: 'Sync Sent',
5784
+ line: $mol_key( line ),
5785
+ units: this.log_pack( units ),
5786
+ })*/
5007
5787
  for (const unit of units) {
5008
5788
  clocks[unit.group()].see_peer(unit.auth, unit.time);
5009
5789
  }
5010
5790
  }
5011
5791
  line_land_init({ line, land }) {
5012
5792
  this.db_land_init(land);
5793
+ // const lands = this.line_land_clocks({ line, land })
5794
+ // if( lands ) return
5013
5795
  this.line_send_clocks(line, land);
5796
+ // this.$.$mol_log3_come({
5797
+ // place: this,
5798
+ // land: land.id(),
5799
+ // message: 'Sync Open',
5800
+ // line: $mol_key( line ),
5801
+ // clocks: land._clocks,
5802
+ // })
5014
5803
  }
5015
5804
  line_land_neck({ line, land }, next = []) {
5016
5805
  return next;
@@ -5054,6 +5843,13 @@ var $;
5054
5843
  }
5055
5844
  else {
5056
5845
  this.line_lands(line, [...lands, land]);
5846
+ // this.$.$mol_log3_done({
5847
+ // place: this,
5848
+ // land: land.id(),
5849
+ // message: 'Sync Pair',
5850
+ // line: $mol_key( line ),
5851
+ // clocks,
5852
+ // })
5057
5853
  }
5058
5854
  return;
5059
5855
  }
@@ -5158,6 +5954,7 @@ var $;
5158
5954
  "use strict";
5159
5955
  var $;
5160
5956
  (function ($) {
5957
+ /** Converts IDBResult to Promise */
5161
5958
  function $mol_db_response(request) {
5162
5959
  return new Promise((done, fail) => {
5163
5960
  request.onerror = () => fail(new Error(request.error.message));
@@ -5171,6 +5968,14 @@ var $;
5171
5968
  "use strict";
5172
5969
  var $;
5173
5970
  (function ($) {
5971
+ /**
5972
+ * Creates new or returns existen database with automatic schema migration.
5973
+ * Schema version is based on migrations count.
5974
+ * Migrations code mustn't be changed after deploy.
5975
+ * Only adding migrations at the end is allowed.
5976
+ * Only new migrations will be applyed to existen DB.
5977
+ * Schema changes allowed only through migratios.
5978
+ */
5174
5979
  async function $mol_db(name, ...migrations) {
5175
5980
  const request = this.$mol_dom_context.indexedDB.open(name, migrations.length ? migrations.length + 1 : undefined);
5176
5981
  request.onupgradeneeded = event => {
@@ -5189,6 +5994,7 @@ var $;
5189
5994
  "use strict";
5190
5995
  var $;
5191
5996
  (function ($) {
5997
+ /** IndexedDB ObjectStore wrapper. */
5192
5998
  class $mol_db_store {
5193
5999
  native;
5194
6000
  constructor(native) {
@@ -5203,6 +6009,7 @@ var $;
5203
6009
  get incremental() {
5204
6010
  return this.native.autoIncrement;
5205
6011
  }
6012
+ /** Returns dictionary of all existen Indexes. */
5206
6013
  get indexes() {
5207
6014
  return new Proxy({}, {
5208
6015
  ownKeys: () => [...this.native.indexNames],
@@ -5210,9 +6017,11 @@ var $;
5210
6017
  get: (_, name) => new $mol_db_index(this.native.index(name))
5211
6018
  });
5212
6019
  }
6020
+ /** Creates new Index */
5213
6021
  index_make(name, path = [], unique = false, multiEntry = false) {
5214
6022
  return this.native.createIndex(name, path, { multiEntry, unique });
5215
6023
  }
6024
+ /** Drops existen Index */
5216
6025
  index_drop(name) {
5217
6026
  this.native.deleteIndex(name);
5218
6027
  return this;
@@ -5223,21 +6032,27 @@ var $;
5223
6032
  get db() {
5224
6033
  return this.transaction.db;
5225
6034
  }
6035
+ /** Deletes all stored Documents */
5226
6036
  clear() {
5227
6037
  return $mol_db_response(this.native.clear());
5228
6038
  }
6039
+ /** Counts Documents by primary key(s) */
5229
6040
  count(keys) {
5230
6041
  return $mol_db_response(this.native.count(keys));
5231
6042
  }
6043
+ /** Stores single Document by primary key. */
5232
6044
  put(doc, key) {
5233
6045
  return $mol_db_response(this.native.put(doc, key));
5234
6046
  }
6047
+ /** Returns Document by primary key. */
5235
6048
  get(key) {
5236
6049
  return $mol_db_response(this.native.get(key));
5237
6050
  }
6051
+ /** Selects Documents by primary keys. */
5238
6052
  select(key, count) {
5239
6053
  return $mol_db_response(this.native.getAll(key, count));
5240
6054
  }
6055
+ /** Deletes Documents by primary key(s). */
5241
6056
  drop(keys) {
5242
6057
  return $mol_db_response(this.native.delete(keys));
5243
6058
  }
@@ -5252,6 +6067,7 @@ var $;
5252
6067
  "use strict";
5253
6068
  var $;
5254
6069
  (function ($) {
6070
+ /** IndexedDB Index wrapper. */
5255
6071
  class $mol_db_index {
5256
6072
  native;
5257
6073
  constructor(native) {
@@ -5278,12 +6094,15 @@ var $;
5278
6094
  get db() {
5279
6095
  return this.store.db;
5280
6096
  }
6097
+ /** Counts Documents by key(s) */
5281
6098
  count(keys) {
5282
6099
  return $mol_db_response(this.native.count(keys));
5283
6100
  }
6101
+ /** Returns Document by primary key. */
5284
6102
  get(key) {
5285
6103
  return $mol_db_response(this.native.get(key));
5286
6104
  }
6105
+ /** Selects Documents by primary keys. */
5287
6106
  select(key, count) {
5288
6107
  return $mol_db_response(this.native.getAll(key, count));
5289
6108
  }
@@ -5319,32 +6138,46 @@ var $;
5319
6138
  "use strict";
5320
6139
  var $;
5321
6140
  (function ($) {
6141
+ /** IndexedDB instance wrapper. */
5322
6142
  class $mol_db_database {
5323
6143
  native;
5324
6144
  constructor(native) {
5325
6145
  this.native = native;
5326
6146
  }
6147
+ /** Returns database name. */
5327
6148
  get name() {
5328
6149
  return this.native.name;
5329
6150
  }
6151
+ /** Returns database schema version. */
5330
6152
  get version() {
5331
6153
  return this.native.version;
5332
6154
  }
6155
+ /** Returns all stores names. */
5333
6156
  get stores() {
5334
6157
  return [...this.native.objectStoreNames];
5335
6158
  }
6159
+ /** Create read-only transaction. */
5336
6160
  read(...names) {
5337
6161
  return new $mol_db_transaction(this.native.transaction(names, 'readonly', { durability: 'relaxed' })).stores;
5338
6162
  }
6163
+ /** Create read/write transaction. */
5339
6164
  change(...names) {
5340
6165
  return new $mol_db_transaction(this.native.transaction(names, 'readwrite', { durability: 'relaxed' }));
5341
6166
  }
6167
+ /**
6168
+ * Deletes database.
6169
+ * DB can be deleted only after end of all transactions.
6170
+ */
5342
6171
  kill() {
5343
6172
  this.native.close();
5344
6173
  const request = $mol_dom_context.indexedDB.deleteDatabase(this.name);
5345
6174
  request.onblocked = console.warn;
5346
6175
  return $mol_db_response(request);
5347
6176
  }
6177
+ /**
6178
+ * Closes DB connection.
6179
+ * Connection really be closed only after end of all transactions.
6180
+ */
5348
6181
  destructor() {
5349
6182
  this.native.close();
5350
6183
  }
@@ -5356,11 +6189,13 @@ var $;
5356
6189
  "use strict";
5357
6190
  var $;
5358
6191
  (function ($) {
6192
+ /** IndexedDB Transaction wrapper. */
5359
6193
  class $mol_db_transaction {
5360
6194
  native;
5361
6195
  constructor(native) {
5362
6196
  this.native = native;
5363
6197
  }
6198
+ /** Returns dictionary of all existen Stores. */
5364
6199
  get stores() {
5365
6200
  return new Proxy({}, {
5366
6201
  ownKeys: () => [...this.native.objectStoreNames],
@@ -5370,18 +6205,22 @@ var $;
5370
6205
  : undefined,
5371
6206
  });
5372
6207
  }
6208
+ /** Creates new Store */
5373
6209
  store_make(name) {
5374
6210
  return this.native.db.createObjectStore(name, { autoIncrement: true });
5375
6211
  }
6212
+ /** Drops existen Store */
5376
6213
  store_drop(name) {
5377
6214
  this.native.db.deleteObjectStore(name);
5378
6215
  return this;
5379
6216
  }
6217
+ /** Instant abort transaction. Any errors aborts transactions automatically. */
5380
6218
  abort() {
5381
6219
  if (this.native.error)
5382
6220
  return;
5383
6221
  this.native.abort();
5384
6222
  }
6223
+ /** Instant commits transaction. Without errors commit proceed automatically later. */
5385
6224
  commit() {
5386
6225
  this.native.commit?.();
5387
6226
  return new Promise((done, fail) => {
@@ -5502,6 +6341,29 @@ var $;
5502
6341
  };
5503
6342
  });
5504
6343
  }
6344
+ // @ $mol_mem
6345
+ // server() {
6346
+ // return new $mol_dom_listener(
6347
+ // $mol_dom_context,
6348
+ // 'message',
6349
+ // $mol_wire_async( ( event: MessageEvent<[ string, $mol_int62_string, readonly $hyoo_crowd_unit[] ]> )=> {
6350
+ // if( !event ) return
6351
+ // if( !Array.isArray( event.data ) ) return
6352
+ // switch( event.data[0] ) {
6353
+ // case 'hyoo_sync_units': {
6354
+ // const [, land_id, units ] = event.data
6355
+ // const line = event.source! as Window
6356
+ // const land = this.land( land_id )
6357
+ // land.apply( units )
6358
+ // this.slaves([ ... new Set([ ... this.slaves(), line ]) ])
6359
+ // this.line_lands( line, [ ... new Set([ ... this.line_lands( line ), land ]) ] )
6360
+ // this.line_land_clocks({ line, land })
6361
+ // line.postMessage([ 'hyoo_sync_units', land.id(), [] ])
6362
+ // }
6363
+ // }
6364
+ // } )
6365
+ // )
6366
+ // }
5505
6367
  line_send_clocks(line, land) {
5506
6368
  if (line instanceof WebSocket) {
5507
6369
  line.send(land.clocks_bin);