@evolu/common 1.0.9 → 1.0.11

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/src/Crdt.ts ADDED
@@ -0,0 +1,375 @@
1
+ import * as Schema from "@effect/schema/Schema";
2
+ import {
3
+ Brand,
4
+ Context,
5
+ Effect,
6
+ Either,
7
+ Layer,
8
+ Number,
9
+ Option,
10
+ ReadonlyArray,
11
+ String,
12
+ pipe,
13
+ } from "effect";
14
+ import { Config } from "./Config.js";
15
+ import { NanoId, NodeId } from "./Crypto.js";
16
+ import { murmurhash } from "./Murmurhash.js";
17
+
18
+ // https://muratbuffalo.blogspot.com/2014/07/hybrid-logical-clocks.html
19
+ // https://jaredforsyth.com/posts/hybrid-logical-clocks/
20
+ // https://github.com/clintharris/crdt-example-app_annotated/blob/master/shared/timestamp.js
21
+ // https://github.com/actualbudget/actual/tree/master/packages/crdt
22
+
23
+ export interface Timestamp {
24
+ readonly node: NodeId;
25
+ readonly millis: Millis;
26
+ readonly counter: Counter;
27
+ }
28
+
29
+ export const AllowedTimeRange = {
30
+ greaterThan: 860934419999,
31
+ lessThan: 2582803260000,
32
+ };
33
+
34
+ /**
35
+ * Millis represents a time that is valid for usage with the Merkle tree.
36
+ * It must be between Apr 13, 1997, and Nov 05, 2051, to ensure MinutesBase3
37
+ * length equals 16. We can find diff for two Merkle trees only within this range.
38
+ * If the device clock is out of range, Evolu will not store data until it's fixed.
39
+ */
40
+ export const Millis = Schema.number.pipe(
41
+ Schema.greaterThan(AllowedTimeRange.greaterThan),
42
+ Schema.lessThan(AllowedTimeRange.lessThan),
43
+ Schema.brand("Millis"),
44
+ );
45
+
46
+ export type Millis = Schema.Schema.To<typeof Millis>;
47
+
48
+ export const initialMillis = Schema.parseSync(Millis)(
49
+ AllowedTimeRange.greaterThan + 1,
50
+ );
51
+
52
+ export const Counter = Schema.number.pipe(
53
+ Schema.between(0, 65535),
54
+ Schema.brand("Counter"),
55
+ );
56
+ export type Counter = Schema.Schema.To<typeof Counter>;
57
+
58
+ const initialCounter = Schema.parseSync(Counter)(0);
59
+
60
+ export type TimestampHash = number & Brand.Brand<"TimestampHash">;
61
+
62
+ export type TimestampString = string & Brand.Brand<"TimestampString">;
63
+
64
+ export const timestampToString = (t: Timestamp): TimestampString =>
65
+ [
66
+ new Date(t.millis).toISOString(),
67
+ t.counter.toString(16).toUpperCase().padStart(4, "0"),
68
+ t.node,
69
+ ].join("-") as TimestampString;
70
+
71
+ export const unsafeTimestampFromString = (s: TimestampString): Timestamp => {
72
+ const a = s.split("-");
73
+ return {
74
+ millis: Date.parse(a.slice(0, 3).join("-")).valueOf() as Millis,
75
+ counter: parseInt(a[3], 16) as Counter,
76
+ node: a[4] as NodeId,
77
+ };
78
+ };
79
+
80
+ export const timestampToHash = (t: Timestamp): TimestampHash =>
81
+ murmurhash(timestampToString(t)) as TimestampHash;
82
+
83
+ const syncNodeId = Schema.parseSync(NodeId)("0000000000000000");
84
+
85
+ export const makeSyncTimestamp = (
86
+ millis: Millis = initialMillis,
87
+ ): Timestamp => ({
88
+ millis,
89
+ counter: initialCounter,
90
+ node: syncNodeId,
91
+ });
92
+
93
+ export const makeInitialTimestamp = NanoId.pipe(
94
+ Effect.flatMap(({ nanoidAsNodeId }) => nanoidAsNodeId),
95
+ Effect.map(
96
+ (node): Timestamp => ({
97
+ millis: initialMillis,
98
+ counter: initialCounter,
99
+ node,
100
+ }),
101
+ ),
102
+ );
103
+
104
+ export interface Time {
105
+ readonly now: Effect.Effect<never, TimestampTimeOutOfRangeError, Millis>;
106
+ }
107
+
108
+ export const Time = Context.Tag<Time>("evolu/Time");
109
+
110
+ export const TimeLive = Layer.succeed(
111
+ Time,
112
+ Time.of({
113
+ now: Effect.suspend(() => Schema.parse(Millis)(Date.now())).pipe(
114
+ Effect.catchTag("ParseError", () =>
115
+ Effect.fail<TimestampTimeOutOfRangeError>({
116
+ _tag: "TimestampTimeOutOfRangeError",
117
+ }),
118
+ ),
119
+ ),
120
+ }),
121
+ );
122
+
123
+ export type TimestampError =
124
+ | TimestampDriftError
125
+ | TimestampCounterOverflowError
126
+ | TimestampDuplicateNodeError
127
+ | TimestampTimeOutOfRangeError;
128
+
129
+ export interface TimestampDriftError {
130
+ readonly _tag: "TimestampDriftError";
131
+ readonly next: Millis;
132
+ readonly now: Millis;
133
+ }
134
+
135
+ export interface TimestampCounterOverflowError {
136
+ readonly _tag: "TimestampCounterOverflowError";
137
+ }
138
+
139
+ export interface TimestampDuplicateNodeError {
140
+ readonly _tag: "TimestampDuplicateNodeError";
141
+ readonly node: NodeId;
142
+ }
143
+
144
+ export interface TimestampTimeOutOfRangeError {
145
+ readonly _tag: "TimestampTimeOutOfRangeError";
146
+ }
147
+
148
+ const getNextMillis = (
149
+ millis: ReadonlyArray<Millis>,
150
+ ): Effect.Effect<
151
+ Time | Config,
152
+ TimestampDriftError | TimestampTimeOutOfRangeError,
153
+ Millis
154
+ > =>
155
+ Effect.gen(function* (_) {
156
+ const time = yield* _(Time);
157
+ const config = yield* _(Config);
158
+
159
+ const now = yield* _(time.now);
160
+ const next = Math.max(now, ...millis) as Millis;
161
+
162
+ if (next - now > config.maxDrift)
163
+ yield* _(
164
+ Effect.fail<TimestampDriftError>({
165
+ _tag: "TimestampDriftError",
166
+ now,
167
+ next,
168
+ }),
169
+ );
170
+
171
+ return next;
172
+ });
173
+
174
+ const incrementCounter = (
175
+ counter: Counter,
176
+ ): Either.Either<TimestampCounterOverflowError, Counter> =>
177
+ pipe(
178
+ Number.increment(counter),
179
+ Schema.parseEither(Counter),
180
+ Either.mapLeft(() => ({ _tag: "TimestampCounterOverflowError" })),
181
+ );
182
+
183
+ const counterMin = Schema.parseSync(Counter)(0);
184
+
185
+ export const sendTimestamp = (
186
+ timestamp: Timestamp,
187
+ ): Effect.Effect<
188
+ Time | Config,
189
+ | TimestampDriftError
190
+ | TimestampCounterOverflowError
191
+ | TimestampTimeOutOfRangeError,
192
+ Timestamp
193
+ > =>
194
+ Effect.gen(function* (_) {
195
+ const millis = yield* _(getNextMillis([timestamp.millis]));
196
+ const counter =
197
+ millis === timestamp.millis
198
+ ? yield* _(incrementCounter(timestamp.counter))
199
+ : counterMin;
200
+ return { ...timestamp, millis, counter };
201
+ });
202
+
203
+ export const receiveTimestamp = ({
204
+ local,
205
+ remote,
206
+ }: {
207
+ readonly local: Timestamp;
208
+ readonly remote: Timestamp;
209
+ }): Effect.Effect<
210
+ Time | Config,
211
+ | TimestampDriftError
212
+ | TimestampCounterOverflowError
213
+ | TimestampDuplicateNodeError
214
+ | TimestampTimeOutOfRangeError,
215
+ Timestamp
216
+ > =>
217
+ Effect.gen(function* (_) {
218
+ if (local.node === remote.node)
219
+ yield* _(
220
+ Effect.fail<TimestampDuplicateNodeError>({
221
+ _tag: "TimestampDuplicateNodeError",
222
+ node: local.node,
223
+ }),
224
+ );
225
+
226
+ const millis = yield* _(getNextMillis([local.millis, remote.millis]));
227
+ const counter = yield* _(
228
+ millis === local.millis && millis === remote.millis
229
+ ? incrementCounter(Math.max(local.counter, remote.counter) as Counter)
230
+ : millis === local.millis
231
+ ? incrementCounter(local.counter)
232
+ : millis === remote.millis
233
+ ? incrementCounter(remote.counter)
234
+ : Either.right(counterMin),
235
+ );
236
+
237
+ return { ...local, millis, counter };
238
+ });
239
+
240
+ /**
241
+ * It's actually not Merkle Tree but a Merkleized prefix tree, aka Merkle Trie.
242
+ * https://decomposition.al/blog/2019/05/31/how-i-learned-about-merklix-trees-without-having-to-become-a-cryptocurrency-enthusiast
243
+ */
244
+ export interface MerkleTree {
245
+ readonly hash?: TimestampHash;
246
+ readonly "0"?: MerkleTree;
247
+ readonly "1"?: MerkleTree;
248
+ readonly "2"?: MerkleTree;
249
+ }
250
+
251
+ export type MerkleTreeString = string & Brand.Brand<"MerkleTreeString">;
252
+
253
+ export const initialMerkleTree = Object.create(null) as MerkleTree;
254
+
255
+ type MerkleTreeKey = keyof Omit<MerkleTree, "hash">;
256
+
257
+ type MerkleTreePath = ReadonlyArray<MerkleTreeKey>;
258
+
259
+ export const millisToMerkleTreePath = (millis: Millis): MerkleTreePath =>
260
+ Math.floor(millis / 1000 / 60)
261
+ .toString(3)
262
+ .split("") as MerkleTreePath;
263
+
264
+ const merkleTreePathToMillis = (path: MerkleTreePath): Millis =>
265
+ path.length === 0
266
+ ? initialMillis
267
+ : // 16 is the length of the base 3 value of the current time in minutes.
268
+ // Ensure it's padded to create the full value.
269
+ ((parseInt(path.join("").padEnd(16, "0"), 3) * 1000 * 60) as Millis);
270
+
271
+ const xorTimestampHashes = (
272
+ a: TimestampHash | undefined,
273
+ b: TimestampHash,
274
+ ): TimestampHash => ((a || 0) ^ b) as TimestampHash;
275
+
276
+ const insertKey = (
277
+ tree: MerkleTree,
278
+ path: MerkleTreePath,
279
+ hash: TimestampHash,
280
+ ): MerkleTree => {
281
+ if (path.length === 0) return tree;
282
+ const key = path[0];
283
+ const child = tree[key] || {};
284
+ return {
285
+ ...tree,
286
+ [key]: {
287
+ ...child,
288
+ ...insertKey(child, path.slice(1), hash),
289
+ hash: xorTimestampHashes(child.hash, hash),
290
+ },
291
+ };
292
+ };
293
+
294
+ export const insertIntoMerkleTree =
295
+ (timestamp: Timestamp) =>
296
+ (tree: MerkleTree): MerkleTree => {
297
+ const path = millisToMerkleTreePath(timestamp.millis);
298
+ const hash = timestampToHash(timestamp);
299
+ return insertKey(
300
+ { ...tree, hash: xorTimestampHashes(tree.hash, hash) },
301
+ path,
302
+ hash,
303
+ );
304
+ };
305
+
306
+ const sortedMerkleTreeKeys: ReadonlyArray<MerkleTreeKey> = ["0", "1", "2"];
307
+
308
+ const getSortedMerkleTreeKeys = (
309
+ tree: MerkleTree,
310
+ ): ReadonlyArray<MerkleTreeKey> =>
311
+ sortedMerkleTreeKeys.filter((key) => key in tree);
312
+
313
+ export const diffMerkleTrees = (
314
+ tree1: MerkleTree,
315
+ tree2: MerkleTree,
316
+ ): Option.Option<Millis> => {
317
+ if (tree1.hash === tree2.hash) return Option.none();
318
+ let node1 = tree1;
319
+ let node2 = tree2;
320
+ let diffPath: MerkleTreePath = [];
321
+
322
+ // This loop will eventually stop when it traverses down to find
323
+ // where the hashes differ, or otherwise when there are no leaves
324
+ // left (this shouldn't happen, if that's the case the hash check at
325
+ // the top of this function should pass)
326
+ // eslint-disable-next-line no-constant-condition
327
+ while (1) {
328
+ const keys = ReadonlyArray.dedupeWith(
329
+ getSortedMerkleTreeKeys(node1).concat(getSortedMerkleTreeKeys(node2)),
330
+ String.Equivalence,
331
+ );
332
+ let diffKey: MerkleTreeKey | null = null;
333
+
334
+ // Traverse down the trie through keys that are different. We
335
+ // traverse down the keys in order. Stop in two cases: either one
336
+ // of the nodes doesn't have the key or a different key isn't
337
+ // found. For the former case, we have to do that because pruning is
338
+ // lossy. We don't know if we've pruned off a changed key, so we
339
+ // can't traverse down anymore. For the latter case, it means two
340
+ // things: either we've hit the bottom of the tree, or the changed
341
+ // key has been pruned off. In the latter case, we have a "partial"
342
+ // key and will fill the rest with 0s. If multiple older
343
+ // messages were added into one trie, we might likely
344
+ // generate a time that only encompasses *some* of those
345
+ // messages. Pruning is lossy, and we traverse down the left-most
346
+ // changed time that we know of, because of pruning, it might take
347
+ // multiple passes to sync up a trie.
348
+ for (let i = 0; i < keys.length; i++) {
349
+ const key = keys[i];
350
+ const next1 = node1[key];
351
+ const next2 = node2[key];
352
+ if (!next1 || !next2) break;
353
+ if (next1.hash !== next2.hash) {
354
+ diffKey = key;
355
+ break;
356
+ }
357
+ }
358
+
359
+ if (!diffKey) {
360
+ return Option.some(merkleTreePathToMillis(diffPath));
361
+ }
362
+
363
+ diffPath = [...diffPath, diffKey];
364
+ node1 = node1[diffKey] || initialMerkleTree;
365
+ node2 = node2[diffKey] || initialMerkleTree;
366
+ }
367
+
368
+ return Option.none();
369
+ };
370
+
371
+ export const merkleTreeToString = (m: MerkleTree): MerkleTreeString =>
372
+ JSON.stringify(m) as MerkleTreeString;
373
+
374
+ export const unsafeMerkleTreeFromString = (m: MerkleTreeString): MerkleTree =>
375
+ JSON.parse(m) as MerkleTree;
package/src/Crypto.ts CHANGED
@@ -63,7 +63,7 @@ export const NanoIdLive = Layer.succeed(
63
63
  */
64
64
  export const slip21Derive = (
65
65
  seed: Uint8Array,
66
- path: string[],
66
+ path: ReadonlyArray<string>,
67
67
  ): Effect.Effect<never, never, Uint8Array> =>
68
68
  Effect.sync(() => {
69
69
  let m = hmac(sha512, "Symmetric key seed", seed);
package/src/Db.ts CHANGED
@@ -16,8 +16,13 @@ import {
16
16
  } from "effect";
17
17
  import * as Kysely from "kysely";
18
18
  import { urlAlphabet } from "nanoid";
19
+ import {
20
+ initialMerkleTree,
21
+ makeInitialTimestamp,
22
+ merkleTreeToString,
23
+ timestampToString,
24
+ } from "./Crdt.js";
19
25
  import { Bip39, Mnemonic, NanoId, slip21Derive } from "./Crypto.js";
20
- import { initialMerkleTree, merkleTreeToString } from "./MerkleTree.js";
21
26
  import { Id, SqliteBoolean, SqliteDate } from "./Model.js";
22
27
  import {
23
28
  createMessageTable,
@@ -33,7 +38,6 @@ import {
33
38
  Value,
34
39
  queryObjectToQuery,
35
40
  } from "./Sqlite.js";
36
- import { makeInitialTimestamp, timestampToString } from "./Timestamp.js";
37
41
 
38
42
  export type TableSchema = ReadonlyRecord.ReadonlyRecord<Value> & {
39
43
  readonly id: Id;
package/src/DbWorker.ts CHANGED
@@ -12,6 +12,25 @@ import {
12
12
  pipe,
13
13
  } from "effect";
14
14
  import { Config, ConfigLive } from "./Config.js";
15
+ import {
16
+ MerkleTree,
17
+ Time,
18
+ TimeLive,
19
+ Timestamp,
20
+ TimestampCounterOverflowError,
21
+ TimestampDriftError,
22
+ TimestampError,
23
+ TimestampString,
24
+ TimestampTimeOutOfRangeError,
25
+ diffMerkleTrees,
26
+ insertIntoMerkleTree,
27
+ makeSyncTimestamp,
28
+ merkleTreeToString,
29
+ receiveTimestamp,
30
+ sendTimestamp,
31
+ timestampToString,
32
+ unsafeTimestampFromString,
33
+ } from "./Crdt.js";
15
34
  import { Bip39, Mnemonic, NanoId } from "./Crypto.js";
16
35
  import {
17
36
  Owner,
@@ -25,12 +44,6 @@ import {
25
44
  } from "./Db.js";
26
45
  import { QueryPatches, makePatches } from "./Diff.js";
27
46
  import { EvoluError, UnexpectedError, makeUnexpectedError } from "./Errors.js";
28
- import {
29
- MerkleTree,
30
- diffMerkleTrees,
31
- insertIntoMerkleTree,
32
- merkleTreeToString,
33
- } from "./MerkleTree.js";
34
47
  import { Id, SqliteDate, cast } from "./Model.js";
35
48
  import {
36
49
  insertIntoMessagesIfNew,
@@ -45,25 +58,12 @@ import { Query, Row, Sqlite, Value, queryObjectFromQuery } from "./Sqlite.js";
45
58
  import {
46
59
  Message,
47
60
  NewMessage,
61
+ NewMessageEquivalence,
48
62
  SyncState,
49
63
  SyncWorker,
50
64
  SyncWorkerOutputSyncResponse,
51
65
  SyncWorkerPostMessage,
52
66
  } from "./SyncWorker.js";
53
- import {
54
- Time,
55
- TimeLive,
56
- Timestamp,
57
- TimestampCounterOverflowError,
58
- TimestampDriftError,
59
- TimestampError,
60
- TimestampString,
61
- makeSyncTimestamp,
62
- receiveTimestamp,
63
- sendTimestamp,
64
- timestampToString,
65
- unsafeTimestampFromString,
66
- } from "./Timestamp.js";
67
67
 
68
68
  // TODO: Refactor to Effect.
69
69
  export interface DbWorker {
@@ -247,7 +247,7 @@ const readTimestampAndMerkleTree = Sqlite.pipe(
247
247
  ),
248
248
  );
249
249
 
250
- const mutateItemsToNewMessages = (
250
+ export const mutateItemsToNewMessages = (
251
251
  items: ReadonlyArray.NonEmptyReadonlyArray<MutateItem>,
252
252
  ): ReadonlyArray.NonEmptyReadonlyArray<NewMessage> =>
253
253
  pipe(
@@ -285,6 +285,7 @@ const mutateItemsToNewMessages = (
285
285
  ),
286
286
  ),
287
287
  ReadonlyArray.flattenNonEmpty,
288
+ ReadonlyArray.dedupeNonEmptyWith(NewMessageEquivalence),
288
289
  );
289
290
 
290
291
  const ensureSchemaByMessages = (
@@ -395,7 +396,9 @@ const mutate = ({
395
396
  | RowsCacheRef
396
397
  | DbWorkerOnMessage
397
398
  | SyncWorkerPostMessage,
398
- TimestampDriftError | TimestampCounterOverflowError,
399
+ | TimestampDriftError
400
+ | TimestampCounterOverflowError
401
+ | TimestampTimeOutOfRangeError,
399
402
  void
400
403
  > =>
401
404
  Effect.gen(function* (_) {
package/src/Errors.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Effect } from "effect";
2
- import { TimestampError } from "./Timestamp.js";
2
+ import { TimestampError } from "./Crdt.js";
3
3
 
4
4
  export type EvoluError = UnexpectedError | TimestampError;
5
5
 
package/src/Evolu.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  } from "effect";
13
13
  import { Simplify } from "kysely";
14
14
  import { Config, ConfigLive } from "./Config.js";
15
+ import { Time, TimeLive } from "./Crdt.js";
15
16
  import { Bip39, NanoId } from "./Crypto.js";
16
17
  import {
17
18
  CommonColumns,
@@ -36,7 +37,6 @@ import { AppState, FlushSync } from "./Platform.js";
36
37
  import { Query, Row } from "./Sqlite.js";
37
38
  import { Store, StoreListener, StoreUnsubscribe, makeStore } from "./Store.js";
38
39
  import { SyncState } from "./SyncWorker.js";
39
- import { Time, TimeLive } from "./Timestamp.js";
40
40
 
41
41
  export interface Evolu<S extends Schema> {
42
42
  readonly subscribeError: ErrorStore["subscribe"];
package/src/Protobuf.ts CHANGED
@@ -3,10 +3,9 @@
3
3
  // @generated from protobuf file "Protobuf.proto" (syntax proto3)
4
4
  // tslint:disable
5
5
  import { MessageType } from "@protobuf-ts/runtime";
6
- import { MerkleTreeString } from "./MerkleTree.js";
7
- import { OwnerId } from "./Db.js";
6
+ import { MerkleTreeString, TimestampString } from "./Crdt.js";
8
7
  import { NodeId } from "./Crypto.js";
9
- import { TimestampString } from "./Timestamp.js";
8
+ import { OwnerId } from "./Db.js";
10
9
  import { Id } from "./Model.js";
11
10
  /**
12
11
  * @generated from protobuf message SyncRequest
package/src/SyncWorker.ts CHANGED
@@ -3,6 +3,7 @@ import { BinaryReader, BinaryWriter } from "@protobuf-ts/runtime";
3
3
  import {
4
4
  Context,
5
5
  Effect,
6
+ Equivalence,
6
7
  Function,
7
8
  Layer,
8
9
  Option,
@@ -11,14 +12,17 @@ import {
11
12
  absurd,
12
13
  identity,
13
14
  } from "effect";
14
- import { SecretBox } from "./Crypto.js";
15
- import { Owner } from "./Db.js";
16
- import { UnexpectedError, makeUnexpectedError } from "./Errors.js";
17
15
  import {
18
16
  MerkleTree,
17
+ Millis,
18
+ Timestamp,
19
+ TimestampString,
19
20
  merkleTreeToString,
20
21
  unsafeMerkleTreeFromString,
21
- } from "./MerkleTree.js";
22
+ } from "./Crdt.js";
23
+ import { SecretBox } from "./Crypto.js";
24
+ import { Owner } from "./Db.js";
25
+ import { UnexpectedError, makeUnexpectedError } from "./Errors.js";
22
26
  import { Id } from "./Model.js";
23
27
  import { Fetch, SyncLock } from "./Platform.js";
24
28
  import {
@@ -28,7 +32,6 @@ import {
28
32
  SyncResponse,
29
33
  } from "./Protobuf.js";
30
34
  import { JsonObjectOrArray, Value } from "./Sqlite.js";
31
- import { Millis, Timestamp, TimestampString } from "./Timestamp.js";
32
35
 
33
36
  export interface SyncWorker {
34
37
  readonly postMessage: (input: SyncWorkerInput) => void;
@@ -64,6 +67,15 @@ export interface NewMessage {
64
67
  readonly value: Value;
65
68
  }
66
69
 
70
+ export const NewMessageEquivalence: Equivalence.Equivalence<NewMessage> = (
71
+ a,
72
+ b,
73
+ ) =>
74
+ a.table === b.table &&
75
+ a.row === b.row &&
76
+ a.column === b.column &&
77
+ JSON.stringify(a.value) === JSON.stringify(b.value);
78
+
67
79
  export interface Message extends NewMessage {
68
80
  readonly timestamp: TimestampString;
69
81
  }
package/src/index.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  export { jsonArrayFrom, jsonObjectFrom } from "kysely/helpers/sqlite";
2
2
  export * from "./Config.js";
3
+ export * from "./Crdt.js";
3
4
  export * from "./Crypto.js";
4
5
  export * from "./Db.js";
5
6
  export * from "./DbWorker.js";
6
7
  export * from "./Diff.js";
7
8
  export * from "./Errors.js";
8
9
  export * from "./Evolu.js";
9
- export * from "./MerkleTree.js";
10
10
  export * from "./Model.js";
11
11
  export * from "./Murmurhash.js";
12
12
  export * from "./Platform.js";
@@ -15,4 +15,3 @@ export * from "./Sql.js";
15
15
  export * from "./Sqlite.js";
16
16
  export * from "./Store.js";
17
17
  export * from "./SyncWorker.js";
18
- export * from "./Timestamp.js";
@@ -1,15 +0,0 @@
1
- import { Brand, Option } from "effect";
2
- import { Millis, Timestamp, TimestampHash } from "./Timestamp.js";
3
- export interface MerkleTree {
4
- readonly hash?: TimestampHash;
5
- readonly "0"?: MerkleTree;
6
- readonly "1"?: MerkleTree;
7
- readonly "2"?: MerkleTree;
8
- }
9
- export type MerkleTreeString = string & Brand.Brand<"MerkleTreeString">;
10
- export declare const initialMerkleTree: MerkleTree;
11
- export declare const insertIntoMerkleTree: (timestamp: Timestamp) => (tree: MerkleTree) => MerkleTree;
12
- export declare const diffMerkleTrees: (tree1: MerkleTree, tree2: MerkleTree) => Option.Option<Millis>;
13
- export declare const merkleTreeToString: (m: MerkleTree) => MerkleTreeString;
14
- export declare const unsafeMerkleTreeFromString: (m: MerkleTreeString) => MerkleTree;
15
- //# sourceMappingURL=MerkleTree.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"MerkleTree.d.ts","sourceRoot":"","sources":["../../src/MerkleTree.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EACL,MAAM,EACN,SAAS,EACT,aAAa,EAEd,MAAM,gBAAgB,CAAC;AAKxB,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,GAAG,CAAC,EAAE,UAAU,CAAC;IAC1B,QAAQ,CAAC,GAAG,CAAC,EAAE,UAAU,CAAC;IAC1B,QAAQ,CAAC,GAAG,CAAC,EAAE,UAAU,CAAC;CAC3B;AAED,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;AAExE,eAAO,MAAM,iBAAiB,YAAoC,CAAC;AAwBnE,eAAO,MAAM,oBAAoB,cACnB,SAAS,YACd,UAAU,KAAG,UAKnB,CAAC;AAKJ,eAAO,MAAM,eAAe,UACnB,UAAU,SACV,UAAU,KAChB,aAAa,CAAC,MAAM,CAiBtB,CAAC;AAEF,eAAO,MAAM,kBAAkB,MAAO,UAAU,KAAG,gBACZ,CAAC;AAExC,eAAO,MAAM,0BAA0B,MAAO,gBAAgB,KAAG,UACpC,CAAC"}
@@ -1,49 +0,0 @@
1
- import { Option } from "effect";
2
- import { timestampToHash, } from "./Timestamp.js";
3
- export const initialMerkleTree = Object.create(null);
4
- const timestampToKey = (timestamp) => Math.floor(timestamp.millis / 1000 / 60).toString(3);
5
- const insertKey = (tree, key, hash) => {
6
- if (key.length === 0)
7
- return tree;
8
- const childKey = key[0];
9
- const child = tree[childKey] || {};
10
- return {
11
- ...tree,
12
- [childKey]: {
13
- ...child,
14
- ...insertKey(child, key.slice(1), hash),
15
- // @ts-expect-error undefined is OK
16
- hash: child.hash ^ hash,
17
- },
18
- };
19
- };
20
- export const insertIntoMerkleTree = (timestamp) => (tree) => {
21
- const key = timestampToKey(timestamp);
22
- const hash = timestampToHash(timestamp);
23
- // @ts-expect-error undefined is OK
24
- return insertKey({ ...tree, hash: tree.hash ^ hash }, key, hash);
25
- };
26
- const keyToTimestamp = (key) => (parseInt(key.length > 0 ? key : "0", 3) * 1000 * 60);
27
- export const diffMerkleTrees = (tree1, tree2) => {
28
- if (tree1.hash === tree2.hash)
29
- return Option.none();
30
- for1: for (let node1 = tree1, node2 = tree2, key = "";;) {
31
- for (const k of ["0", "1", "2"]) {
32
- const next1 = node1[k];
33
- const next2 = node2[k];
34
- if (!next1 && !next2)
35
- continue;
36
- if (!next1 || !next2)
37
- break;
38
- if (next1.hash !== next2.hash) {
39
- key += k;
40
- node1 = next1;
41
- node2 = next2;
42
- continue for1;
43
- }
44
- }
45
- return Option.some(keyToTimestamp(key));
46
- }
47
- };
48
- export const merkleTreeToString = (m) => JSON.stringify(m);
49
- export const unsafeMerkleTreeFromString = (m) => JSON.parse(m);