dexie-cloud-addon 4.0.7 → 4.1.0-alpha.10
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/dist/modern/DexieCloudOptions.d.ts +4 -2
- package/dist/modern/WSObservable.d.ts +9 -6
- package/dist/modern/db/DexieCloudDB.d.ts +2 -0
- package/dist/modern/db/entities/PersistedSyncState.d.ts +7 -0
- package/dist/modern/dexie-cloud-addon.js +1752 -79
- package/dist/modern/dexie-cloud-addon.js.map +1 -1
- package/dist/modern/dexie-cloud-addon.min.js +1 -1
- package/dist/modern/dexie-cloud-addon.min.js.map +1 -1
- package/dist/modern/service-worker.js +1752 -79
- package/dist/modern/service-worker.js.map +1 -1
- package/dist/modern/service-worker.min.js +1 -1
- package/dist/modern/service-worker.min.js.map +1 -1
- package/dist/modern/sync/DEXIE_CLOUD_SYNCER_ID.d.ts +1 -0
- package/dist/modern/sync/syncWithServer.d.ts +2 -2
- package/dist/modern/yjs/Y.d.ts +3 -0
- package/dist/modern/yjs/YDexieCloudSyncState.d.ts +4 -0
- package/dist/modern/yjs/YTable.d.ts +2 -0
- package/dist/modern/yjs/applyYMessages.d.ts +5 -0
- package/dist/modern/yjs/awareness.d.ts +4 -0
- package/dist/modern/yjs/createYClientUpdateObservable.d.ts +4 -0
- package/dist/modern/yjs/createYHandler.d.ts +5 -0
- package/dist/modern/yjs/downloadYDocsFromServer.d.ts +3 -0
- package/dist/modern/yjs/getUpdatesTable.d.ts +3 -0
- package/dist/modern/yjs/listUpdatesSince.d.ts +2 -0
- package/dist/modern/yjs/listYClientMessagesAndStateVector.d.ts +26 -0
- package/dist/modern/yjs/updateYSyncStates.d.ts +6 -0
- package/dist/umd/DexieCloudOptions.d.ts +4 -2
- package/dist/umd/WSObservable.d.ts +9 -6
- package/dist/umd/db/DexieCloudDB.d.ts +2 -0
- package/dist/umd/db/entities/PersistedSyncState.d.ts +7 -0
- package/dist/umd/dexie-cloud-addon.js +1750 -77
- package/dist/umd/dexie-cloud-addon.js.map +1 -1
- package/dist/umd/dexie-cloud-addon.min.js +1 -1
- package/dist/umd/dexie-cloud-addon.min.js.map +1 -1
- package/dist/umd/service-worker.js +1750 -77
- package/dist/umd/service-worker.js.map +1 -1
- package/dist/umd/service-worker.min.js +1 -1
- package/dist/umd/service-worker.min.js.map +1 -1
- package/dist/umd/sync/DEXIE_CLOUD_SYNCER_ID.d.ts +1 -0
- package/dist/umd/sync/syncWithServer.d.ts +2 -2
- package/dist/umd/yjs/Y.d.ts +3 -0
- package/dist/umd/yjs/YDexieCloudSyncState.d.ts +4 -0
- package/dist/umd/yjs/YTable.d.ts +2 -0
- package/dist/umd/yjs/applyYMessages.d.ts +5 -0
- package/dist/umd/yjs/awareness.d.ts +4 -0
- package/dist/umd/yjs/createYClientUpdateObservable.d.ts +4 -0
- package/dist/umd/yjs/createYHandler.d.ts +5 -0
- package/dist/umd/yjs/downloadYDocsFromServer.d.ts +3 -0
- package/dist/umd/yjs/getUpdatesTable.d.ts +3 -0
- package/dist/umd/yjs/listUpdatesSince.d.ts +2 -0
- package/dist/umd/yjs/listYClientMessagesAndStateVector.d.ts +26 -0
- package/dist/umd/yjs/updateYSyncStates.d.ts +6 -0
- package/package.json +5 -4
- package/dist/modern/helpers/dbOnClosed.d.ts +0 -2
- package/dist/umd/helpers/dbOnClosed.d.ts +0 -2
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*
|
|
9
9
|
* ==========================================================================
|
|
10
10
|
*
|
|
11
|
-
* Version 4.0.
|
|
11
|
+
* Version 4.1.0-alpha.10, Wed Oct 16 2024
|
|
12
12
|
*
|
|
13
13
|
* https://dexie.org
|
|
14
14
|
*
|
|
@@ -16,8 +16,8 @@
|
|
|
16
16
|
*
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
-
import Dexie, { PropModification, cmp, liveQuery } from 'dexie';
|
|
20
|
-
import { firstValueFrom, from as from$1, filter as filter$1, Observable as Observable$1, BehaviorSubject, Subject, fromEvent, of, merge, Subscription as Subscription$1, throwError, combineLatest, map as map$1, share, timer as timer$1 } from 'rxjs';
|
|
19
|
+
import Dexie, { PropModification, cmp, DexieYProvider, liveQuery } from 'dexie';
|
|
20
|
+
import { firstValueFrom, from as from$1, filter as filter$1, Observable as Observable$1, BehaviorSubject, Subject, fromEvent, of, merge, switchMap as switchMap$1, tap as tap$1, mergeMap as mergeMap$1, Subscription as Subscription$1, throwError, combineLatest, map as map$1, share, timer as timer$1 } from 'rxjs';
|
|
21
21
|
|
|
22
22
|
/******************************************************************************
|
|
23
23
|
Copyright (c) Microsoft Corporation.
|
|
@@ -467,6 +467,1075 @@ function getDbNameFromDbUrl(dbUrl) {
|
|
|
467
467
|
: url.pathname.split('/')[1];
|
|
468
468
|
}
|
|
469
469
|
|
|
470
|
+
/**
|
|
471
|
+
* Common Math expressions.
|
|
472
|
+
*
|
|
473
|
+
* @module math
|
|
474
|
+
*/
|
|
475
|
+
|
|
476
|
+
const floor = Math.floor;
|
|
477
|
+
const abs = Math.abs;
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* @function
|
|
481
|
+
* @param {number} a
|
|
482
|
+
* @param {number} b
|
|
483
|
+
* @return {number} The smaller element of a and b
|
|
484
|
+
*/
|
|
485
|
+
const min = (a, b) => a < b ? a : b;
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* @function
|
|
489
|
+
* @param {number} a
|
|
490
|
+
* @param {number} b
|
|
491
|
+
* @return {number} The bigger element of a and b
|
|
492
|
+
*/
|
|
493
|
+
const max = (a, b) => a > b ? a : b;
|
|
494
|
+
|
|
495
|
+
/**
|
|
496
|
+
* @param {number} n
|
|
497
|
+
* @return {boolean} Wether n is negative. This function also differentiates between -0 and +0
|
|
498
|
+
*/
|
|
499
|
+
const isNegativeZero = n => n !== 0 ? n < 0 : 1 / n < 0;
|
|
500
|
+
|
|
501
|
+
/* eslint-env browser */
|
|
502
|
+
|
|
503
|
+
const BIT7 = 64;
|
|
504
|
+
const BIT8 = 128;
|
|
505
|
+
const BITS6 = 63;
|
|
506
|
+
const BITS7 = 127;
|
|
507
|
+
/**
|
|
508
|
+
* @type {number}
|
|
509
|
+
*/
|
|
510
|
+
const BITS31 = 0x7FFFFFFF;
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Utility helpers for working with numbers.
|
|
514
|
+
*
|
|
515
|
+
* @module number
|
|
516
|
+
*/
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
|
|
520
|
+
|
|
521
|
+
/* c8 ignore next */
|
|
522
|
+
const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && floor(num) === num);
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Utility module to work with Arrays.
|
|
526
|
+
*
|
|
527
|
+
* @module array
|
|
528
|
+
*/
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
const isArray = Array.isArray;
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* @param {string} str
|
|
535
|
+
* @return {Uint8Array}
|
|
536
|
+
*/
|
|
537
|
+
const _encodeUtf8Polyfill = str => {
|
|
538
|
+
const encodedString = unescape(encodeURIComponent(str));
|
|
539
|
+
const len = encodedString.length;
|
|
540
|
+
const buf = new Uint8Array(len);
|
|
541
|
+
for (let i = 0; i < len; i++) {
|
|
542
|
+
buf[i] = /** @type {number} */ (encodedString.codePointAt(i));
|
|
543
|
+
}
|
|
544
|
+
return buf
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
/* c8 ignore next */
|
|
548
|
+
const utf8TextEncoder = /** @type {TextEncoder} */ (typeof TextEncoder !== 'undefined' ? new TextEncoder() : null);
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* @param {string} str
|
|
552
|
+
* @return {Uint8Array}
|
|
553
|
+
*/
|
|
554
|
+
const _encodeUtf8Native = str => utf8TextEncoder.encode(str);
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* @param {string} str
|
|
558
|
+
* @return {Uint8Array}
|
|
559
|
+
*/
|
|
560
|
+
/* c8 ignore next */
|
|
561
|
+
const encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill;
|
|
562
|
+
|
|
563
|
+
/* c8 ignore next */
|
|
564
|
+
let utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
565
|
+
|
|
566
|
+
/* c8 ignore start */
|
|
567
|
+
if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {
|
|
568
|
+
// Safari doesn't handle BOM correctly.
|
|
569
|
+
// This fixes a bug in Safari 13.0.5 where it produces a BOM the first time it is called.
|
|
570
|
+
// utf8TextDecoder.decode(new Uint8Array()).length === 1 on the first call and
|
|
571
|
+
// utf8TextDecoder.decode(new Uint8Array()).length === 1 on the second call
|
|
572
|
+
// Another issue is that from then on no BOM chars are recognized anymore
|
|
573
|
+
/* c8 ignore next */
|
|
574
|
+
utf8TextDecoder = null;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* Efficient schema-less binary encoding with support for variable length encoding.
|
|
579
|
+
*
|
|
580
|
+
* Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.
|
|
581
|
+
*
|
|
582
|
+
* Encodes numbers in little-endian order (least to most significant byte order)
|
|
583
|
+
* and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
|
|
584
|
+
* which is also used in Protocol Buffers.
|
|
585
|
+
*
|
|
586
|
+
* ```js
|
|
587
|
+
* // encoding step
|
|
588
|
+
* const encoder = encoding.createEncoder()
|
|
589
|
+
* encoding.writeVarUint(encoder, 256)
|
|
590
|
+
* encoding.writeVarString(encoder, 'Hello world!')
|
|
591
|
+
* const buf = encoding.toUint8Array(encoder)
|
|
592
|
+
* ```
|
|
593
|
+
*
|
|
594
|
+
* ```js
|
|
595
|
+
* // decoding step
|
|
596
|
+
* const decoder = decoding.createDecoder(buf)
|
|
597
|
+
* decoding.readVarUint(decoder) // => 256
|
|
598
|
+
* decoding.readVarString(decoder) // => 'Hello world!'
|
|
599
|
+
* decoding.hasContent(decoder) // => false - all data is read
|
|
600
|
+
* ```
|
|
601
|
+
*
|
|
602
|
+
* @module encoding
|
|
603
|
+
*/
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* A BinaryEncoder handles the encoding to an Uint8Array.
|
|
608
|
+
*/
|
|
609
|
+
class Encoder {
|
|
610
|
+
constructor () {
|
|
611
|
+
this.cpos = 0;
|
|
612
|
+
this.cbuf = new Uint8Array(100);
|
|
613
|
+
/**
|
|
614
|
+
* @type {Array<Uint8Array>}
|
|
615
|
+
*/
|
|
616
|
+
this.bufs = [];
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/**
|
|
621
|
+
* The current length of the encoded data.
|
|
622
|
+
*
|
|
623
|
+
* @function
|
|
624
|
+
* @param {Encoder} encoder
|
|
625
|
+
* @return {number}
|
|
626
|
+
*/
|
|
627
|
+
const length = encoder => {
|
|
628
|
+
let len = encoder.cpos;
|
|
629
|
+
for (let i = 0; i < encoder.bufs.length; i++) {
|
|
630
|
+
len += encoder.bufs[i].length;
|
|
631
|
+
}
|
|
632
|
+
return len
|
|
633
|
+
};
|
|
634
|
+
|
|
635
|
+
/**
|
|
636
|
+
* Transform to Uint8Array.
|
|
637
|
+
*
|
|
638
|
+
* @function
|
|
639
|
+
* @param {Encoder} encoder
|
|
640
|
+
* @return {Uint8Array} The created ArrayBuffer.
|
|
641
|
+
*/
|
|
642
|
+
const toUint8Array = encoder => {
|
|
643
|
+
const uint8arr = new Uint8Array(length(encoder));
|
|
644
|
+
let curPos = 0;
|
|
645
|
+
for (let i = 0; i < encoder.bufs.length; i++) {
|
|
646
|
+
const d = encoder.bufs[i];
|
|
647
|
+
uint8arr.set(d, curPos);
|
|
648
|
+
curPos += d.length;
|
|
649
|
+
}
|
|
650
|
+
uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos);
|
|
651
|
+
return uint8arr
|
|
652
|
+
};
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* Verify that it is possible to write `len` bytes wtihout checking. If
|
|
656
|
+
* necessary, a new Buffer with the required length is attached.
|
|
657
|
+
*
|
|
658
|
+
* @param {Encoder} encoder
|
|
659
|
+
* @param {number} len
|
|
660
|
+
*/
|
|
661
|
+
const verifyLen = (encoder, len) => {
|
|
662
|
+
const bufferLen = encoder.cbuf.length;
|
|
663
|
+
if (bufferLen - encoder.cpos < len) {
|
|
664
|
+
encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos));
|
|
665
|
+
encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2);
|
|
666
|
+
encoder.cpos = 0;
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
|
|
670
|
+
/**
|
|
671
|
+
* Write one byte to the encoder.
|
|
672
|
+
*
|
|
673
|
+
* @function
|
|
674
|
+
* @param {Encoder} encoder
|
|
675
|
+
* @param {number} num The byte that is to be encoded.
|
|
676
|
+
*/
|
|
677
|
+
const write = (encoder, num) => {
|
|
678
|
+
const bufferLen = encoder.cbuf.length;
|
|
679
|
+
if (encoder.cpos === bufferLen) {
|
|
680
|
+
encoder.bufs.push(encoder.cbuf);
|
|
681
|
+
encoder.cbuf = new Uint8Array(bufferLen * 2);
|
|
682
|
+
encoder.cpos = 0;
|
|
683
|
+
}
|
|
684
|
+
encoder.cbuf[encoder.cpos++] = num;
|
|
685
|
+
};
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Write a variable length unsigned integer. Max encodable integer is 2^53.
|
|
689
|
+
*
|
|
690
|
+
* @function
|
|
691
|
+
* @param {Encoder} encoder
|
|
692
|
+
* @param {number} num The number that is to be encoded.
|
|
693
|
+
*/
|
|
694
|
+
const writeVarUint = (encoder, num) => {
|
|
695
|
+
while (num > BITS7) {
|
|
696
|
+
write(encoder, BIT8 | (BITS7 & num));
|
|
697
|
+
num = floor(num / 128); // shift >>> 7
|
|
698
|
+
}
|
|
699
|
+
write(encoder, BITS7 & num);
|
|
700
|
+
};
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* Write a variable length integer.
|
|
704
|
+
*
|
|
705
|
+
* We use the 7th bit instead for signaling that this is a negative number.
|
|
706
|
+
*
|
|
707
|
+
* @function
|
|
708
|
+
* @param {Encoder} encoder
|
|
709
|
+
* @param {number} num The number that is to be encoded.
|
|
710
|
+
*/
|
|
711
|
+
const writeVarInt = (encoder, num) => {
|
|
712
|
+
const isNegative = isNegativeZero(num);
|
|
713
|
+
if (isNegative) {
|
|
714
|
+
num = -num;
|
|
715
|
+
}
|
|
716
|
+
// |- whether to continue reading |- whether is negative |- number
|
|
717
|
+
write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | (BITS6 & num));
|
|
718
|
+
num = floor(num / 64); // shift >>> 6
|
|
719
|
+
// We don't need to consider the case of num === 0 so we can use a different
|
|
720
|
+
// pattern here than above.
|
|
721
|
+
while (num > 0) {
|
|
722
|
+
write(encoder, (num > BITS7 ? BIT8 : 0) | (BITS7 & num));
|
|
723
|
+
num = floor(num / 128); // shift >>> 7
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
|
|
727
|
+
/**
|
|
728
|
+
* A cache to store strings temporarily
|
|
729
|
+
*/
|
|
730
|
+
const _strBuffer = new Uint8Array(30000);
|
|
731
|
+
const _maxStrBSize = _strBuffer.length / 3;
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Write a variable length string.
|
|
735
|
+
*
|
|
736
|
+
* @function
|
|
737
|
+
* @param {Encoder} encoder
|
|
738
|
+
* @param {String} str The string that is to be encoded.
|
|
739
|
+
*/
|
|
740
|
+
const _writeVarStringNative = (encoder, str) => {
|
|
741
|
+
if (str.length < _maxStrBSize) {
|
|
742
|
+
// We can encode the string into the existing buffer
|
|
743
|
+
/* c8 ignore next */
|
|
744
|
+
const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
|
|
745
|
+
writeVarUint(encoder, written);
|
|
746
|
+
for (let i = 0; i < written; i++) {
|
|
747
|
+
write(encoder, _strBuffer[i]);
|
|
748
|
+
}
|
|
749
|
+
} else {
|
|
750
|
+
writeVarUint8Array(encoder, encodeUtf8(str));
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* Write a variable length string.
|
|
756
|
+
*
|
|
757
|
+
* @function
|
|
758
|
+
* @param {Encoder} encoder
|
|
759
|
+
* @param {String} str The string that is to be encoded.
|
|
760
|
+
*/
|
|
761
|
+
const _writeVarStringPolyfill = (encoder, str) => {
|
|
762
|
+
const encodedString = unescape(encodeURIComponent(str));
|
|
763
|
+
const len = encodedString.length;
|
|
764
|
+
writeVarUint(encoder, len);
|
|
765
|
+
for (let i = 0; i < len; i++) {
|
|
766
|
+
write(encoder, /** @type {number} */ (encodedString.codePointAt(i)));
|
|
767
|
+
}
|
|
768
|
+
};
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* Write a variable length string.
|
|
772
|
+
*
|
|
773
|
+
* @function
|
|
774
|
+
* @param {Encoder} encoder
|
|
775
|
+
* @param {String} str The string that is to be encoded.
|
|
776
|
+
*/
|
|
777
|
+
/* c8 ignore next */
|
|
778
|
+
const writeVarString = (utf8TextEncoder && /** @type {any} */ (utf8TextEncoder).encodeInto) ? _writeVarStringNative : _writeVarStringPolyfill;
|
|
779
|
+
|
|
780
|
+
/**
|
|
781
|
+
* Append fixed-length Uint8Array to the encoder.
|
|
782
|
+
*
|
|
783
|
+
* @function
|
|
784
|
+
* @param {Encoder} encoder
|
|
785
|
+
* @param {Uint8Array} uint8Array
|
|
786
|
+
*/
|
|
787
|
+
const writeUint8Array = (encoder, uint8Array) => {
|
|
788
|
+
const bufferLen = encoder.cbuf.length;
|
|
789
|
+
const cpos = encoder.cpos;
|
|
790
|
+
const leftCopyLen = min(bufferLen - cpos, uint8Array.length);
|
|
791
|
+
const rightCopyLen = uint8Array.length - leftCopyLen;
|
|
792
|
+
encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
|
|
793
|
+
encoder.cpos += leftCopyLen;
|
|
794
|
+
if (rightCopyLen > 0) {
|
|
795
|
+
// Still something to write, write right half..
|
|
796
|
+
// Append new buffer
|
|
797
|
+
encoder.bufs.push(encoder.cbuf);
|
|
798
|
+
// must have at least size of remaining buffer
|
|
799
|
+
encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen));
|
|
800
|
+
// copy array
|
|
801
|
+
encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
|
|
802
|
+
encoder.cpos = rightCopyLen;
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* Append an Uint8Array to Encoder.
|
|
808
|
+
*
|
|
809
|
+
* @function
|
|
810
|
+
* @param {Encoder} encoder
|
|
811
|
+
* @param {Uint8Array} uint8Array
|
|
812
|
+
*/
|
|
813
|
+
const writeVarUint8Array = (encoder, uint8Array) => {
|
|
814
|
+
writeVarUint(encoder, uint8Array.byteLength);
|
|
815
|
+
writeUint8Array(encoder, uint8Array);
|
|
816
|
+
};
|
|
817
|
+
|
|
818
|
+
/**
|
|
819
|
+
* Create an DataView of the next `len` bytes. Use it to write data after
|
|
820
|
+
* calling this function.
|
|
821
|
+
*
|
|
822
|
+
* ```js
|
|
823
|
+
* // write float32 using DataView
|
|
824
|
+
* const dv = writeOnDataView(encoder, 4)
|
|
825
|
+
* dv.setFloat32(0, 1.1)
|
|
826
|
+
* // read float32 using DataView
|
|
827
|
+
* const dv = readFromDataView(encoder, 4)
|
|
828
|
+
* dv.getFloat32(0) // => 1.100000023841858 (leaving it to the reader to find out why this is the correct result)
|
|
829
|
+
* ```
|
|
830
|
+
*
|
|
831
|
+
* @param {Encoder} encoder
|
|
832
|
+
* @param {number} len
|
|
833
|
+
* @return {DataView}
|
|
834
|
+
*/
|
|
835
|
+
const writeOnDataView = (encoder, len) => {
|
|
836
|
+
verifyLen(encoder, len);
|
|
837
|
+
const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len);
|
|
838
|
+
encoder.cpos += len;
|
|
839
|
+
return dview
|
|
840
|
+
};
|
|
841
|
+
|
|
842
|
+
/**
|
|
843
|
+
* @param {Encoder} encoder
|
|
844
|
+
* @param {number} num
|
|
845
|
+
*/
|
|
846
|
+
const writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false);
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* @param {Encoder} encoder
|
|
850
|
+
* @param {number} num
|
|
851
|
+
*/
|
|
852
|
+
const writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false);
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* @param {Encoder} encoder
|
|
856
|
+
* @param {bigint} num
|
|
857
|
+
*/
|
|
858
|
+
const writeBigInt64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigInt64(0, num, false);
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* @param {Encoder} encoder
|
|
862
|
+
* @param {bigint} num
|
|
863
|
+
*/
|
|
864
|
+
const writeBigUint64 = (encoder, num) => /** @type {any} */ (writeOnDataView(encoder, 8)).setBigUint64(0, num, false);
|
|
865
|
+
|
|
866
|
+
const floatTestBed = new DataView(new ArrayBuffer(4));
|
|
867
|
+
/**
|
|
868
|
+
* Check if a number can be encoded as a 32 bit float.
|
|
869
|
+
*
|
|
870
|
+
* @param {number} num
|
|
871
|
+
* @return {boolean}
|
|
872
|
+
*/
|
|
873
|
+
const isFloat32 = num => {
|
|
874
|
+
floatTestBed.setFloat32(0, num);
|
|
875
|
+
return floatTestBed.getFloat32(0) === num
|
|
876
|
+
};
|
|
877
|
+
|
|
878
|
+
/**
|
|
879
|
+
* Encode data with efficient binary format.
|
|
880
|
+
*
|
|
881
|
+
* Differences to JSON:
|
|
882
|
+
* • Transforms data to a binary format (not to a string)
|
|
883
|
+
* • Encodes undefined, NaN, and ArrayBuffer (these can't be represented in JSON)
|
|
884
|
+
* • Numbers are efficiently encoded either as a variable length integer, as a
|
|
885
|
+
* 32 bit float, as a 64 bit float, or as a 64 bit bigint.
|
|
886
|
+
*
|
|
887
|
+
* Encoding table:
|
|
888
|
+
*
|
|
889
|
+
* | Data Type | Prefix | Encoding Method | Comment |
|
|
890
|
+
* | ------------------- | -------- | ------------------ | ------- |
|
|
891
|
+
* | undefined | 127 | | Functions, symbol, and everything that cannot be identified is encoded as undefined |
|
|
892
|
+
* | null | 126 | | |
|
|
893
|
+
* | integer | 125 | writeVarInt | Only encodes 32 bit signed integers |
|
|
894
|
+
* | float32 | 124 | writeFloat32 | |
|
|
895
|
+
* | float64 | 123 | writeFloat64 | |
|
|
896
|
+
* | bigint | 122 | writeBigInt64 | |
|
|
897
|
+
* | boolean (false) | 121 | | True and false are different data types so we save the following byte |
|
|
898
|
+
* | boolean (true) | 120 | | - 0b01111000 so the last bit determines whether true or false |
|
|
899
|
+
* | string | 119 | writeVarString | |
|
|
900
|
+
* | object<string,any> | 118 | custom | Writes {length} then {length} key-value pairs |
|
|
901
|
+
* | array<any> | 117 | custom | Writes {length} then {length} json values |
|
|
902
|
+
* | Uint8Array | 116 | writeVarUint8Array | We use Uint8Array for any kind of binary data |
|
|
903
|
+
*
|
|
904
|
+
* Reasons for the decreasing prefix:
|
|
905
|
+
* We need the first bit for extendability (later we may want to encode the
|
|
906
|
+
* prefix with writeVarUint). The remaining 7 bits are divided as follows:
|
|
907
|
+
* [0-30] the beginning of the data range is used for custom purposes
|
|
908
|
+
* (defined by the function that uses this library)
|
|
909
|
+
* [31-127] the end of the data range is used for data encoding by
|
|
910
|
+
* lib0/encoding.js
|
|
911
|
+
*
|
|
912
|
+
* @param {Encoder} encoder
|
|
913
|
+
* @param {undefined|null|number|bigint|boolean|string|Object<string,any>|Array<any>|Uint8Array} data
|
|
914
|
+
*/
|
|
915
|
+
const writeAny = (encoder, data) => {
|
|
916
|
+
switch (typeof data) {
|
|
917
|
+
case 'string':
|
|
918
|
+
// TYPE 119: STRING
|
|
919
|
+
write(encoder, 119);
|
|
920
|
+
writeVarString(encoder, data);
|
|
921
|
+
break
|
|
922
|
+
case 'number':
|
|
923
|
+
if (isInteger(data) && abs(data) <= BITS31) {
|
|
924
|
+
// TYPE 125: INTEGER
|
|
925
|
+
write(encoder, 125);
|
|
926
|
+
writeVarInt(encoder, data);
|
|
927
|
+
} else if (isFloat32(data)) {
|
|
928
|
+
// TYPE 124: FLOAT32
|
|
929
|
+
write(encoder, 124);
|
|
930
|
+
writeFloat32(encoder, data);
|
|
931
|
+
} else {
|
|
932
|
+
// TYPE 123: FLOAT64
|
|
933
|
+
write(encoder, 123);
|
|
934
|
+
writeFloat64(encoder, data);
|
|
935
|
+
}
|
|
936
|
+
break
|
|
937
|
+
case 'bigint':
|
|
938
|
+
// TYPE 122: BigInt
|
|
939
|
+
write(encoder, 122);
|
|
940
|
+
writeBigInt64(encoder, data);
|
|
941
|
+
break
|
|
942
|
+
case 'object':
|
|
943
|
+
if (data === null) {
|
|
944
|
+
// TYPE 126: null
|
|
945
|
+
write(encoder, 126);
|
|
946
|
+
} else if (isArray(data)) {
|
|
947
|
+
// TYPE 117: Array
|
|
948
|
+
write(encoder, 117);
|
|
949
|
+
writeVarUint(encoder, data.length);
|
|
950
|
+
for (let i = 0; i < data.length; i++) {
|
|
951
|
+
writeAny(encoder, data[i]);
|
|
952
|
+
}
|
|
953
|
+
} else if (data instanceof Uint8Array) {
|
|
954
|
+
// TYPE 116: ArrayBuffer
|
|
955
|
+
write(encoder, 116);
|
|
956
|
+
writeVarUint8Array(encoder, data);
|
|
957
|
+
} else {
|
|
958
|
+
// TYPE 118: Object
|
|
959
|
+
write(encoder, 118);
|
|
960
|
+
const keys = Object.keys(data);
|
|
961
|
+
writeVarUint(encoder, keys.length);
|
|
962
|
+
for (let i = 0; i < keys.length; i++) {
|
|
963
|
+
const key = keys[i];
|
|
964
|
+
writeVarString(encoder, key);
|
|
965
|
+
writeAny(encoder, data[key]);
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
break
|
|
969
|
+
case 'boolean':
|
|
970
|
+
// TYPE 120/121: boolean (true/false)
|
|
971
|
+
write(encoder, data ? 120 : 121);
|
|
972
|
+
break
|
|
973
|
+
default:
|
|
974
|
+
// TYPE 127: undefined
|
|
975
|
+
write(encoder, 127);
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
|
|
979
|
+
function encodeYMessage(msg) {
|
|
980
|
+
const encoder = new Encoder();
|
|
981
|
+
writeVarString(encoder, msg.type);
|
|
982
|
+
writeVarString(encoder, msg.table);
|
|
983
|
+
writeVarString(encoder, msg.prop);
|
|
984
|
+
switch (msg.type) {
|
|
985
|
+
case 'u-ack':
|
|
986
|
+
case 'u-reject':
|
|
987
|
+
writeBigUint64(encoder, BigInt(msg.i));
|
|
988
|
+
break;
|
|
989
|
+
default:
|
|
990
|
+
writeAny(encoder, msg.k);
|
|
991
|
+
switch (msg.type) {
|
|
992
|
+
case 'aware':
|
|
993
|
+
writeVarUint8Array(encoder, msg.u);
|
|
994
|
+
break;
|
|
995
|
+
case 'doc-open':
|
|
996
|
+
writeAny(encoder, msg.serverRev);
|
|
997
|
+
writeAny(encoder, msg.sv);
|
|
998
|
+
break;
|
|
999
|
+
case 'doc-close':
|
|
1000
|
+
break;
|
|
1001
|
+
case 'sv':
|
|
1002
|
+
writeVarUint8Array(encoder, msg.sv);
|
|
1003
|
+
break;
|
|
1004
|
+
case 'u-c':
|
|
1005
|
+
writeVarUint8Array(encoder, msg.u);
|
|
1006
|
+
writeBigUint64(encoder, BigInt(msg.i));
|
|
1007
|
+
break;
|
|
1008
|
+
case 'u-s':
|
|
1009
|
+
writeVarUint8Array(encoder, msg.u);
|
|
1010
|
+
break;
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
return toUint8Array(encoder);
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
/**
|
|
1017
|
+
* Error helpers.
|
|
1018
|
+
*
|
|
1019
|
+
* @module error
|
|
1020
|
+
*/
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* @param {string} s
|
|
1024
|
+
* @return {Error}
|
|
1025
|
+
*/
|
|
1026
|
+
/* c8 ignore next */
|
|
1027
|
+
const create = s => new Error(s);
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* Efficient schema-less binary decoding with support for variable length encoding.
|
|
1031
|
+
*
|
|
1032
|
+
* Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.
|
|
1033
|
+
*
|
|
1034
|
+
* Encodes numbers in little-endian order (least to most significant byte order)
|
|
1035
|
+
* and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
|
|
1036
|
+
* which is also used in Protocol Buffers.
|
|
1037
|
+
*
|
|
1038
|
+
* ```js
|
|
1039
|
+
* // encoding step
|
|
1040
|
+
* const encoder = encoding.createEncoder()
|
|
1041
|
+
* encoding.writeVarUint(encoder, 256)
|
|
1042
|
+
* encoding.writeVarString(encoder, 'Hello world!')
|
|
1043
|
+
* const buf = encoding.toUint8Array(encoder)
|
|
1044
|
+
* ```
|
|
1045
|
+
*
|
|
1046
|
+
* ```js
|
|
1047
|
+
* // decoding step
|
|
1048
|
+
* const decoder = decoding.createDecoder(buf)
|
|
1049
|
+
* decoding.readVarUint(decoder) // => 256
|
|
1050
|
+
* decoding.readVarString(decoder) // => 'Hello world!'
|
|
1051
|
+
* decoding.hasContent(decoder) // => false - all data is read
|
|
1052
|
+
* ```
|
|
1053
|
+
*
|
|
1054
|
+
* @module decoding
|
|
1055
|
+
*/
|
|
1056
|
+
|
|
1057
|
+
|
|
1058
|
+
const errorUnexpectedEndOfArray = create('Unexpected end of array');
|
|
1059
|
+
const errorIntegerOutOfRange = create('Integer out of Range');
|
|
1060
|
+
|
|
1061
|
+
/**
|
|
1062
|
+
* A Decoder handles the decoding of an Uint8Array.
|
|
1063
|
+
*/
|
|
1064
|
+
class Decoder {
|
|
1065
|
+
/**
|
|
1066
|
+
* @param {Uint8Array} uint8Array Binary data to decode
|
|
1067
|
+
*/
|
|
1068
|
+
constructor (uint8Array) {
|
|
1069
|
+
/**
|
|
1070
|
+
* Decoding target.
|
|
1071
|
+
*
|
|
1072
|
+
* @type {Uint8Array}
|
|
1073
|
+
*/
|
|
1074
|
+
this.arr = uint8Array;
|
|
1075
|
+
/**
|
|
1076
|
+
* Current decoding position.
|
|
1077
|
+
*
|
|
1078
|
+
* @type {number}
|
|
1079
|
+
*/
|
|
1080
|
+
this.pos = 0;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
/**
|
|
1085
|
+
* @function
|
|
1086
|
+
* @param {Decoder} decoder
|
|
1087
|
+
* @return {boolean}
|
|
1088
|
+
*/
|
|
1089
|
+
const hasContent = decoder => decoder.pos !== decoder.arr.length;
|
|
1090
|
+
|
|
1091
|
+
/**
|
|
1092
|
+
* Create an Uint8Array view of the next `len` bytes and advance the position by `len`.
|
|
1093
|
+
*
|
|
1094
|
+
* Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
|
|
1095
|
+
* Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
|
|
1096
|
+
*
|
|
1097
|
+
* @function
|
|
1098
|
+
* @param {Decoder} decoder The decoder instance
|
|
1099
|
+
* @param {number} len The length of bytes to read
|
|
1100
|
+
* @return {Uint8Array}
|
|
1101
|
+
*/
|
|
1102
|
+
const readUint8Array = (decoder, len) => {
|
|
1103
|
+
const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
|
|
1104
|
+
decoder.pos += len;
|
|
1105
|
+
return view
|
|
1106
|
+
};
|
|
1107
|
+
|
|
1108
|
+
/**
|
|
1109
|
+
* Read variable length Uint8Array.
|
|
1110
|
+
*
|
|
1111
|
+
* Important: The Uint8Array still points to the underlying ArrayBuffer. Make sure to discard the result as soon as possible to prevent any memory leaks.
|
|
1112
|
+
* Use `buffer.copyUint8Array` to copy the result into a new Uint8Array.
|
|
1113
|
+
*
|
|
1114
|
+
* @function
|
|
1115
|
+
* @param {Decoder} decoder
|
|
1116
|
+
* @return {Uint8Array}
|
|
1117
|
+
*/
|
|
1118
|
+
const readVarUint8Array = decoder => readUint8Array(decoder, readVarUint(decoder));
|
|
1119
|
+
|
|
1120
|
+
/**
|
|
1121
|
+
* Read one byte as unsigned integer.
|
|
1122
|
+
* @function
|
|
1123
|
+
* @param {Decoder} decoder The decoder instance
|
|
1124
|
+
* @return {number} Unsigned 8-bit integer
|
|
1125
|
+
*/
|
|
1126
|
+
const readUint8 = decoder => decoder.arr[decoder.pos++];
|
|
1127
|
+
|
|
1128
|
+
/**
|
|
1129
|
+
* Read unsigned integer (32bit) with variable length.
|
|
1130
|
+
* 1/8th of the storage is used as encoding overhead.
|
|
1131
|
+
* * numbers < 2^7 is stored in one bytlength
|
|
1132
|
+
* * numbers < 2^14 is stored in two bylength
|
|
1133
|
+
*
|
|
1134
|
+
* @function
|
|
1135
|
+
* @param {Decoder} decoder
|
|
1136
|
+
* @return {number} An unsigned integer.length
|
|
1137
|
+
*/
|
|
1138
|
+
const readVarUint = decoder => {
|
|
1139
|
+
let num = 0;
|
|
1140
|
+
let mult = 1;
|
|
1141
|
+
const len = decoder.arr.length;
|
|
1142
|
+
while (decoder.pos < len) {
|
|
1143
|
+
const r = decoder.arr[decoder.pos++];
|
|
1144
|
+
// num = num | ((r & binary.BITS7) << len)
|
|
1145
|
+
num = num + (r & BITS7) * mult; // shift $r << (7*#iterations) and add it to num
|
|
1146
|
+
mult *= 128; // next iteration, shift 7 "more" to the left
|
|
1147
|
+
if (r < BIT8) {
|
|
1148
|
+
return num
|
|
1149
|
+
}
|
|
1150
|
+
/* c8 ignore start */
|
|
1151
|
+
if (num > MAX_SAFE_INTEGER) {
|
|
1152
|
+
throw errorIntegerOutOfRange
|
|
1153
|
+
}
|
|
1154
|
+
/* c8 ignore stop */
|
|
1155
|
+
}
|
|
1156
|
+
throw errorUnexpectedEndOfArray
|
|
1157
|
+
};
|
|
1158
|
+
|
|
1159
|
+
/**
|
|
1160
|
+
* Read signed integer (32bit) with variable length.
|
|
1161
|
+
* 1/8th of the storage is used as encoding overhead.
|
|
1162
|
+
* * numbers < 2^7 is stored in one bytlength
|
|
1163
|
+
* * numbers < 2^14 is stored in two bylength
|
|
1164
|
+
* @todo This should probably create the inverse ~num if number is negative - but this would be a breaking change.
|
|
1165
|
+
*
|
|
1166
|
+
* @function
|
|
1167
|
+
* @param {Decoder} decoder
|
|
1168
|
+
* @return {number} An unsigned integer.length
|
|
1169
|
+
*/
|
|
1170
|
+
const readVarInt = decoder => {
|
|
1171
|
+
let r = decoder.arr[decoder.pos++];
|
|
1172
|
+
let num = r & BITS6;
|
|
1173
|
+
let mult = 64;
|
|
1174
|
+
const sign = (r & BIT7) > 0 ? -1 : 1;
|
|
1175
|
+
if ((r & BIT8) === 0) {
|
|
1176
|
+
// don't continue reading
|
|
1177
|
+
return sign * num
|
|
1178
|
+
}
|
|
1179
|
+
const len = decoder.arr.length;
|
|
1180
|
+
while (decoder.pos < len) {
|
|
1181
|
+
r = decoder.arr[decoder.pos++];
|
|
1182
|
+
// num = num | ((r & binary.BITS7) << len)
|
|
1183
|
+
num = num + (r & BITS7) * mult;
|
|
1184
|
+
mult *= 128;
|
|
1185
|
+
if (r < BIT8) {
|
|
1186
|
+
return sign * num
|
|
1187
|
+
}
|
|
1188
|
+
/* c8 ignore start */
|
|
1189
|
+
if (num > MAX_SAFE_INTEGER) {
|
|
1190
|
+
throw errorIntegerOutOfRange
|
|
1191
|
+
}
|
|
1192
|
+
/* c8 ignore stop */
|
|
1193
|
+
}
|
|
1194
|
+
throw errorUnexpectedEndOfArray
|
|
1195
|
+
};
|
|
1196
|
+
|
|
1197
|
+
/**
|
|
1198
|
+
* We don't test this function anymore as we use native decoding/encoding by default now.
|
|
1199
|
+
* Better not modify this anymore..
|
|
1200
|
+
*
|
|
1201
|
+
* Transforming utf8 to a string is pretty expensive. The code performs 10x better
|
|
1202
|
+
* when String.fromCodePoint is fed with all characters as arguments.
|
|
1203
|
+
* But most environments have a maximum number of arguments per functions.
|
|
1204
|
+
* For effiency reasons we apply a maximum of 10000 characters at once.
|
|
1205
|
+
*
|
|
1206
|
+
* @function
|
|
1207
|
+
* @param {Decoder} decoder
|
|
1208
|
+
* @return {String} The read String.
|
|
1209
|
+
*/
|
|
1210
|
+
/* c8 ignore start */
|
|
1211
|
+
const _readVarStringPolyfill = decoder => {
|
|
1212
|
+
let remainingLen = readVarUint(decoder);
|
|
1213
|
+
if (remainingLen === 0) {
|
|
1214
|
+
return ''
|
|
1215
|
+
} else {
|
|
1216
|
+
let encodedString = String.fromCodePoint(readUint8(decoder)); // remember to decrease remainingLen
|
|
1217
|
+
if (--remainingLen < 100) { // do not create a Uint8Array for small strings
|
|
1218
|
+
while (remainingLen--) {
|
|
1219
|
+
encodedString += String.fromCodePoint(readUint8(decoder));
|
|
1220
|
+
}
|
|
1221
|
+
} else {
|
|
1222
|
+
while (remainingLen > 0) {
|
|
1223
|
+
const nextLen = remainingLen < 10000 ? remainingLen : 10000;
|
|
1224
|
+
// this is dangerous, we create a fresh array view from the existing buffer
|
|
1225
|
+
const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
|
|
1226
|
+
decoder.pos += nextLen;
|
|
1227
|
+
// Starting with ES5.1 we can supply a generic array-like object as arguments
|
|
1228
|
+
encodedString += String.fromCodePoint.apply(null, /** @type {any} */ (bytes));
|
|
1229
|
+
remainingLen -= nextLen;
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
return decodeURIComponent(escape(encodedString))
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
/* c8 ignore stop */
|
|
1236
|
+
|
|
1237
|
+
/**
|
|
1238
|
+
* @function
|
|
1239
|
+
* @param {Decoder} decoder
|
|
1240
|
+
* @return {String} The read String
|
|
1241
|
+
*/
|
|
1242
|
+
const _readVarStringNative = decoder =>
|
|
1243
|
+
/** @type any */ (utf8TextDecoder).decode(readVarUint8Array(decoder));
|
|
1244
|
+
|
|
1245
|
+
/**
|
|
1246
|
+
* Read string of variable length
|
|
1247
|
+
* * varUint is used to store the length of the string
|
|
1248
|
+
*
|
|
1249
|
+
* @function
|
|
1250
|
+
* @param {Decoder} decoder
|
|
1251
|
+
* @return {String} The read String
|
|
1252
|
+
*
|
|
1253
|
+
*/
|
|
1254
|
+
/* c8 ignore next */
|
|
1255
|
+
const readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill;
|
|
1256
|
+
|
|
1257
|
+
/**
|
|
1258
|
+
* @param {Decoder} decoder
|
|
1259
|
+
* @param {number} len
|
|
1260
|
+
* @return {DataView}
|
|
1261
|
+
*/
|
|
1262
|
+
const readFromDataView = (decoder, len) => {
|
|
1263
|
+
const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len);
|
|
1264
|
+
decoder.pos += len;
|
|
1265
|
+
return dv
|
|
1266
|
+
};
|
|
1267
|
+
|
|
1268
|
+
/**
|
|
1269
|
+
* @param {Decoder} decoder
|
|
1270
|
+
*/
|
|
1271
|
+
const readFloat32 = decoder => readFromDataView(decoder, 4).getFloat32(0, false);
|
|
1272
|
+
|
|
1273
|
+
/**
|
|
1274
|
+
* @param {Decoder} decoder
|
|
1275
|
+
*/
|
|
1276
|
+
const readFloat64 = decoder => readFromDataView(decoder, 8).getFloat64(0, false);
|
|
1277
|
+
|
|
1278
|
+
/**
|
|
1279
|
+
* @param {Decoder} decoder
|
|
1280
|
+
*/
|
|
1281
|
+
const readBigInt64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigInt64(0, false);
|
|
1282
|
+
|
|
1283
|
+
/**
|
|
1284
|
+
* @param {Decoder} decoder
|
|
1285
|
+
*/
|
|
1286
|
+
const readBigUint64 = decoder => /** @type {any} */ (readFromDataView(decoder, 8)).getBigUint64(0, false);
|
|
1287
|
+
|
|
1288
|
+
/**
|
|
1289
|
+
* @type {Array<function(Decoder):any>}
|
|
1290
|
+
*/
|
|
1291
|
+
const readAnyLookupTable = [
|
|
1292
|
+
decoder => undefined, // CASE 127: undefined
|
|
1293
|
+
decoder => null, // CASE 126: null
|
|
1294
|
+
readVarInt, // CASE 125: integer
|
|
1295
|
+
readFloat32, // CASE 124: float32
|
|
1296
|
+
readFloat64, // CASE 123: float64
|
|
1297
|
+
readBigInt64, // CASE 122: bigint
|
|
1298
|
+
decoder => false, // CASE 121: boolean (false)
|
|
1299
|
+
decoder => true, // CASE 120: boolean (true)
|
|
1300
|
+
readVarString, // CASE 119: string
|
|
1301
|
+
decoder => { // CASE 118: object<string,any>
|
|
1302
|
+
const len = readVarUint(decoder);
|
|
1303
|
+
/**
|
|
1304
|
+
* @type {Object<string,any>}
|
|
1305
|
+
*/
|
|
1306
|
+
const obj = {};
|
|
1307
|
+
for (let i = 0; i < len; i++) {
|
|
1308
|
+
const key = readVarString(decoder);
|
|
1309
|
+
obj[key] = readAny(decoder);
|
|
1310
|
+
}
|
|
1311
|
+
return obj
|
|
1312
|
+
},
|
|
1313
|
+
decoder => { // CASE 117: array<any>
|
|
1314
|
+
const len = readVarUint(decoder);
|
|
1315
|
+
const arr = [];
|
|
1316
|
+
for (let i = 0; i < len; i++) {
|
|
1317
|
+
arr.push(readAny(decoder));
|
|
1318
|
+
}
|
|
1319
|
+
return arr
|
|
1320
|
+
},
|
|
1321
|
+
readVarUint8Array // CASE 116: Uint8Array
|
|
1322
|
+
];
|
|
1323
|
+
|
|
1324
|
+
/**
|
|
1325
|
+
* @param {Decoder} decoder
|
|
1326
|
+
*/
|
|
1327
|
+
const readAny = decoder => readAnyLookupTable[127 - readUint8(decoder)](decoder);
|
|
1328
|
+
|
|
1329
|
+
function decodeYMessage(a) {
|
|
1330
|
+
const decoder = new Decoder(a);
|
|
1331
|
+
const type = readVarString(decoder);
|
|
1332
|
+
const table = readVarString(decoder);
|
|
1333
|
+
const prop = readVarString(decoder);
|
|
1334
|
+
switch (type) {
|
|
1335
|
+
case 'u-ack':
|
|
1336
|
+
case 'u-reject':
|
|
1337
|
+
return {
|
|
1338
|
+
type,
|
|
1339
|
+
table,
|
|
1340
|
+
prop,
|
|
1341
|
+
i: Number(readBigUint64(decoder)),
|
|
1342
|
+
};
|
|
1343
|
+
default: {
|
|
1344
|
+
const k = readAny(decoder);
|
|
1345
|
+
switch (type) {
|
|
1346
|
+
case 'in-sync':
|
|
1347
|
+
return { type, table, prop, k };
|
|
1348
|
+
case 'aware':
|
|
1349
|
+
return {
|
|
1350
|
+
type,
|
|
1351
|
+
table,
|
|
1352
|
+
prop,
|
|
1353
|
+
k,
|
|
1354
|
+
u: readVarUint8Array(decoder),
|
|
1355
|
+
};
|
|
1356
|
+
case 'doc-open':
|
|
1357
|
+
return {
|
|
1358
|
+
type,
|
|
1359
|
+
table,
|
|
1360
|
+
prop,
|
|
1361
|
+
k,
|
|
1362
|
+
serverRev: readAny(decoder),
|
|
1363
|
+
sv: readAny(decoder),
|
|
1364
|
+
};
|
|
1365
|
+
case 'doc-close':
|
|
1366
|
+
return { type, table, prop, k };
|
|
1367
|
+
case 'sv':
|
|
1368
|
+
return {
|
|
1369
|
+
type,
|
|
1370
|
+
table,
|
|
1371
|
+
prop,
|
|
1372
|
+
k,
|
|
1373
|
+
sv: readVarUint8Array(decoder),
|
|
1374
|
+
};
|
|
1375
|
+
case 'u-c':
|
|
1376
|
+
return {
|
|
1377
|
+
type,
|
|
1378
|
+
table,
|
|
1379
|
+
prop,
|
|
1380
|
+
k,
|
|
1381
|
+
u: readVarUint8Array(decoder),
|
|
1382
|
+
i: Number(readBigUint64(decoder)),
|
|
1383
|
+
};
|
|
1384
|
+
case 'u-s':
|
|
1385
|
+
return {
|
|
1386
|
+
type,
|
|
1387
|
+
table,
|
|
1388
|
+
prop,
|
|
1389
|
+
k,
|
|
1390
|
+
u: readVarUint8Array(decoder)
|
|
1391
|
+
};
|
|
1392
|
+
default:
|
|
1393
|
+
throw new TypeError(`Unknown message type: ${type}`);
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
async function asyncIterablePipeline(source, ...stages) {
|
|
1400
|
+
var _a, e_1, _b, _c;
|
|
1401
|
+
// Chain generators by sending outdata from one to another
|
|
1402
|
+
let result = source(); // Start with the source generator
|
|
1403
|
+
for (let i = 0; i < stages.length; i++) {
|
|
1404
|
+
result = stages[i](result); // Pass on the result to next generator
|
|
1405
|
+
}
|
|
1406
|
+
try {
|
|
1407
|
+
// Start running the machine. If the last stage is a sink, it will consume the data and never emit anything
|
|
1408
|
+
// to us here...
|
|
1409
|
+
for (var _d = true, result_1 = __asyncValues(result), result_1_1; result_1_1 = await result_1.next(), _a = result_1_1.done, !_a; _d = true) {
|
|
1410
|
+
_c = result_1_1.value;
|
|
1411
|
+
_d = false;
|
|
1412
|
+
const chunk = _c;
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
1416
|
+
finally {
|
|
1417
|
+
try {
|
|
1418
|
+
if (!_d && !_a && (_b = result_1.return)) await _b.call(result_1);
|
|
1419
|
+
}
|
|
1420
|
+
finally { if (e_1) throw e_1.error; }
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
function consumeChunkedBinaryStream(source) {
|
|
1425
|
+
return __asyncGenerator(this, arguments, function* consumeChunkedBinaryStream_1() {
|
|
1426
|
+
var _a, e_1, _b, _c;
|
|
1427
|
+
let state = 0;
|
|
1428
|
+
let sizeBuf = new Uint8Array(4);
|
|
1429
|
+
let sizeBufPos = 0;
|
|
1430
|
+
let bufs = [];
|
|
1431
|
+
let len = 0;
|
|
1432
|
+
try {
|
|
1433
|
+
for (var _d = true, source_1 = __asyncValues(source), source_1_1; source_1_1 = yield __await(source_1.next()), _a = source_1_1.done, !_a; _d = true) {
|
|
1434
|
+
_c = source_1_1.value;
|
|
1435
|
+
_d = false;
|
|
1436
|
+
const chunk = _c;
|
|
1437
|
+
const dw = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength);
|
|
1438
|
+
let pos = 0;
|
|
1439
|
+
while (pos < chunk.byteLength) {
|
|
1440
|
+
switch (state) {
|
|
1441
|
+
case 0:
|
|
1442
|
+
// Beginning of a size header
|
|
1443
|
+
if (pos + 4 > chunk.byteLength) {
|
|
1444
|
+
for (const b of chunk.slice(pos)) {
|
|
1445
|
+
if (sizeBufPos === 4)
|
|
1446
|
+
break;
|
|
1447
|
+
sizeBuf[sizeBufPos++] = b;
|
|
1448
|
+
++pos;
|
|
1449
|
+
}
|
|
1450
|
+
if (sizeBufPos < 4) {
|
|
1451
|
+
// Need more bytes in order to read length.
|
|
1452
|
+
// Will go out from while loop as well because pos is defenitely = chunk.byteLength here.
|
|
1453
|
+
break;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
else if (sizeBufPos > 0 && sizeBufPos < 4) {
|
|
1457
|
+
for (const b of chunk.slice(pos, pos + 4 - sizeBufPos)) {
|
|
1458
|
+
sizeBuf[sizeBufPos++] = b;
|
|
1459
|
+
++pos;
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
// Intentional fall-through...
|
|
1463
|
+
case 1:
|
|
1464
|
+
len =
|
|
1465
|
+
sizeBufPos === 4
|
|
1466
|
+
? new DataView(sizeBuf.buffer, 0, 4).getUint32(0, false)
|
|
1467
|
+
: dw.getUint32(pos, false);
|
|
1468
|
+
if (sizeBufPos)
|
|
1469
|
+
sizeBufPos = 0; // in this case pos is already forwarded
|
|
1470
|
+
else
|
|
1471
|
+
pos += 4; // else pos is not yet forwarded - that's why we do it now
|
|
1472
|
+
// Intentional fall-through...
|
|
1473
|
+
case 2:
|
|
1474
|
+
// Eat the chunk
|
|
1475
|
+
if (pos >= chunk.byteLength) {
|
|
1476
|
+
state = 2;
|
|
1477
|
+
break;
|
|
1478
|
+
}
|
|
1479
|
+
if (pos + len > chunk.byteLength) {
|
|
1480
|
+
bufs.push(chunk.slice(pos));
|
|
1481
|
+
len -= (chunk.byteLength - pos);
|
|
1482
|
+
state = 2;
|
|
1483
|
+
pos = chunk.byteLength; // will break while loop.
|
|
1484
|
+
}
|
|
1485
|
+
else {
|
|
1486
|
+
if (bufs.length > 0) {
|
|
1487
|
+
const concats = new Uint8Array(bufs.reduce((p, c) => p + c.byteLength, len));
|
|
1488
|
+
let p = 0;
|
|
1489
|
+
for (const buf of bufs) {
|
|
1490
|
+
concats.set(buf, p);
|
|
1491
|
+
p += buf.byteLength;
|
|
1492
|
+
}
|
|
1493
|
+
concats.set(chunk.slice(pos, pos + len), p);
|
|
1494
|
+
bufs = [];
|
|
1495
|
+
yield yield __await(concats);
|
|
1496
|
+
}
|
|
1497
|
+
else {
|
|
1498
|
+
yield yield __await(chunk.slice(pos, pos + len));
|
|
1499
|
+
}
|
|
1500
|
+
pos += len;
|
|
1501
|
+
state = 0;
|
|
1502
|
+
}
|
|
1503
|
+
break;
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
1509
|
+
finally {
|
|
1510
|
+
try {
|
|
1511
|
+
if (!_d && !_a && (_b = source_1.return)) yield __await(_b.call(source_1));
|
|
1512
|
+
}
|
|
1513
|
+
finally { if (e_1) throw e_1.error; }
|
|
1514
|
+
}
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
function getFetchResponseBodyGenerator(res) {
|
|
1519
|
+
return function () {
|
|
1520
|
+
return __asyncGenerator(this, arguments, function* () {
|
|
1521
|
+
if (!res.body)
|
|
1522
|
+
throw new Error("Response body is not readable");
|
|
1523
|
+
const reader = res.body.getReader();
|
|
1524
|
+
try {
|
|
1525
|
+
while (true) {
|
|
1526
|
+
const { done, value } = yield __await(reader.read());
|
|
1527
|
+
if (done)
|
|
1528
|
+
return yield __await(void 0);
|
|
1529
|
+
yield yield __await(value);
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
finally {
|
|
1533
|
+
reader.releaseLock();
|
|
1534
|
+
}
|
|
1535
|
+
});
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
|
|
470
1539
|
function isFunction(value) {
|
|
471
1540
|
return typeof value === 'function';
|
|
472
1541
|
}
|
|
@@ -3614,7 +4683,7 @@ function updateSyncRateLimitDelays(db, res) {
|
|
|
3614
4683
|
}
|
|
3615
4684
|
|
|
3616
4685
|
//import {BisonWebStreamReader} from "dreambase-library/dist/typeson-simplified/BisonWebStreamReader";
|
|
3617
|
-
function syncWithServer(changes, syncState, baseRevs, db, databaseUrl, schema, clientIdentity, currentUser) {
|
|
4686
|
+
function syncWithServer(changes, y, syncState, baseRevs, db, databaseUrl, schema, clientIdentity, currentUser) {
|
|
3618
4687
|
return __awaiter(this, void 0, void 0, function* () {
|
|
3619
4688
|
//
|
|
3620
4689
|
// Push changes to server using fetch
|
|
@@ -3652,6 +4721,7 @@ function syncWithServer(changes, syncState, baseRevs, db, databaseUrl, schema, c
|
|
|
3652
4721
|
: undefined,
|
|
3653
4722
|
baseRevs,
|
|
3654
4723
|
changes: encodeIdsForServer(db.dx.core.schema, currentUser, changes),
|
|
4724
|
+
y,
|
|
3655
4725
|
};
|
|
3656
4726
|
console.debug('Sync request', syncRequest);
|
|
3657
4727
|
db.syncStateChangedEvent.next({
|
|
@@ -3865,6 +4935,357 @@ function applyServerChanges(changes, db) {
|
|
|
3865
4935
|
});
|
|
3866
4936
|
}
|
|
3867
4937
|
|
|
4938
|
+
const DEXIE_CLOUD_SYNCER_ID = 'dexie-cloud-syncer';
|
|
4939
|
+
|
|
4940
|
+
function listUpdatesSince(yTable, sinceIncluding) {
|
|
4941
|
+
return yTable
|
|
4942
|
+
.where('i')
|
|
4943
|
+
.between(sinceIncluding, Infinity, true)
|
|
4944
|
+
.toArray();
|
|
4945
|
+
}
|
|
4946
|
+
|
|
4947
|
+
function $Y(db) {
|
|
4948
|
+
const $Y = db.dx._options.Y;
|
|
4949
|
+
if (!$Y)
|
|
4950
|
+
throw new Error('Y library not supplied to Dexie constructor');
|
|
4951
|
+
return $Y;
|
|
4952
|
+
}
|
|
4953
|
+
|
|
4954
|
+
/** Queries the local database for YMessages to send to server.
|
|
4955
|
+
*
|
|
4956
|
+
* There are 2 messages that this function can provide:
|
|
4957
|
+
* YUpdateFromClientRequest ( for local updates )
|
|
4958
|
+
* YStateVector ( for state vector of foreign updates so that server can reduce the number of udpates to send back )
|
|
4959
|
+
*
|
|
4960
|
+
* Notice that we do not do a step 1 sync phase here to get a state vector from the server. Reason we can avoid
|
|
4961
|
+
* the 2-step sync is that we are client-server and not client-client here and we keep track of the client changes
|
|
4962
|
+
* sent to server by letting server acknowledge them. There is always a chance that some client update has already
|
|
4963
|
+
* been sent and that the client failed to receive the ack. However, if this happens it does not matter - the change
|
|
4964
|
+
* would be sent again and Yjs handles duplicate changes anyway. And it's rare so we earn the cost of roundtrips by
|
|
4965
|
+
* avoiding the step1 sync and instead keep track of this in the `unsentFrom` property of the SyncState.
|
|
4966
|
+
*
|
|
4967
|
+
* @param db
|
|
4968
|
+
* @returns
|
|
4969
|
+
*/
|
|
4970
|
+
function listYClientMessagesAndStateVector(db, tablesToSync) {
|
|
4971
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
4972
|
+
const result = [];
|
|
4973
|
+
const lastUpdateIds = {};
|
|
4974
|
+
for (const table of tablesToSync) {
|
|
4975
|
+
if (table.schema.yProps) {
|
|
4976
|
+
for (const yProp of table.schema.yProps) {
|
|
4977
|
+
const Y = $Y(db); // This is how we retrieve the user-provided Y library
|
|
4978
|
+
const yTable = db.table(yProp.updatesTable); // the updates-table for this combo of table+propName
|
|
4979
|
+
const syncState = (yield yTable.get(DEXIE_CLOUD_SYNCER_ID));
|
|
4980
|
+
// unsentFrom = the `i` value of updates that aren't yet sent to server (or at least not acked by the server yet)
|
|
4981
|
+
const unsentFrom = (syncState === null || syncState === void 0 ? void 0 : syncState.unsentFrom) || 1;
|
|
4982
|
+
// receivedUntil = the `i` value of updates that both we and the server knows we already have (we know it by the outcome from last syncWithServer() because server keep track of its revision numbers
|
|
4983
|
+
const receivedUntil = (syncState === null || syncState === void 0 ? void 0 : syncState.receivedUntil) || 0;
|
|
4984
|
+
// Compute the least value of these two (but since receivedUntil is inclusive we need to add +1 to it)
|
|
4985
|
+
const unsyncedFrom = Math.min(unsentFrom, receivedUntil + 1);
|
|
4986
|
+
// Query all these updates for all docs of this table+prop combination
|
|
4987
|
+
const updates = yield listUpdatesSince(yTable, unsyncedFrom);
|
|
4988
|
+
if (updates.length > 0)
|
|
4989
|
+
lastUpdateIds[yTable.name] = updates[updates.length - 1].i;
|
|
4990
|
+
// Now sort them by document and whether they are local or not + ignore local updates already sent:
|
|
4991
|
+
const perDoc = {};
|
|
4992
|
+
for (const update of updates) {
|
|
4993
|
+
// Sort updates into buckets of the doc primary key + the flag (whether it's local or foreign)
|
|
4994
|
+
const isLocal = ((update.f || 0) & 0x01) === 0x01;
|
|
4995
|
+
if (isLocal && update.i < unsentFrom)
|
|
4996
|
+
continue; // This local update has already been sent and acked.
|
|
4997
|
+
const docKey = JSON.stringify(update.k) + '/' + isLocal;
|
|
4998
|
+
let entry = perDoc[docKey];
|
|
4999
|
+
if (!entry) {
|
|
5000
|
+
perDoc[docKey] = entry = {
|
|
5001
|
+
i: update.i,
|
|
5002
|
+
k: update.k,
|
|
5003
|
+
isLocal,
|
|
5004
|
+
u: [],
|
|
5005
|
+
};
|
|
5006
|
+
entry.u.push(update.u);
|
|
5007
|
+
}
|
|
5008
|
+
else {
|
|
5009
|
+
entry.u.push(update.u);
|
|
5010
|
+
entry.i = Math.max(update.i, entry.i);
|
|
5011
|
+
}
|
|
5012
|
+
}
|
|
5013
|
+
// Now, go through all these and:
|
|
5014
|
+
// * For local updates, compute a merged update per document.
|
|
5015
|
+
// * For foreign updates, compute a state vector to pass to server, so that server can
|
|
5016
|
+
// avoid re-sending updates that we already have (they might have been sent of websocket
|
|
5017
|
+
// and when that happens, we do not mark them in any way nor do we update receivedUntil -
|
|
5018
|
+
// we only update receivedUntil after a "full sync" (syncWithServer()))
|
|
5019
|
+
for (const { k, isLocal, u, i } of Object.values(perDoc)) {
|
|
5020
|
+
const mergedUpdate = u.length === 1 ? u[0] : Y.mergeUpdatesV2(u);
|
|
5021
|
+
if (isLocal) {
|
|
5022
|
+
result.push({
|
|
5023
|
+
type: 'u-c',
|
|
5024
|
+
table: table.name,
|
|
5025
|
+
prop: yProp.prop,
|
|
5026
|
+
k,
|
|
5027
|
+
u: mergedUpdate,
|
|
5028
|
+
i,
|
|
5029
|
+
});
|
|
5030
|
+
}
|
|
5031
|
+
else {
|
|
5032
|
+
const stateVector = Y.encodeStateVectorFromUpdateV2(mergedUpdate);
|
|
5033
|
+
result.push({
|
|
5034
|
+
type: 'sv',
|
|
5035
|
+
table: table.name,
|
|
5036
|
+
prop: yProp.prop,
|
|
5037
|
+
k,
|
|
5038
|
+
sv: stateVector,
|
|
5039
|
+
});
|
|
5040
|
+
}
|
|
5041
|
+
}
|
|
5042
|
+
}
|
|
5043
|
+
}
|
|
5044
|
+
}
|
|
5045
|
+
return {
|
|
5046
|
+
yMessages: result,
|
|
5047
|
+
lastUpdateIds
|
|
5048
|
+
};
|
|
5049
|
+
});
|
|
5050
|
+
}
|
|
5051
|
+
|
|
5052
|
+
function getUpdatesTable(db, table, ydocProp) {
|
|
5053
|
+
var _a, _b, _c;
|
|
5054
|
+
const utbl = (_c = (_b = (_a = db.table(table)) === null || _a === void 0 ? void 0 : _a.schema.yProps) === null || _b === void 0 ? void 0 : _b.find(p => p.prop === ydocProp)) === null || _c === void 0 ? void 0 : _c.updatesTable;
|
|
5055
|
+
if (!utbl)
|
|
5056
|
+
throw new Error(`No updatesTable found for ${table}.${ydocProp}`);
|
|
5057
|
+
return db.table(utbl);
|
|
5058
|
+
}
|
|
5059
|
+
|
|
5060
|
+
function applyYServerMessages(yMessages, db) {
|
|
5061
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
5062
|
+
const result = {};
|
|
5063
|
+
for (const m of yMessages) {
|
|
5064
|
+
switch (m.type) {
|
|
5065
|
+
case 'u-s': {
|
|
5066
|
+
const utbl = getUpdatesTable(db, m.table, m.prop);
|
|
5067
|
+
result[utbl.name] = yield utbl.add({
|
|
5068
|
+
k: m.k,
|
|
5069
|
+
u: m.u,
|
|
5070
|
+
});
|
|
5071
|
+
break;
|
|
5072
|
+
}
|
|
5073
|
+
case 'u-ack': {
|
|
5074
|
+
const utbl = getUpdatesTable(db, m.table, m.prop);
|
|
5075
|
+
yield db.transaction('rw', utbl, (tx) => __awaiter(this, void 0, void 0, function* () {
|
|
5076
|
+
let syncer = (yield tx
|
|
5077
|
+
.table(utbl.name)
|
|
5078
|
+
.get(DEXIE_CLOUD_SYNCER_ID));
|
|
5079
|
+
yield tx.table(utbl.name).put(Object.assign(Object.assign({}, (syncer || { i: DEXIE_CLOUD_SYNCER_ID })), { unsentFrom: Math.max((syncer === null || syncer === void 0 ? void 0 : syncer.unsentFrom) || 1, m.i + 1) }));
|
|
5080
|
+
}));
|
|
5081
|
+
break;
|
|
5082
|
+
}
|
|
5083
|
+
case 'u-reject': {
|
|
5084
|
+
// Acces control or constraint rejected the update.
|
|
5085
|
+
// We delete it. It's not going to be sent again.
|
|
5086
|
+
// What's missing is a way to notify consumers, such as Tiptap editor, that the update was rejected.
|
|
5087
|
+
// This is only an issue when the document is open. We could find the open document and
|
|
5088
|
+
// in a perfect world, we should send a reverse update to the open document to undo the change.
|
|
5089
|
+
// See my question in https://discuss.yjs.dev/t/generate-an-inverse-update/2765
|
|
5090
|
+
console.debug(`Y update rejected. Deleting it.`);
|
|
5091
|
+
const utbl = getUpdatesTable(db, m.table, m.prop);
|
|
5092
|
+
yield utbl.delete(m.i);
|
|
5093
|
+
break;
|
|
5094
|
+
}
|
|
5095
|
+
case 'in-sync': {
|
|
5096
|
+
const doc = DexieYProvider.getDocCache(db.dx).find(m.table, m.k, m.prop);
|
|
5097
|
+
if (doc && !doc.isSynced) {
|
|
5098
|
+
doc.emit('sync', [true]);
|
|
5099
|
+
}
|
|
5100
|
+
break;
|
|
5101
|
+
}
|
|
5102
|
+
}
|
|
5103
|
+
}
|
|
5104
|
+
return result;
|
|
5105
|
+
});
|
|
5106
|
+
}
|
|
5107
|
+
|
|
5108
|
+
function updateYSyncStates(lastUpdateIdsBeforeSync, receivedUntilsAfterSync, db, serverRevision) {
|
|
5109
|
+
var _a, _b, _c, _d, _e;
|
|
5110
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
5111
|
+
// We want to update unsentFrom for each yTable to the value specified in first argument
|
|
5112
|
+
// because we got those values before we synced with server and here we are back from server
|
|
5113
|
+
// that has successfully received all those messages - no matter if the last update was a client or server update,
|
|
5114
|
+
// we can safely store unsentFrom to a value of the last update + 1 here.
|
|
5115
|
+
// We also want to update receivedUntil for each yTable to the value specified in the second argument,
|
|
5116
|
+
// because that contains the highest resulted id of each update from server after storing it.
|
|
5117
|
+
// We could do these two tasks separately, but that would require two update calls on the same YSyncState, so
|
|
5118
|
+
// to optimize the dexie calls, we merge these two maps into a single one so we can do a single update request
|
|
5119
|
+
// per yTable.
|
|
5120
|
+
const mergedSpec = {};
|
|
5121
|
+
for (const [yTable, lastUpdateId] of Object.entries(lastUpdateIdsBeforeSync)) {
|
|
5122
|
+
(_a = mergedSpec[yTable]) !== null && _a !== void 0 ? _a : (mergedSpec[yTable] = {});
|
|
5123
|
+
mergedSpec[yTable].unsentFrom = lastUpdateId + 1;
|
|
5124
|
+
}
|
|
5125
|
+
for (const [yTable, lastUpdateId] of Object.entries(receivedUntilsAfterSync)) {
|
|
5126
|
+
(_b = mergedSpec[yTable]) !== null && _b !== void 0 ? _b : (mergedSpec[yTable] = {});
|
|
5127
|
+
mergedSpec[yTable].receivedUntil = lastUpdateId;
|
|
5128
|
+
}
|
|
5129
|
+
// Now go through all yTables and update their YSyncStates:
|
|
5130
|
+
const allYTables = Object.values(db.dx._dbSchema)
|
|
5131
|
+
.filter((tblSchema) => tblSchema.yProps)
|
|
5132
|
+
.map((tblSchema) => tblSchema.yProps.map((yProp) => yProp.updatesTable))
|
|
5133
|
+
.flat();
|
|
5134
|
+
for (const yTable of allYTables) {
|
|
5135
|
+
const mergedEntry = mergedSpec[yTable];
|
|
5136
|
+
const unsentFrom = (_c = mergedEntry === null || mergedEntry === void 0 ? void 0 : mergedEntry.unsentFrom) !== null && _c !== void 0 ? _c : 1;
|
|
5137
|
+
const receivedUntil = (_e = (_d = mergedEntry === null || mergedEntry === void 0 ? void 0 : mergedEntry.receivedUntil) !== null && _d !== void 0 ? _d :
|
|
5138
|
+
// from local because we are in the same parent transaction (in sync.ts) that
|
|
5139
|
+
// applied all updates from the server
|
|
5140
|
+
(yield db
|
|
5141
|
+
.table(yTable)
|
|
5142
|
+
.where('i')
|
|
5143
|
+
.between(1, Infinity) // Because i might be string DEXIE_CLOUD_SYNCER_ID if not a number.
|
|
5144
|
+
.reverse()
|
|
5145
|
+
.limit(1)
|
|
5146
|
+
.primaryKeys())[0]) !== null && _e !== void 0 ? _e : 0;
|
|
5147
|
+
// We're already in a transaction, but for the sake of
|
|
5148
|
+
// code readability and correctness, let's launch an atomic sub transaction:
|
|
5149
|
+
yield db.transaction('rw', yTable, () => __awaiter(this, void 0, void 0, function* () {
|
|
5150
|
+
const state = yield db
|
|
5151
|
+
.table(yTable)
|
|
5152
|
+
.get(DEXIE_CLOUD_SYNCER_ID);
|
|
5153
|
+
if (!state) {
|
|
5154
|
+
yield db.table(yTable).add({
|
|
5155
|
+
i: DEXIE_CLOUD_SYNCER_ID,
|
|
5156
|
+
unsentFrom,
|
|
5157
|
+
receivedUntil,
|
|
5158
|
+
serverRev: serverRevision,
|
|
5159
|
+
});
|
|
5160
|
+
}
|
|
5161
|
+
else {
|
|
5162
|
+
state.unsentFrom = Math.max(unsentFrom, state.unsentFrom || 1);
|
|
5163
|
+
state.receivedUntil = Math.max(receivedUntil, state.receivedUntil || 0);
|
|
5164
|
+
state.serverRev = serverRevision;
|
|
5165
|
+
yield db.table(yTable).put(state);
|
|
5166
|
+
}
|
|
5167
|
+
}));
|
|
5168
|
+
}
|
|
5169
|
+
});
|
|
5170
|
+
}
|
|
5171
|
+
|
|
5172
|
+
const BINSTREAM_TYPE_REALMID = 1;
|
|
5173
|
+
const BINSTREAM_TYPE_TABLE_AND_PROP = 2;
|
|
5174
|
+
const BINSTREAM_TYPE_DOCUMENT = 3;
|
|
5175
|
+
function downloadYDocsFromServer(db, databaseUrl, { yDownloadedRealms, realms }) {
|
|
5176
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
5177
|
+
if (yDownloadedRealms &&
|
|
5178
|
+
realms &&
|
|
5179
|
+
realms.every((realmId) => yDownloadedRealms[realmId] === '*')) {
|
|
5180
|
+
return; // Already done!
|
|
5181
|
+
}
|
|
5182
|
+
console.debug('Downloading Y.Docs from added realms');
|
|
5183
|
+
const user = yield loadAccessToken(db);
|
|
5184
|
+
const headers = {
|
|
5185
|
+
'Content-Type': 'application/json',
|
|
5186
|
+
Accept: 'application/octet-stream',
|
|
5187
|
+
};
|
|
5188
|
+
if (user) {
|
|
5189
|
+
headers.Authorization = `Bearer ${user.accessToken}`;
|
|
5190
|
+
}
|
|
5191
|
+
const res = yield fetch(`${databaseUrl}/y/download`, {
|
|
5192
|
+
body: TSON.stringify({ downloadedRealms: yDownloadedRealms || {} }),
|
|
5193
|
+
method: 'POST',
|
|
5194
|
+
headers,
|
|
5195
|
+
credentials: 'include',
|
|
5196
|
+
});
|
|
5197
|
+
if (!res.ok) {
|
|
5198
|
+
throw new Error(`Failed to download Yjs documents from server. Status: ${res.status}`);
|
|
5199
|
+
}
|
|
5200
|
+
yield asyncIterablePipeline(getFetchResponseBodyGenerator(res), consumeChunkedBinaryStream, consumeDownloadChunks);
|
|
5201
|
+
function consumeDownloadChunks(chunks) {
|
|
5202
|
+
return __asyncGenerator(this, arguments, function* consumeDownloadChunks_1() {
|
|
5203
|
+
var _a, e_1, _b, _c;
|
|
5204
|
+
let currentRealmId = null;
|
|
5205
|
+
let currentTable = null;
|
|
5206
|
+
let currentProp = null;
|
|
5207
|
+
let docsToInsert = [];
|
|
5208
|
+
function storeCollectedDocs(completedRealm) {
|
|
5209
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
5210
|
+
const lastDoc = docsToInsert[docsToInsert.length - 1];
|
|
5211
|
+
if (docsToInsert.length > 0) {
|
|
5212
|
+
if (!currentRealmId || !currentTable || !currentProp) {
|
|
5213
|
+
throw new Error(`Protocol error from ${databaseUrl}/y/download`);
|
|
5214
|
+
}
|
|
5215
|
+
const yTable = getUpdatesTable(db, currentTable, currentProp);
|
|
5216
|
+
yield yTable.bulkAdd(docsToInsert);
|
|
5217
|
+
docsToInsert = [];
|
|
5218
|
+
}
|
|
5219
|
+
if (currentRealmId &&
|
|
5220
|
+
((currentTable && currentProp && lastDoc) || completedRealm)) {
|
|
5221
|
+
yield db.$syncState.update('syncState', (syncState) => {
|
|
5222
|
+
const yDownloadedRealms = syncState.yDownloadedRealms || {};
|
|
5223
|
+
yDownloadedRealms[currentRealmId] = completedRealm
|
|
5224
|
+
? '*'
|
|
5225
|
+
: {
|
|
5226
|
+
tbl: currentTable,
|
|
5227
|
+
prop: currentProp,
|
|
5228
|
+
key: lastDoc.k,
|
|
5229
|
+
};
|
|
5230
|
+
syncState.yDownloadedRealms = yDownloadedRealms;
|
|
5231
|
+
});
|
|
5232
|
+
}
|
|
5233
|
+
});
|
|
5234
|
+
}
|
|
5235
|
+
try {
|
|
5236
|
+
try {
|
|
5237
|
+
for (var _d = true, chunks_1 = __asyncValues(chunks), chunks_1_1; chunks_1_1 = yield __await(chunks_1.next()), _a = chunks_1_1.done, !_a; _d = true) {
|
|
5238
|
+
_c = chunks_1_1.value;
|
|
5239
|
+
_d = false;
|
|
5240
|
+
const chunk = _c;
|
|
5241
|
+
const decoder = new Decoder(chunk);
|
|
5242
|
+
while (hasContent(decoder)) {
|
|
5243
|
+
switch (readUint8(decoder)) {
|
|
5244
|
+
case BINSTREAM_TYPE_REALMID:
|
|
5245
|
+
yield __await(storeCollectedDocs(true));
|
|
5246
|
+
currentRealmId = readVarString(decoder);
|
|
5247
|
+
break;
|
|
5248
|
+
case BINSTREAM_TYPE_TABLE_AND_PROP:
|
|
5249
|
+
yield __await(storeCollectedDocs(false)); // still on same realm
|
|
5250
|
+
currentTable = readVarString(decoder);
|
|
5251
|
+
currentProp = readVarString(decoder);
|
|
5252
|
+
break;
|
|
5253
|
+
case BINSTREAM_TYPE_DOCUMENT: {
|
|
5254
|
+
const k = readAny(decoder);
|
|
5255
|
+
const u = readVarUint8Array(decoder);
|
|
5256
|
+
docsToInsert.push({
|
|
5257
|
+
k,
|
|
5258
|
+
u,
|
|
5259
|
+
});
|
|
5260
|
+
break;
|
|
5261
|
+
}
|
|
5262
|
+
}
|
|
5263
|
+
}
|
|
5264
|
+
yield __await(storeCollectedDocs(false)); // Chunk full - migth still be on same realm
|
|
5265
|
+
}
|
|
5266
|
+
}
|
|
5267
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
5268
|
+
finally {
|
|
5269
|
+
try {
|
|
5270
|
+
if (!_d && !_a && (_b = chunks_1.return)) yield __await(_b.call(chunks_1));
|
|
5271
|
+
}
|
|
5272
|
+
finally { if (e_1) throw e_1.error; }
|
|
5273
|
+
}
|
|
5274
|
+
yield __await(storeCollectedDocs(true)); // Everything downloaded - finalize last downloaded realm to "*"
|
|
5275
|
+
}
|
|
5276
|
+
catch (error) {
|
|
5277
|
+
if (!(error instanceof Dexie.DexieError)) {
|
|
5278
|
+
// Network error might have happened.
|
|
5279
|
+
// Store what we've collected so far:
|
|
5280
|
+
yield __await(storeCollectedDocs(false));
|
|
5281
|
+
}
|
|
5282
|
+
throw error;
|
|
5283
|
+
}
|
|
5284
|
+
});
|
|
5285
|
+
}
|
|
5286
|
+
});
|
|
5287
|
+
}
|
|
5288
|
+
|
|
3868
5289
|
const CURRENT_SYNC_WORKER = 'currentSyncWorker';
|
|
3869
5290
|
function sync(db, options, schema, syncOptions) {
|
|
3870
5291
|
return _sync
|
|
@@ -3953,10 +5374,11 @@ function _sync(db, options, schema, { isInitialSync, cancelToken, justCheckIfNee
|
|
|
3953
5374
|
//
|
|
3954
5375
|
// List changes to sync
|
|
3955
5376
|
//
|
|
3956
|
-
const [clientChangeSet, syncState, baseRevs] = yield db.transaction('r', db.tables, () => __awaiter(this, void 0, void 0, function* () {
|
|
5377
|
+
const [clientChangeSet, syncState, baseRevs, { yMessages, lastUpdateIds }] = yield db.transaction('r', db.tables, () => __awaiter(this, void 0, void 0, function* () {
|
|
3957
5378
|
const syncState = yield db.getPersistedSyncState();
|
|
3958
5379
|
const baseRevs = yield db.$baseRevs.toArray();
|
|
3959
5380
|
let clientChanges = yield listClientChanges(mutationTables);
|
|
5381
|
+
const yResults = yield listYClientMessagesAndStateVector(db, tablesToSync);
|
|
3960
5382
|
throwIfCancelled(cancelToken);
|
|
3961
5383
|
if (doSyncify) {
|
|
3962
5384
|
const alreadySyncedRealms = [
|
|
@@ -3966,11 +5388,11 @@ function _sync(db, options, schema, { isInitialSync, cancelToken, justCheckIfNee
|
|
|
3966
5388
|
const syncificationInserts = yield listSyncifiedChanges(tablesToSyncify, currentUser, schema, alreadySyncedRealms);
|
|
3967
5389
|
throwIfCancelled(cancelToken);
|
|
3968
5390
|
clientChanges = clientChanges.concat(syncificationInserts);
|
|
3969
|
-
return [clientChanges, syncState, baseRevs];
|
|
5391
|
+
return [clientChanges, syncState, baseRevs, yResults];
|
|
3970
5392
|
}
|
|
3971
|
-
return [clientChanges, syncState, baseRevs];
|
|
5393
|
+
return [clientChanges, syncState, baseRevs, yResults];
|
|
3972
5394
|
}));
|
|
3973
|
-
const pushSyncIsNeeded = clientChangeSet.some((set) => set.muts.some((mut) => mut.keys.length > 0));
|
|
5395
|
+
const pushSyncIsNeeded = clientChangeSet.some((set) => set.muts.some((mut) => mut.keys.length > 0)) || yMessages.some(m => m.type === 'u-c');
|
|
3974
5396
|
if (justCheckIfNeeded) {
|
|
3975
5397
|
console.debug('Sync is needed:', pushSyncIsNeeded);
|
|
3976
5398
|
return pushSyncIsNeeded;
|
|
@@ -3985,12 +5407,12 @@ function _sync(db, options, schema, { isInitialSync, cancelToken, justCheckIfNee
|
|
|
3985
5407
|
// Push changes to server
|
|
3986
5408
|
//
|
|
3987
5409
|
throwIfCancelled(cancelToken);
|
|
3988
|
-
const res = yield syncWithServer(clientChangeSet, syncState, baseRevs, db, databaseUrl, schema, clientIdentity, currentUser);
|
|
5410
|
+
const res = yield syncWithServer(clientChangeSet, yMessages, syncState, baseRevs, db, databaseUrl, schema, clientIdentity, currentUser);
|
|
3989
5411
|
console.debug('Sync response', res);
|
|
3990
5412
|
//
|
|
3991
5413
|
// Apply changes locally and clear old change entries:
|
|
3992
5414
|
//
|
|
3993
|
-
const done = yield db.transaction('rw', db.tables, (tx) => __awaiter(this, void 0, void 0, function* () {
|
|
5415
|
+
const { done, newSyncState } = yield db.transaction('rw', db.tables, (tx) => __awaiter(this, void 0, void 0, function* () {
|
|
3994
5416
|
// @ts-ignore
|
|
3995
5417
|
tx.idbtrans.disableChangeTracking = true;
|
|
3996
5418
|
// @ts-ignore
|
|
@@ -4082,17 +5504,35 @@ function _sync(db, options, schema, { isInitialSync, cancelToken, justCheckIfNee
|
|
|
4082
5504
|
// apply server changes
|
|
4083
5505
|
//
|
|
4084
5506
|
yield applyServerChanges(filteredChanges, db);
|
|
5507
|
+
if (res.yMessages) {
|
|
5508
|
+
//
|
|
5509
|
+
// apply yMessages
|
|
5510
|
+
//
|
|
5511
|
+
const receivedUntils = yield applyYServerMessages(res.yMessages, db);
|
|
5512
|
+
//
|
|
5513
|
+
// update Y SyncStates
|
|
5514
|
+
//
|
|
5515
|
+
yield updateYSyncStates(lastUpdateIds, receivedUntils, db, res.serverRevision);
|
|
5516
|
+
}
|
|
4085
5517
|
//
|
|
4086
|
-
// Update syncState
|
|
5518
|
+
// Update regular syncState
|
|
4087
5519
|
//
|
|
4088
5520
|
db.$syncState.put(newSyncState, 'syncState');
|
|
4089
|
-
return
|
|
5521
|
+
return {
|
|
5522
|
+
done: addedClientChanges.length === 0,
|
|
5523
|
+
newSyncState
|
|
5524
|
+
};
|
|
4090
5525
|
}));
|
|
4091
5526
|
if (!done) {
|
|
4092
5527
|
console.debug('MORE SYNC NEEDED. Go for it again!');
|
|
4093
5528
|
yield checkSyncRateLimitDelay(db);
|
|
4094
5529
|
return yield _sync(db, options, schema, { isInitialSync, cancelToken });
|
|
4095
5530
|
}
|
|
5531
|
+
const usingYProps = Object.values(schema).some(tbl => { var _a; return (_a = tbl.yProps) === null || _a === void 0 ? void 0 : _a.length; });
|
|
5532
|
+
const serverSupportsYprops = !!res.yMessages;
|
|
5533
|
+
if (usingYProps && serverSupportsYprops) {
|
|
5534
|
+
yield downloadYDocsFromServer(db, databaseUrl, newSyncState);
|
|
5535
|
+
}
|
|
4096
5536
|
console.debug('SYNC DONE', { isInitialSync });
|
|
4097
5537
|
db.syncCompleteEvent.next();
|
|
4098
5538
|
return false; // Not needed anymore
|
|
@@ -4145,6 +5585,18 @@ function deleteObjectsFromRemovedRealms(db, res, prevState) {
|
|
|
4145
5585
|
}
|
|
4146
5586
|
}
|
|
4147
5587
|
}
|
|
5588
|
+
if (rejectedRealms.size > 0) {
|
|
5589
|
+
// Remove rejected/deleted realms from yDownloadedRealms because of the following use case:
|
|
5590
|
+
// 1. User becomes added to the realm
|
|
5591
|
+
// 2. User syncs and all documents of the realm is downloaded (downloadYDocsFromServer.ts)
|
|
5592
|
+
// 3. User leaves the realm and all docs are deleted locally (built-in-trigger of deleting their rows in this file)
|
|
5593
|
+
// 4. User is yet again added to the realm. At this point, we must make sure the docs are not considered already downloaded.
|
|
5594
|
+
const updateSpec = {};
|
|
5595
|
+
for (const realmId of rejectedRealms) {
|
|
5596
|
+
updateSpec[`yDownloadedRealms.${realmId}`] = undefined; // Setting to undefined will delete the property
|
|
5597
|
+
}
|
|
5598
|
+
yield db.$syncState.update('syncState', updateSpec);
|
|
5599
|
+
}
|
|
4148
5600
|
});
|
|
4149
5601
|
}
|
|
4150
5602
|
function filterServerChangesThroughAddedClientChanges(serverChanges, addedClientChanges) {
|
|
@@ -4156,13 +5608,15 @@ function filterServerChangesThroughAddedClientChanges(serverChanges, addedClient
|
|
|
4156
5608
|
return toDBOperationSet(changes);
|
|
4157
5609
|
}
|
|
4158
5610
|
|
|
5611
|
+
const LIMIT_NUM_MESSAGES_PER_TIME = 10; // Allow a maximum of 10 messages per...
|
|
5612
|
+
const TIME_WINDOW = 10000; // ...10 seconds.
|
|
5613
|
+
const PAUSE_PERIOD = 1000; // Pause for 1 second if reached
|
|
4159
5614
|
function MessagesFromServerConsumer(db) {
|
|
4160
5615
|
const queue = [];
|
|
4161
5616
|
const readyToServe = new BehaviorSubject(true);
|
|
4162
5617
|
const event = new BehaviorSubject(null);
|
|
4163
5618
|
let isWorking = false;
|
|
4164
|
-
let
|
|
4165
|
-
let loopDetection = [0, 0, 0, 0, 0, 0, 0, 0, 0, Date.now()];
|
|
5619
|
+
let loopDetection = new Array(LIMIT_NUM_MESSAGES_PER_TIME).fill(0);
|
|
4166
5620
|
event.subscribe(() => __awaiter(this, void 0, void 0, function* () {
|
|
4167
5621
|
if (isWorking)
|
|
4168
5622
|
return;
|
|
@@ -4176,20 +5630,11 @@ function MessagesFromServerConsumer(db) {
|
|
|
4176
5630
|
}
|
|
4177
5631
|
finally {
|
|
4178
5632
|
if (loopDetection[loopDetection.length - 1] - loopDetection[0] <
|
|
4179
|
-
|
|
5633
|
+
TIME_WINDOW) {
|
|
4180
5634
|
// Ten loops within 10 seconds. Slow down!
|
|
4181
|
-
|
|
4182
|
-
|
|
4183
|
-
|
|
4184
|
-
loopWarning = Date.now() + 60000;
|
|
4185
|
-
yield new Promise((resolve) => setTimeout(resolve, 60000));
|
|
4186
|
-
}
|
|
4187
|
-
else {
|
|
4188
|
-
// This is a one-time event. Just pause 10 seconds.
|
|
4189
|
-
console.warn(`Slowing down websocket loop for 10 seconds`);
|
|
4190
|
-
loopWarning = Date.now() + 10000;
|
|
4191
|
-
yield new Promise((resolve) => setTimeout(resolve, 10000));
|
|
4192
|
-
}
|
|
5635
|
+
// This is a one-time event. Just pause 10 seconds.
|
|
5636
|
+
console.warn(`Slowing down websocket loop for ${PAUSE_PERIOD} milliseconds`);
|
|
5637
|
+
yield new Promise((resolve) => setTimeout(resolve, PAUSE_PERIOD));
|
|
4193
5638
|
}
|
|
4194
5639
|
isWorking = false;
|
|
4195
5640
|
readyToServe.next(true);
|
|
@@ -4461,6 +5906,7 @@ function DexieCloudDB(dx) {
|
|
|
4461
5906
|
};
|
|
4462
5907
|
Object.assign(db, helperMethods);
|
|
4463
5908
|
db.messageConsumer = MessagesFromServerConsumer(db);
|
|
5909
|
+
db.messageProducer = new Subject();
|
|
4464
5910
|
wm.set(dx.cloud, db);
|
|
4465
5911
|
}
|
|
4466
5912
|
return db;
|
|
@@ -4490,24 +5936,6 @@ const safariVersion = isSafari
|
|
|
4490
5936
|
const DISABLE_SERVICEWORKER_STRATEGY = (isSafari && safariVersion <= 605) || // Disable for Safari for now.
|
|
4491
5937
|
isFirefox; // Disable for Firefox for now. Seems to have a bug in reading CryptoKeys from IDB from service workers
|
|
4492
5938
|
|
|
4493
|
-
/* Helper function to subscribe to database close no matter if it was unexpectedly closed or manually using db.close()
|
|
4494
|
-
*/
|
|
4495
|
-
function dbOnClosed(db, handler) {
|
|
4496
|
-
db.on.close.subscribe(handler);
|
|
4497
|
-
// @ts-ignore
|
|
4498
|
-
const origClose = db._close;
|
|
4499
|
-
// @ts-ignore
|
|
4500
|
-
db._close = function () {
|
|
4501
|
-
origClose.call(this);
|
|
4502
|
-
handler();
|
|
4503
|
-
};
|
|
4504
|
-
return () => {
|
|
4505
|
-
db.on.close.unsubscribe(handler);
|
|
4506
|
-
// @ts-ignore
|
|
4507
|
-
db._close = origClose;
|
|
4508
|
-
};
|
|
4509
|
-
}
|
|
4510
|
-
|
|
4511
5939
|
const IS_SERVICE_WORKER = typeof self !== "undefined" && "clients" in self && !self.document;
|
|
4512
5940
|
|
|
4513
5941
|
function throwVersionIncrementNeeded() {
|
|
@@ -4973,13 +6401,18 @@ function createMutationTrackingMiddleware({ currentUserObservable, db, }) {
|
|
|
4973
6401
|
values = values.filter((_, idx) => !failures[idx]);
|
|
4974
6402
|
}
|
|
4975
6403
|
const ts = Date.now();
|
|
6404
|
+
// Canonicalize req.criteria.index to null if it's on the primary key.
|
|
6405
|
+
const criteria = 'criteria' in req && req.criteria
|
|
6406
|
+
? Object.assign(Object.assign({}, req.criteria), { index: req.criteria.index === schema.primaryKey.keyPath // Use null to inform server that criteria is on primary key
|
|
6407
|
+
? null // This will disable the server from trying to log consistent operations where it shouldnt.
|
|
6408
|
+
: req.criteria.index }) : undefined;
|
|
4976
6409
|
const mut = req.type === 'delete'
|
|
4977
6410
|
? {
|
|
4978
6411
|
type: 'delete',
|
|
4979
6412
|
ts,
|
|
4980
6413
|
opNo,
|
|
4981
6414
|
keys,
|
|
4982
|
-
criteria
|
|
6415
|
+
criteria,
|
|
4983
6416
|
txid,
|
|
4984
6417
|
userId,
|
|
4985
6418
|
}
|
|
@@ -4993,14 +6426,14 @@ function createMutationTrackingMiddleware({ currentUserObservable, db, }) {
|
|
|
4993
6426
|
userId,
|
|
4994
6427
|
values,
|
|
4995
6428
|
}
|
|
4996
|
-
:
|
|
6429
|
+
: criteria && req.changeSpec
|
|
4997
6430
|
? {
|
|
4998
6431
|
// Common changeSpec for all keys
|
|
4999
6432
|
type: 'modify',
|
|
5000
6433
|
ts,
|
|
5001
6434
|
opNo,
|
|
5002
6435
|
keys,
|
|
5003
|
-
criteria
|
|
6436
|
+
criteria,
|
|
5004
6437
|
changeSpec: req.changeSpec,
|
|
5005
6438
|
txid,
|
|
5006
6439
|
userId,
|
|
@@ -5028,7 +6461,7 @@ function createMutationTrackingMiddleware({ currentUserObservable, db, }) {
|
|
|
5028
6461
|
if ('isAdditionalChunk' in req && req.isAdditionalChunk) {
|
|
5029
6462
|
mut.isAdditionalChunk = true;
|
|
5030
6463
|
}
|
|
5031
|
-
return keys.length > 0 ||
|
|
6464
|
+
return keys.length > 0 || criteria
|
|
5032
6465
|
? mutsTable
|
|
5033
6466
|
.mutate({ type: 'add', trans, values: [mut] }) // Log entry
|
|
5034
6467
|
.then(() => res) // Return original response
|
|
@@ -5042,6 +6475,7 @@ function createMutationTrackingMiddleware({ currentUserObservable, db, }) {
|
|
|
5042
6475
|
|
|
5043
6476
|
function overrideParseStoresSpec(origFunc, dexie) {
|
|
5044
6477
|
return function (stores, dbSchema) {
|
|
6478
|
+
var _a;
|
|
5045
6479
|
const storesClone = Object.assign(Object.assign({}, DEXIE_CLOUD_SCHEMA), stores);
|
|
5046
6480
|
// Merge indexes of DEXIE_CLOUD_SCHEMA with stores
|
|
5047
6481
|
Object.keys(DEXIE_CLOUD_SCHEMA).forEach((tableName) => {
|
|
@@ -5102,6 +6536,14 @@ function overrideParseStoresSpec(origFunc, dexie) {
|
|
|
5102
6536
|
}
|
|
5103
6537
|
});
|
|
5104
6538
|
const rv = origFunc.call(this, storesClone, dbSchema);
|
|
6539
|
+
for (const [tableName, spec] of Object.entries(dbSchema)) {
|
|
6540
|
+
if ((_a = spec.yProps) === null || _a === void 0 ? void 0 : _a.length) {
|
|
6541
|
+
const cloudTableSchema = cloudSchema[tableName];
|
|
6542
|
+
if (cloudTableSchema) {
|
|
6543
|
+
cloudTableSchema.yProps = spec.yProps.map((yProp) => yProp.prop);
|
|
6544
|
+
}
|
|
6545
|
+
}
|
|
6546
|
+
}
|
|
5105
6547
|
return rv;
|
|
5106
6548
|
};
|
|
5107
6549
|
}
|
|
@@ -5187,31 +6629,90 @@ class TokenExpiredError extends Error {
|
|
|
5187
6629
|
}
|
|
5188
6630
|
}
|
|
5189
6631
|
|
|
6632
|
+
function createYClientUpdateObservable(db) {
|
|
6633
|
+
const yTableRecords = flatten(db.tables
|
|
6634
|
+
.filter((table) => { var _a, _b; return ((_b = (_a = db.cloud.schema) === null || _a === void 0 ? void 0 : _a[table.name]) === null || _b === void 0 ? void 0 : _b.markedForSync) && table.schema.yProps; })
|
|
6635
|
+
.map((table) => table.schema.yProps.map((p) => ({
|
|
6636
|
+
table: table.name,
|
|
6637
|
+
ydocProp: p.prop,
|
|
6638
|
+
updatesTable: p.updatesTable,
|
|
6639
|
+
}))));
|
|
6640
|
+
return merge(...yTableRecords.map(({ table, ydocProp, updatesTable }) => {
|
|
6641
|
+
// Per updates table (table+prop combo), we first read syncer.unsentFrom,
|
|
6642
|
+
// and then start listening for updates since that number.
|
|
6643
|
+
const yTbl = db.table(updatesTable);
|
|
6644
|
+
return from$1(yTbl.get(DEXIE_CLOUD_SYNCER_ID)).pipe(switchMap$1((syncer) => {
|
|
6645
|
+
let currentUnsentFrom = (syncer === null || syncer === void 0 ? void 0 : syncer.unsentFrom) || 1;
|
|
6646
|
+
return from$1(liveQuery(() => __awaiter(this, void 0, void 0, function* () {
|
|
6647
|
+
const addedUpdates = yield listUpdatesSince(yTbl, currentUnsentFrom);
|
|
6648
|
+
return addedUpdates
|
|
6649
|
+
.filter((update) => update.f && update.f & 1) // Only include local updates
|
|
6650
|
+
.map((update) => {
|
|
6651
|
+
return {
|
|
6652
|
+
type: 'u-c',
|
|
6653
|
+
table,
|
|
6654
|
+
prop: ydocProp,
|
|
6655
|
+
k: update.k,
|
|
6656
|
+
u: update.u,
|
|
6657
|
+
i: update.i,
|
|
6658
|
+
};
|
|
6659
|
+
});
|
|
6660
|
+
}))).pipe(tap$1((addedUpdates) => {
|
|
6661
|
+
// Update currentUnsentFrom to only listen for updates that will be newer than the ones we emitted.
|
|
6662
|
+
// (Before, we did this within the liveQuery, but that caused a bug because
|
|
6663
|
+
// a cancelled emittion of a liveQuery would update the currentUnsentFrom without
|
|
6664
|
+
// emitting anything, leading to that we jumped over some updates. Here we update it
|
|
6665
|
+
// after the liveQuery has emitted its updates)
|
|
6666
|
+
if (addedUpdates.length > 0) {
|
|
6667
|
+
currentUnsentFrom = addedUpdates.at(-1).i + 1;
|
|
6668
|
+
}
|
|
6669
|
+
}));
|
|
6670
|
+
}));
|
|
6671
|
+
})).pipe(
|
|
6672
|
+
// Flatten the array of messages.
|
|
6673
|
+
// If messageProducer emits empty array, nothing is emitted
|
|
6674
|
+
// but if messageProducer emits array of messages, they are
|
|
6675
|
+
// emitted one by one.
|
|
6676
|
+
mergeMap$1((messages) => messages), tap$1((message) => {
|
|
6677
|
+
console.debug('dexie-cloud emitting y-c', message);
|
|
6678
|
+
}));
|
|
6679
|
+
}
|
|
6680
|
+
|
|
6681
|
+
function getAwarenessLibrary(db) {
|
|
6682
|
+
var _a, _b;
|
|
6683
|
+
if (!((_a = db.cloud.options) === null || _a === void 0 ? void 0 : _a.awarenessProtocol)) {
|
|
6684
|
+
throw new Dexie.MissingAPIError('awarenessProtocol was not provided to db.cloud.configure(). Please import * as awarenessProtocol from "y-protocols/awareness".');
|
|
6685
|
+
}
|
|
6686
|
+
return (_b = db.cloud.options) === null || _b === void 0 ? void 0 : _b.awarenessProtocol;
|
|
6687
|
+
}
|
|
6688
|
+
const awarenessWeakMap = new WeakMap();
|
|
6689
|
+
const getDocAwareness = (doc) => awarenessWeakMap.get(doc);
|
|
6690
|
+
|
|
5190
6691
|
const SERVER_PING_TIMEOUT = 20000;
|
|
5191
6692
|
const CLIENT_PING_INTERVAL = 30000;
|
|
5192
6693
|
const FAIL_RETRY_WAIT_TIME = 60000;
|
|
5193
6694
|
class WSObservable extends Observable$1 {
|
|
5194
|
-
constructor(
|
|
5195
|
-
super((subscriber) => new WSConnection(
|
|
6695
|
+
constructor(db, rev, realmSetHash, clientIdentity, messageProducer, webSocketStatus, user) {
|
|
6696
|
+
super((subscriber) => new WSConnection(db, rev, realmSetHash, clientIdentity, user, subscriber, messageProducer, webSocketStatus));
|
|
5196
6697
|
}
|
|
5197
6698
|
}
|
|
5198
6699
|
let counter = 0;
|
|
5199
6700
|
class WSConnection extends Subscription$1 {
|
|
5200
|
-
constructor(
|
|
6701
|
+
constructor(db, rev, realmSetHash, clientIdentity, user, subscriber, messageProducer, webSocketStatus) {
|
|
5201
6702
|
super(() => this.teardown());
|
|
5202
6703
|
this.id = ++counter;
|
|
6704
|
+
this.subscriptions = new Set();
|
|
5203
6705
|
this.reconnecting = false;
|
|
5204
|
-
console.debug('New WebSocket Connection', this.id,
|
|
5205
|
-
this.
|
|
6706
|
+
console.debug('New WebSocket Connection', this.id, user.accessToken ? 'authorized' : 'unauthorized');
|
|
6707
|
+
this.db = db;
|
|
6708
|
+
this.databaseUrl = db.cloud.options.databaseUrl;
|
|
5206
6709
|
this.rev = rev;
|
|
5207
6710
|
this.realmSetHash = realmSetHash;
|
|
5208
6711
|
this.clientIdentity = clientIdentity;
|
|
5209
|
-
this.
|
|
5210
|
-
this.tokenExpiration = tokenExpiration;
|
|
6712
|
+
this.user = user;
|
|
5211
6713
|
this.subscriber = subscriber;
|
|
5212
6714
|
this.lastUserActivity = new Date();
|
|
5213
6715
|
this.messageProducer = messageProducer;
|
|
5214
|
-
this.messageProducerSubscription = null;
|
|
5215
6716
|
this.webSocketStatus = webSocketStatus;
|
|
5216
6717
|
this.connect();
|
|
5217
6718
|
}
|
|
@@ -5232,10 +6733,10 @@ class WSConnection extends Subscription$1 {
|
|
|
5232
6733
|
catch (_a) { }
|
|
5233
6734
|
}
|
|
5234
6735
|
this.ws = null;
|
|
5235
|
-
|
|
5236
|
-
|
|
5237
|
-
this.messageProducerSubscription = null;
|
|
6736
|
+
for (const sub of this.subscriptions) {
|
|
6737
|
+
sub.unsubscribe();
|
|
5238
6738
|
}
|
|
6739
|
+
this.subscriptions.clear();
|
|
5239
6740
|
}
|
|
5240
6741
|
reconnect() {
|
|
5241
6742
|
if (this.reconnecting)
|
|
@@ -5268,7 +6769,8 @@ class WSConnection extends Subscription$1 {
|
|
|
5268
6769
|
//console.debug('SyncStatus: DUBB: Ooops it was closed!');
|
|
5269
6770
|
return;
|
|
5270
6771
|
}
|
|
5271
|
-
|
|
6772
|
+
const tokenExpiration = this.user.accessTokenExpiration;
|
|
6773
|
+
if (tokenExpiration && tokenExpiration < new Date()) {
|
|
5272
6774
|
this.subscriber.error(new TokenExpiredError()); // Will be handled in connectWebSocket.ts.
|
|
5273
6775
|
return;
|
|
5274
6776
|
}
|
|
@@ -5323,13 +6825,13 @@ class WSConnection extends Subscription$1 {
|
|
|
5323
6825
|
searchParams.set('rev', this.rev);
|
|
5324
6826
|
searchParams.set('realmsHash', this.realmSetHash);
|
|
5325
6827
|
searchParams.set('clientId', this.clientIdentity);
|
|
5326
|
-
if (this.
|
|
5327
|
-
searchParams.set('token', this.
|
|
6828
|
+
if (this.user.accessToken) {
|
|
6829
|
+
searchParams.set('token', this.user.accessToken);
|
|
5328
6830
|
}
|
|
5329
6831
|
// Connect the WebSocket to given url:
|
|
5330
6832
|
console.debug('dexie-cloud WebSocket create');
|
|
5331
6833
|
const ws = (this.ws = new WebSocket(`${wsUrl}/changes?${searchParams}`));
|
|
5332
|
-
|
|
6834
|
+
ws.binaryType = "arraybuffer";
|
|
5333
6835
|
ws.onclose = (event) => {
|
|
5334
6836
|
if (!this.pinger)
|
|
5335
6837
|
return;
|
|
@@ -5339,17 +6841,33 @@ class WSConnection extends Subscription$1 {
|
|
|
5339
6841
|
ws.onmessage = (event) => {
|
|
5340
6842
|
if (!this.pinger)
|
|
5341
6843
|
return;
|
|
5342
|
-
console.debug('dexie-cloud WebSocket onmessage', event.data);
|
|
5343
6844
|
this.lastServerActivity = new Date();
|
|
5344
6845
|
try {
|
|
5345
|
-
const msg =
|
|
6846
|
+
const msg = typeof event.data === 'string'
|
|
6847
|
+
? TSON.parse(event.data)
|
|
6848
|
+
: decodeYMessage(new Uint8Array(event.data));
|
|
6849
|
+
console.debug('dexie-cloud WebSocket onmessage', msg.type, msg);
|
|
5346
6850
|
if (msg.type === 'error') {
|
|
5347
6851
|
throw new Error(`Error message from dexie-cloud: ${msg.error}`);
|
|
5348
6852
|
}
|
|
5349
|
-
if (msg.type === 'rev') {
|
|
6853
|
+
else if (msg.type === 'rev') {
|
|
5350
6854
|
this.rev = msg.rev; // No meaning but seems reasonable.
|
|
5351
6855
|
}
|
|
5352
|
-
if (msg.type
|
|
6856
|
+
else if (msg.type === 'aware') {
|
|
6857
|
+
const docCache = DexieYProvider.getDocCache(this.db.dx);
|
|
6858
|
+
const doc = docCache.find(msg.table, msg.k, msg.prop);
|
|
6859
|
+
if (doc) {
|
|
6860
|
+
const awareness = getDocAwareness(doc);
|
|
6861
|
+
if (awareness) {
|
|
6862
|
+
const awap = getAwarenessLibrary(this.db);
|
|
6863
|
+
awap.applyAwarenessUpdate(awareness, msg.u, 'server');
|
|
6864
|
+
}
|
|
6865
|
+
}
|
|
6866
|
+
}
|
|
6867
|
+
else if (msg.type === 'u-ack' || msg.type === 'u-reject' || msg.type === 'u-s' || msg.type === 'in-sync') {
|
|
6868
|
+
applyYServerMessages([msg], this.db);
|
|
6869
|
+
}
|
|
6870
|
+
else if (msg.type !== 'pong') {
|
|
5353
6871
|
this.subscriber.next(msg);
|
|
5354
6872
|
}
|
|
5355
6873
|
}
|
|
@@ -5377,16 +6895,27 @@ class WSConnection extends Subscription$1 {
|
|
|
5377
6895
|
}
|
|
5378
6896
|
};
|
|
5379
6897
|
});
|
|
5380
|
-
this.
|
|
5381
|
-
var _a;
|
|
6898
|
+
this.subscriptions.add(this.messageProducer.subscribe((msg) => {
|
|
6899
|
+
var _a, _b;
|
|
5382
6900
|
if (!this.closed) {
|
|
5383
6901
|
if (msg.type === 'ready' &&
|
|
5384
6902
|
this.webSocketStatus.value !== 'connected') {
|
|
5385
6903
|
this.webSocketStatus.next('connected');
|
|
5386
6904
|
}
|
|
5387
|
-
(
|
|
6905
|
+
console.debug('dexie-cloud WebSocket send', msg.type, msg);
|
|
6906
|
+
if (msg.type === 'ready') {
|
|
6907
|
+
(_a = this.ws) === null || _a === void 0 ? void 0 : _a.send(TSON.stringify(msg));
|
|
6908
|
+
}
|
|
6909
|
+
else {
|
|
6910
|
+
// If it's not a "ready" message, it's an YMessage.
|
|
6911
|
+
// YMessages can be sent binary encoded.
|
|
6912
|
+
(_b = this.ws) === null || _b === void 0 ? void 0 : _b.send(encodeYMessage(msg));
|
|
6913
|
+
}
|
|
5388
6914
|
}
|
|
5389
|
-
});
|
|
6915
|
+
}));
|
|
6916
|
+
if (this.user.isLoggedIn && !isEagerSyncDisabled(this.db)) {
|
|
6917
|
+
this.subscriptions.add(createYClientUpdateObservable(this.db).subscribe(this.db.messageProducer));
|
|
6918
|
+
}
|
|
5390
6919
|
}
|
|
5391
6920
|
catch (error) {
|
|
5392
6921
|
this.pauseUntil = new Date(Date.now() + FAIL_RETRY_WAIT_TIME);
|
|
@@ -5428,7 +6957,7 @@ function connectWebSocket(db) {
|
|
|
5428
6957
|
if (!((_a = db.cloud.options) === null || _a === void 0 ? void 0 : _a.databaseUrl)) {
|
|
5429
6958
|
throw new Error(`No database URL to connect WebSocket to`);
|
|
5430
6959
|
}
|
|
5431
|
-
const
|
|
6960
|
+
const readyForChangesMessage = db.messageConsumer.readyToServe.pipe(filter((isReady) => isReady), // When consumer is ready for new messages, produce such a message to inform server about it
|
|
5432
6961
|
switchMap(() => db.getPersistedSyncState()), // We need the info on which server revision we are at:
|
|
5433
6962
|
filter((syncState) => syncState && syncState.serverRevision), // We wont send anything to server before inital sync has taken place
|
|
5434
6963
|
switchMap((syncState) => __awaiter(this, void 0, void 0, function* () {
|
|
@@ -5439,6 +6968,7 @@ function connectWebSocket(db) {
|
|
|
5439
6968
|
realmSetHash: yield computeRealmSetHash(syncState)
|
|
5440
6969
|
});
|
|
5441
6970
|
})));
|
|
6971
|
+
const messageProducer = merge(readyForChangesMessage, db.messageProducer);
|
|
5442
6972
|
function createObservable() {
|
|
5443
6973
|
return db.cloud.persistedSyncState.pipe(filter((syncState) => syncState === null || syncState === void 0 ? void 0 : syncState.serverRevision), // Don't connect before there's no initial sync performed.
|
|
5444
6974
|
take(1), // Don't continue waking up whenever syncState change
|
|
@@ -5465,7 +6995,7 @@ function connectWebSocket(db) {
|
|
|
5465
6995
|
// If no new entries, server won't bother the client. If new entries, server sends only those
|
|
5466
6996
|
// and the baseRev of the last from same client-ID.
|
|
5467
6997
|
if (userLogin) {
|
|
5468
|
-
return new WSObservable(db
|
|
6998
|
+
return new WSObservable(db, db.cloud.persistedSyncState.value.serverRevision, realmSetHash, db.cloud.persistedSyncState.value.clientIdentity, messageProducer, db.cloud.webSocketStatus, userLogin);
|
|
5469
6999
|
}
|
|
5470
7000
|
else {
|
|
5471
7001
|
return from$1([]);
|
|
@@ -6271,6 +7801,130 @@ const getInvitesObservable = associate((db) => {
|
|
|
6271
7801
|
})), []);
|
|
6272
7802
|
});
|
|
6273
7803
|
|
|
7804
|
+
function createYHandler(db) {
|
|
7805
|
+
return (provider) => {
|
|
7806
|
+
var _a;
|
|
7807
|
+
const awap = getAwarenessLibrary(db);
|
|
7808
|
+
const doc = provider.doc;
|
|
7809
|
+
const { parentTable, parentId, parentProp, updatesTable } = doc.meta;
|
|
7810
|
+
if (!((_a = db.cloud.schema) === null || _a === void 0 ? void 0 : _a[parentTable].markedForSync)) {
|
|
7811
|
+
return; // The table that holds the doc is not marked for sync - leave it to dexie. No syncing, no awareness.
|
|
7812
|
+
}
|
|
7813
|
+
let awareness = new awap.Awareness(doc);
|
|
7814
|
+
awarenessWeakMap.set(doc, awareness);
|
|
7815
|
+
provider.awareness = awareness;
|
|
7816
|
+
awareness.on('update', ({ added, updated, removed }, origin) => {
|
|
7817
|
+
// Send the update
|
|
7818
|
+
const changedClients = added.concat(updated).concat(removed);
|
|
7819
|
+
const user = db.cloud.currentUser.value;
|
|
7820
|
+
if (origin !== 'server' && user.isLoggedIn && !isEagerSyncDisabled(db)) {
|
|
7821
|
+
const update = awap.encodeAwarenessUpdate(awareness, changedClients);
|
|
7822
|
+
db.messageProducer.next({
|
|
7823
|
+
type: 'aware',
|
|
7824
|
+
table: parentTable,
|
|
7825
|
+
prop: parentProp,
|
|
7826
|
+
k: doc.meta.parentId,
|
|
7827
|
+
u: update,
|
|
7828
|
+
});
|
|
7829
|
+
if (provider.destroyed) {
|
|
7830
|
+
// We're called from awareness.on('destroy') that did
|
|
7831
|
+
// removeAwarenessStates.
|
|
7832
|
+
// It's time to also send the doc-close message that dexie-cloud understands
|
|
7833
|
+
// and uses to stop subscribing for updates and awareness updates and brings
|
|
7834
|
+
// down the cached information in memory on the WS connection for this.
|
|
7835
|
+
db.messageProducer.next({
|
|
7836
|
+
type: 'doc-close',
|
|
7837
|
+
table: parentTable,
|
|
7838
|
+
prop: parentProp,
|
|
7839
|
+
k: doc.meta.parentId
|
|
7840
|
+
});
|
|
7841
|
+
}
|
|
7842
|
+
}
|
|
7843
|
+
});
|
|
7844
|
+
awareness.on('destroy', () => {
|
|
7845
|
+
// Signal to server that this provider is destroyed (the update event will be triggered, which
|
|
7846
|
+
// in turn will trigger db.messageProducer that will send the message to the server if WS is connected)
|
|
7847
|
+
awap.removeAwarenessStates(awareness, [doc.clientID], 'provider destroyed');
|
|
7848
|
+
});
|
|
7849
|
+
// Now wait til document is loaded and then open the document on the server
|
|
7850
|
+
provider.on('load', () => __awaiter(this, void 0, void 0, function* () {
|
|
7851
|
+
if (provider.destroyed)
|
|
7852
|
+
return;
|
|
7853
|
+
let connected = false;
|
|
7854
|
+
let currentFlowId = 1;
|
|
7855
|
+
const subscription = db.cloud.webSocketStatus.subscribe((wsStatus) => {
|
|
7856
|
+
if (provider.destroyed)
|
|
7857
|
+
return;
|
|
7858
|
+
// Keep "connected" state in a variable so we can check it after async operations
|
|
7859
|
+
connected = wsStatus === 'connected';
|
|
7860
|
+
// We are or got connected. Open the document on the server.
|
|
7861
|
+
const user = db.cloud.currentUser.value;
|
|
7862
|
+
if (wsStatus === "connected" && user.isLoggedIn && !isEagerSyncDisabled(db)) {
|
|
7863
|
+
++currentFlowId;
|
|
7864
|
+
openDocumentOnServer().catch(error => {
|
|
7865
|
+
console.warn(`Error catched in createYHandler.ts: ${error}`);
|
|
7866
|
+
});
|
|
7867
|
+
}
|
|
7868
|
+
});
|
|
7869
|
+
// Wait until WebSocket is connected
|
|
7870
|
+
provider.addCleanupHandler(subscription);
|
|
7871
|
+
/** Sends an 'doc-open' message to server whenever websocket becomes
|
|
7872
|
+
* connected, or if it is already connected.
|
|
7873
|
+
* The flow is aborted in case websocket is disconnected while querying
|
|
7874
|
+
* information required to compute the state vector. Flow is also
|
|
7875
|
+
* aborted in case document or provider has been destroyed during
|
|
7876
|
+
* the async parts of the task.
|
|
7877
|
+
*
|
|
7878
|
+
* The state vector is only computed from the updates that have occured
|
|
7879
|
+
* after the last full sync - which could very often be zero - in which
|
|
7880
|
+
* case no state vector is sent (then the server already knows us by
|
|
7881
|
+
* revision)
|
|
7882
|
+
*
|
|
7883
|
+
* When server gets the doc-open message, it will authorized us for
|
|
7884
|
+
* whether we are allowed to read / write to this document, and then
|
|
7885
|
+
* keep the cached information in memory on the WS connection for this
|
|
7886
|
+
* particular document, as well as subscribe to updates and awareness updates
|
|
7887
|
+
* from other clients on the document.
|
|
7888
|
+
*/
|
|
7889
|
+
function openDocumentOnServer(wsStatus) {
|
|
7890
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
7891
|
+
const myFlow = currentFlowId; // So we can abort when a new flow is started
|
|
7892
|
+
const yTbl = db.table(updatesTable);
|
|
7893
|
+
const syncState = yield yTbl.get(DEXIE_CLOUD_SYNCER_ID);
|
|
7894
|
+
// After every await, check if we still should be working on this task.
|
|
7895
|
+
if (provider.destroyed || currentFlowId !== myFlow || !connected)
|
|
7896
|
+
return;
|
|
7897
|
+
const receivedUntil = (syncState === null || syncState === void 0 ? void 0 : syncState.receivedUntil) || 0;
|
|
7898
|
+
const docOpenMsg = {
|
|
7899
|
+
type: 'doc-open',
|
|
7900
|
+
table: parentTable,
|
|
7901
|
+
prop: parentProp,
|
|
7902
|
+
k: parentId,
|
|
7903
|
+
serverRev: syncState === null || syncState === void 0 ? void 0 : syncState.serverRev,
|
|
7904
|
+
};
|
|
7905
|
+
const serverUpdatesSinceLastSync = yield yTbl
|
|
7906
|
+
.where('i')
|
|
7907
|
+
.between(receivedUntil, Infinity, false)
|
|
7908
|
+
.filter((update) => cmp(update.k, parentId) === 0 && // Only updates for this document
|
|
7909
|
+
((update.f || 0) & 1) === 0 // Don't include local changes
|
|
7910
|
+
)
|
|
7911
|
+
.toArray();
|
|
7912
|
+
// After every await, check if we still should be working on this task.
|
|
7913
|
+
if (provider.destroyed || currentFlowId !== myFlow || !connected)
|
|
7914
|
+
return;
|
|
7915
|
+
if (serverUpdatesSinceLastSync.length > 0) {
|
|
7916
|
+
const Y = $Y(db); // Get the Yjs library from Dexie constructor options
|
|
7917
|
+
const mergedUpdate = Y.mergeUpdatesV2(serverUpdatesSinceLastSync.map((update) => update.u));
|
|
7918
|
+
const stateVector = Y.encodeStateVectorFromUpdateV2(mergedUpdate);
|
|
7919
|
+
docOpenMsg.sv = stateVector;
|
|
7920
|
+
}
|
|
7921
|
+
db.messageProducer.next(docOpenMsg);
|
|
7922
|
+
});
|
|
7923
|
+
}
|
|
7924
|
+
}));
|
|
7925
|
+
};
|
|
7926
|
+
}
|
|
7927
|
+
|
|
6274
7928
|
function getTiedRealmId(objectId) {
|
|
6275
7929
|
return 'rlm~' + objectId;
|
|
6276
7930
|
}
|
|
@@ -6307,8 +7961,9 @@ function dexieCloud(dexie) {
|
|
|
6307
7961
|
if (closed)
|
|
6308
7962
|
throw new Dexie.DatabaseClosedError();
|
|
6309
7963
|
}
|
|
6310
|
-
|
|
7964
|
+
dexie.once('close', () => {
|
|
6311
7965
|
subscriptions.forEach((subscription) => subscription.unsubscribe());
|
|
7966
|
+
subscriptions.splice(0, subscriptions.length);
|
|
6312
7967
|
closed = true;
|
|
6313
7968
|
localSyncWorker && localSyncWorker.stop();
|
|
6314
7969
|
localSyncWorker = null;
|
|
@@ -6317,7 +7972,7 @@ function dexieCloud(dexie) {
|
|
|
6317
7972
|
const syncComplete = new Subject();
|
|
6318
7973
|
dexie.cloud = {
|
|
6319
7974
|
// @ts-ignore
|
|
6320
|
-
version: "4.0.
|
|
7975
|
+
version: "4.1.0-alpha.10",
|
|
6321
7976
|
options: Object.assign({}, DEFAULT_OPTIONS),
|
|
6322
7977
|
schema: null,
|
|
6323
7978
|
get currentUserId() {
|
|
@@ -6463,6 +8118,7 @@ function dexieCloud(dexie) {
|
|
|
6463
8118
|
throw new Error(`Internal error`); // options cannot be null if configuredProgramatically is set.
|
|
6464
8119
|
const newPersistedOptions = Object.assign({}, options);
|
|
6465
8120
|
delete newPersistedOptions.fetchTokens;
|
|
8121
|
+
delete newPersistedOptions.awarenessProtocol;
|
|
6466
8122
|
yield db.$syncState.put(newPersistedOptions, 'options');
|
|
6467
8123
|
}
|
|
6468
8124
|
if (((_h = db.cloud.options) === null || _h === void 0 ? void 0 : _h.tryUseServiceWorker) &&
|
|
@@ -6540,12 +8196,29 @@ function dexieCloud(dexie) {
|
|
|
6540
8196
|
currentUserEmitter.pipe(skip(1), take(1)),
|
|
6541
8197
|
db.cloud.persistedSyncState.pipe(skip(1), take(1)),
|
|
6542
8198
|
]));
|
|
8199
|
+
const yHandler = createYHandler(db);
|
|
8200
|
+
db.dx.on('y', yHandler);
|
|
8201
|
+
db.dx.once('close', () => {
|
|
8202
|
+
var _a;
|
|
8203
|
+
(_a = db.dx.on.y) === null || _a === void 0 ? void 0 : _a.unsubscribe(yHandler);
|
|
8204
|
+
});
|
|
6543
8205
|
}
|
|
6544
8206
|
// HERE: If requireAuth, do athentication now.
|
|
6545
8207
|
let changedUser = false;
|
|
6546
8208
|
const user = yield db.getCurrentUser();
|
|
6547
|
-
|
|
6548
|
-
|
|
8209
|
+
const requireAuth = (_c = db.cloud.options) === null || _c === void 0 ? void 0 : _c.requireAuth;
|
|
8210
|
+
if (requireAuth) {
|
|
8211
|
+
if (typeof requireAuth === 'object') {
|
|
8212
|
+
// requireAuth contains login hints. Check if we already fulfil it:
|
|
8213
|
+
if (!user.isLoggedIn ||
|
|
8214
|
+
(requireAuth.userId && user.userId !== requireAuth.userId) ||
|
|
8215
|
+
(requireAuth.email && user.email !== requireAuth.email)) {
|
|
8216
|
+
// If not, login the configured user:
|
|
8217
|
+
changedUser = yield login(db, requireAuth);
|
|
8218
|
+
}
|
|
8219
|
+
}
|
|
8220
|
+
else if (!user.isLoggedIn) {
|
|
8221
|
+
// requireAuth is true and user is not logged in
|
|
6549
8222
|
changedUser = yield login(db);
|
|
6550
8223
|
}
|
|
6551
8224
|
}
|
|
@@ -6601,7 +8274,7 @@ function dexieCloud(dexie) {
|
|
|
6601
8274
|
}
|
|
6602
8275
|
}
|
|
6603
8276
|
// @ts-ignore
|
|
6604
|
-
dexieCloud.version = "4.0.
|
|
8277
|
+
dexieCloud.version = "4.1.0-alpha.10";
|
|
6605
8278
|
Dexie.Cloud = dexieCloud;
|
|
6606
8279
|
|
|
6607
8280
|
export { dexieCloud as default, dexieCloud, getTiedObjectId, getTiedRealmId, resolveText };
|