@spooky-sync/core 0.0.1-canary.98 → 1.0.0-beta.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.
Files changed (279) hide show
  1. package/AGENTS.md +58 -21
  2. package/README.md +59 -16
  3. package/dist/index.d.ts +2235 -908
  4. package/dist/index.js +20424 -5052
  5. package/dist/live.d.ts +149 -0
  6. package/dist/live.js +739 -0
  7. package/dist/otel/index.d.ts +1 -1
  8. package/dist/pure.d.ts +401 -0
  9. package/dist/pure.js +24 -0
  10. package/dist/rows-worker.d.ts +1 -0
  11. package/dist/rows-worker.js +2639 -0
  12. package/dist/sqlite-open.js +392 -0
  13. package/dist/sqlite-worker.d.ts +1 -0
  14. package/dist/sqlite-worker.js +439 -0
  15. package/dist/sw.d.ts +207 -0
  16. package/dist/sw.js +393 -0
  17. package/dist/tabs-broker-worker.d.ts +8 -0
  18. package/dist/tabs-broker-worker.js +477 -0
  19. package/dist/types.d.ts +2084 -82
  20. package/dist/worker-edges.js +498 -0
  21. package/dist/worker-impersonation.js +60 -0
  22. package/dist/worker-ref-tables.d.ts +48 -0
  23. package/dist/worker-types.d.ts +112 -0
  24. package/dist/worker-types.js +73 -0
  25. package/package.json +39 -8
  26. package/scripts/check-broker-bundle.mjs +33 -0
  27. package/scripts/check-worker-entries.mjs +186 -0
  28. package/skills/sp00ky-core/SKILL.md +44 -8
  29. package/skills/sp00ky-core/references/config.md +8 -2
  30. package/src/boot/auth-flip.saga.test.ts +174 -0
  31. package/src/boot/auth-flip.saga.ts +77 -0
  32. package/src/boot/boot.saga.test.ts +203 -0
  33. package/src/boot/boot.saga.ts +146 -0
  34. package/src/boot/bucket-switch.saga.test.ts +191 -0
  35. package/src/boot/bucket-switch.saga.ts +151 -0
  36. package/src/boot/preload.saga.test.ts +96 -0
  37. package/src/boot/preload.saga.ts +45 -0
  38. package/src/bucket-blurhash.test.ts +148 -0
  39. package/src/client/bucket-handle.test.ts +195 -0
  40. package/src/client/bucket-handle.ts +372 -0
  41. package/src/client/eager-paint.test.ts +82 -0
  42. package/src/client/router.test.ts +59 -0
  43. package/src/client/router.ts +104 -0
  44. package/src/client/runtime.test.ts +319 -0
  45. package/src/client/runtime.ts +307 -0
  46. package/src/client/services.test.ts +74 -0
  47. package/src/client/services.ts +440 -0
  48. package/src/client/sp00ky-client.test.ts +570 -0
  49. package/src/client/sp00ky-client.ts +875 -0
  50. package/src/index.ts +87 -0
  51. package/src/kernel/constants.test.ts +19 -0
  52. package/src/kernel/constants.ts +94 -0
  53. package/src/kernel/effects.test.ts +40 -0
  54. package/src/kernel/effects.ts +181 -0
  55. package/src/kernel/events.ts +60 -0
  56. package/src/kernel/interpreter.test.ts +133 -0
  57. package/src/kernel/interpreter.ts +151 -0
  58. package/src/kernel/saga.test.ts +89 -0
  59. package/src/kernel/saga.ts +73 -0
  60. package/src/live/index.test.ts +512 -0
  61. package/src/live/index.ts +1059 -0
  62. package/src/modules/app-release/index.test.ts +125 -0
  63. package/src/modules/app-release/index.ts +209 -0
  64. package/src/modules/auth/auth.local-first.test.ts +228 -0
  65. package/src/modules/auth/auth.session-recheck.test.ts +140 -0
  66. package/src/modules/auth/events/index.ts +7 -1
  67. package/src/modules/auth/impersonation-banner.ts +443 -0
  68. package/src/modules/auth/impersonation.integration.test.ts +209 -0
  69. package/src/modules/auth/impersonation.test.ts +377 -0
  70. package/src/modules/auth/impersonation.ts +179 -0
  71. package/src/modules/auth/index.ts +516 -34
  72. package/src/modules/channel/channel.test.ts +752 -0
  73. package/src/modules/channel/hub.test.ts +223 -0
  74. package/src/modules/channel/hub.ts +355 -0
  75. package/src/modules/channel/index.ts +1497 -0
  76. package/src/modules/channel/room.test.ts +340 -0
  77. package/src/modules/channel/room.ts +367 -0
  78. package/src/modules/channel/rooms.fixture.ts +383 -0
  79. package/src/modules/channel/share.test.ts +535 -0
  80. package/src/modules/channel/webrtc.ts +472 -0
  81. package/src/modules/crdt/acceptance.ts +75 -0
  82. package/src/modules/crdt/bytes.ts +50 -0
  83. package/src/modules/crdt/crdt-field.ts +82 -238
  84. package/src/modules/crdt/crdt.test.ts +546 -0
  85. package/src/modules/crdt/hash.ts +103 -0
  86. package/src/modules/crdt/index.ts +740 -271
  87. package/src/modules/crdt/loro-loader.ts +25 -0
  88. package/src/modules/crdt/mirror.ts +37 -0
  89. package/src/modules/devtools/flags.ts +349 -0
  90. package/src/modules/devtools/index.ts +661 -99
  91. package/src/modules/devtools/mutations.test.ts +92 -0
  92. package/src/modules/devtools/mutations.ts +160 -0
  93. package/src/modules/devtools/notify-throttle.test.ts +166 -0
  94. package/src/modules/devtools/state-shape.test.ts +263 -0
  95. package/src/modules/devtools/storage-info.test.ts +79 -0
  96. package/src/modules/devtools/storage-info.ts +169 -0
  97. package/src/modules/devtools/versions.ts +29 -0
  98. package/src/modules/feature-flag/index.test.ts +179 -1
  99. package/src/modules/feature-flag/index.ts +117 -10
  100. package/src/modules/ref-tables.test.ts +28 -1
  101. package/src/modules/ref-tables.ts +23 -1
  102. package/src/modules/web-push/index.test.ts +824 -0
  103. package/src/modules/web-push/index.ts +1027 -0
  104. package/src/mutation/ingest-outage.integration.test.ts +400 -0
  105. package/src/mutation/jobs.test.ts +25 -0
  106. package/src/mutation/jobs.ts +41 -0
  107. package/src/mutation/mutation-id.test.ts +37 -0
  108. package/src/mutation/mutation-id.ts +35 -0
  109. package/src/mutation/pending-writes.integration.test.ts +175 -0
  110. package/src/mutation/push.saga.test.ts +361 -0
  111. package/src/mutation/push.saga.ts +245 -0
  112. package/src/mutation/rows.test.ts +278 -0
  113. package/src/mutation/rows.ts +515 -0
  114. package/src/mutation/tray.saga.test.ts +63 -0
  115. package/src/mutation/tray.saga.ts +48 -0
  116. package/src/mutation/write.saga.test.ts +436 -0
  117. package/src/mutation/write.saga.ts +384 -0
  118. package/src/pure.ts +66 -0
  119. package/src/push/types.ts +174 -0
  120. package/src/query/anon-query-isolation.integration.test.ts +531 -0
  121. package/src/query/env.test.ts +23 -0
  122. package/src/query/env.ts +65 -0
  123. package/src/query/fetch.saga.test.ts +199 -0
  124. package/src/query/fetch.saga.ts +120 -0
  125. package/src/query/hash.test.ts +14 -0
  126. package/src/query/hash.ts +18 -0
  127. package/src/query/id-set-plan.test.ts +132 -0
  128. package/src/query/lifecycle.saga.test.ts +274 -0
  129. package/src/query/lifecycle.saga.ts +186 -0
  130. package/src/query/list-ref-live.integration.test.ts +203 -0
  131. package/src/query/materialize.saga.test.ts +216 -0
  132. package/src/query/materialize.saga.ts +83 -0
  133. package/src/query/materialize.test.ts +58 -0
  134. package/src/query/materialize.ts +133 -0
  135. package/src/query/membership.saga.test.ts +514 -0
  136. package/src/query/membership.saga.ts +339 -0
  137. package/src/query/membership.test.ts +151 -0
  138. package/src/query/membership.ts +234 -0
  139. package/src/query/register.saga.test.ts +430 -0
  140. package/src/query/register.saga.ts +330 -0
  141. package/src/query/render-set.test.ts +47 -0
  142. package/src/query/render-set.ts +71 -0
  143. package/src/query/session-guard.integration.test.ts +304 -0
  144. package/src/query/sql.test.ts +118 -0
  145. package/src/query/sql.ts +174 -0
  146. package/src/{modules/data → query}/window-query.test.ts +22 -4
  147. package/src/{modules/data → query}/window-query.ts +86 -8
  148. package/src/services/blobs/blob-cache.test.ts +359 -0
  149. package/src/services/blobs/blob-cache.ts +603 -0
  150. package/src/services/blobs/blob-manifest.ts +227 -0
  151. package/src/services/blobs/blob-store.test.ts +77 -0
  152. package/src/services/blobs/blob-store.ts +359 -0
  153. package/src/services/blobs/blob.fixture.ts +90 -0
  154. package/src/services/blobs/index.ts +70 -0
  155. package/src/services/database/cache-engine.ts +223 -0
  156. package/src/services/database/connection-supervisor.test.ts +318 -0
  157. package/src/services/database/connection-supervisor.ts +422 -0
  158. package/src/services/database/database.query-timeout.test.ts +140 -0
  159. package/src/services/database/database.responses.test.ts +43 -0
  160. package/src/services/database/database.ts +151 -56
  161. package/src/services/database/engine-factory.ts +40 -0
  162. package/src/services/database/errors.ts +34 -0
  163. package/src/services/database/index.ts +8 -0
  164. package/src/services/database/landed-body-clear.integration.test.ts +236 -0
  165. package/src/services/database/local-migrator.integration.test.ts +110 -0
  166. package/src/services/database/local-migrator.ts +54 -9
  167. package/src/services/database/local.test.ts +117 -0
  168. package/src/services/database/local.ts +364 -74
  169. package/src/services/database/plan-render.test.ts +159 -0
  170. package/src/services/database/plan-render.ts +108 -0
  171. package/src/services/database/relation-resolver.test.ts +484 -0
  172. package/src/services/database/relation-resolver.ts +0 -0
  173. package/src/services/database/remote.ts +283 -4
  174. package/src/services/database/rows-cache-engine.test.ts +1014 -0
  175. package/src/services/database/rows-cache-engine.ts +921 -0
  176. package/src/services/database/rows-exec.integration.test.ts +589 -0
  177. package/src/services/database/rows-exec.ts +1027 -0
  178. package/src/services/database/rows-prewarm.ts +225 -0
  179. package/src/services/database/rows-store.test.ts +635 -0
  180. package/src/services/database/rows-store.ts +1208 -0
  181. package/src/services/database/rows-transport.fixture.ts +151 -0
  182. package/src/services/database/rows-worker.ts +588 -0
  183. package/src/services/database/sqlite-cache-engine.test.ts +649 -0
  184. package/src/services/database/sqlite-cache-engine.timeout.test.ts +61 -0
  185. package/src/services/database/sqlite-cache-engine.ts +1422 -0
  186. package/src/services/database/sqlite-column-reset.integration.test.ts +100 -0
  187. package/src/services/database/sqlite-column-reset.ts +91 -0
  188. package/src/services/database/sqlite-devtools-queries.integration.test.ts +143 -0
  189. package/src/services/database/sqlite-devtools-queries.test.ts +154 -0
  190. package/src/services/database/sqlite-lock-verify.test.ts +33 -0
  191. package/src/services/database/sqlite-lock-verify.ts +45 -0
  192. package/src/services/database/sqlite-open.test.ts +150 -0
  193. package/src/services/database/sqlite-open.ts +164 -0
  194. package/src/services/database/sqlite-plan-sql.test.ts +164 -0
  195. package/src/services/database/sqlite-plan-sql.ts +196 -0
  196. package/src/services/database/sqlite-projection.test.ts +121 -0
  197. package/src/services/database/sqlite-select.integration.test.ts +185 -0
  198. package/src/services/database/sqlite-select.test.ts +261 -0
  199. package/src/services/database/sqlite-select.ts +131 -0
  200. package/src/services/database/sqlite-transport.fixture.ts +30 -0
  201. package/src/services/database/sqlite-transport.ts +231 -0
  202. package/src/services/database/sqlite-worker.ts +437 -0
  203. package/src/services/database/surql-translate.ts +417 -0
  204. package/src/services/database/surreal-cache-engine.ts +163 -0
  205. package/src/services/logger/index.test.ts +132 -0
  206. package/src/services/logger/index.ts +187 -6
  207. package/src/services/persistence/surrealdb.ts +2 -2
  208. package/src/services/stream-processor/index.ts +621 -93
  209. package/src/services/stream-processor/stream-processor.batch.test.ts +57 -7
  210. package/src/services/stream-processor/stream-processor.prime.test.ts +234 -0
  211. package/src/services/stream-processor/stream-processor.reset.test.ts +226 -0
  212. package/src/services/stream-processor/wasm-types.ts +41 -1
  213. package/src/services/tabs/broker-client.ts +284 -0
  214. package/src/services/tabs/broker.test.ts +381 -0
  215. package/src/services/tabs/coordinator.test.ts +386 -0
  216. package/src/services/tabs/coordinator.ts +646 -0
  217. package/src/services/tabs/fake-ports.fixture.ts +112 -0
  218. package/src/services/tabs/leader-locks.ts +75 -0
  219. package/src/services/tabs/protocol.ts +262 -0
  220. package/src/services/tabs/support.ts +38 -0
  221. package/src/services/tabs/tabs-broker-worker.ts +652 -0
  222. package/src/sp00ky.ts +5 -648
  223. package/src/state/client-state.ts +231 -0
  224. package/src/state/lifecycle.test.ts +184 -0
  225. package/src/state/lifecycle.ts +127 -0
  226. package/src/state/reducers.test.ts +337 -0
  227. package/src/state/reducers.ts +571 -0
  228. package/src/state/selectors.test.ts +203 -0
  229. package/src/state/selectors.ts +264 -0
  230. package/src/sw/index.test.ts +582 -0
  231. package/src/sw/index.ts +607 -0
  232. package/src/sw/store.ts +96 -0
  233. package/src/sync/connection.saga.test.ts +97 -0
  234. package/src/sync/connection.saga.ts +89 -0
  235. package/src/sync/live.saga.test.ts +229 -0
  236. package/src/sync/live.saga.ts +116 -0
  237. package/src/sync/policy.health.test.ts +56 -0
  238. package/src/{modules/sync/utils.test.ts → sync/policy.test.ts} +96 -11
  239. package/src/{modules/sync/utils.ts → sync/policy.ts} +186 -7
  240. package/src/sync/poll.saga.test.ts +51 -0
  241. package/src/sync/poll.saga.ts +36 -0
  242. package/src/sync/tabs.saga.test.ts +78 -0
  243. package/src/sync/tabs.saga.ts +96 -0
  244. package/src/testing/adapters.ts +137 -0
  245. package/src/testing/build.ts +63 -0
  246. package/src/testing/fake-services.ts +63 -0
  247. package/src/testing/run-pure.test.ts +92 -0
  248. package/src/testing/run-pure.ts +128 -0
  249. package/src/testing/services.ts +17 -0
  250. package/src/types.ts +601 -25
  251. package/src/utils/blurhash.ts +90 -0
  252. package/src/utils/edges.ts +57 -0
  253. package/src/utils/error-classification.test.ts +116 -0
  254. package/src/utils/error-classification.ts +74 -0
  255. package/src/utils/index.ts +58 -3
  256. package/src/utils/parser.test.ts +67 -102
  257. package/src/utils/parser.ts +62 -1
  258. package/src/utils/semver.test.ts +32 -0
  259. package/src/utils/semver.ts +30 -0
  260. package/src/utils/sha256.ts +15 -0
  261. package/src/utils/surql.ts +17 -15
  262. package/src/utils/utils.test.ts +3 -2
  263. package/tsdown.config.ts +105 -4
  264. package/vitest.config.ts +52 -0
  265. package/src/modules/cache/index.ts +0 -253
  266. package/src/modules/cache/types.ts +0 -19
  267. package/src/modules/crdt/crdt-hydration.test.ts +0 -206
  268. package/src/modules/data/data.status.test.ts +0 -108
  269. package/src/modules/data/data.test.ts +0 -58
  270. package/src/modules/data/index.ts +0 -1491
  271. package/src/modules/sync/engine.ts +0 -227
  272. package/src/modules/sync/events/index.ts +0 -84
  273. package/src/modules/sync/index.ts +0 -3
  274. package/src/modules/sync/queue/index.ts +0 -2
  275. package/src/modules/sync/queue/queue-down.ts +0 -90
  276. package/src/modules/sync/queue/queue-up.ts +0 -224
  277. package/src/modules/sync/scheduler.ts +0 -121
  278. package/src/modules/sync/sync.ts +0 -1244
  279. package/src/sp00ky.auth-order.test.ts +0 -65
@@ -0,0 +1,535 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { RecordId } from 'surrealdb';
3
+ import type { QueryPlan, SchemaStructure } from '@spooky-sync/query-builder';
4
+ import {
5
+ ChannelManager,
6
+ decodeInterest,
7
+ encodeInterest,
8
+ mergeInterest,
9
+ peerKey,
10
+ queryInterest,
11
+ showsRow,
12
+ type ChannelTransport,
13
+ type ChannelTransportFactory,
14
+ type ChannelsConfig,
15
+ type PeerRef,
16
+ type Row,
17
+ type TransportHooks,
18
+ } from './index';
19
+ import { hubTransport } from './hub';
20
+ import { fakeBrowser, memoryRoom, settle } from './rooms.fixture';
21
+
22
+ const schema = {
23
+ tables: [
24
+ {
25
+ name: 'note',
26
+ columns: {
27
+ id: { type: 'string', optional: false, recordId: true },
28
+ folder: { type: 'string', optional: false },
29
+ title: { type: 'string', optional: false },
30
+ draft: { type: 'boolean', optional: true },
31
+ author: { type: 'string', optional: true, recordId: true },
32
+ },
33
+ primaryKey: ['id'],
34
+ },
35
+ {
36
+ name: 'tag',
37
+ columns: { id: { type: 'string', optional: false, recordId: true }, note: { type: 'string', optional: false, recordId: true }, label: { type: 'string', optional: false } },
38
+ primaryKey: ['id'],
39
+ },
40
+ {
41
+ name: 'secret',
42
+ columns: { id: { type: 'string', optional: false, recordId: true }, text: { type: 'string', optional: false } },
43
+ primaryKey: ['id'],
44
+ },
45
+ {
46
+ name: 'call',
47
+ columns: { id: { type: 'string', optional: false, recordId: true }, view_id: { type: 'string', optional: true } },
48
+ channel: true,
49
+ primaryKey: ['id'],
50
+ },
51
+ ],
52
+ relationships: [],
53
+ backends: {},
54
+ } as unknown as SchemaStructure;
55
+
56
+ const columnsOf = (table: string) => schema.tables.find((t) => t.name === table)?.columns;
57
+ const eq = (field: string, value: unknown) => ({ field, op: '=', value });
58
+ const inFolder = (folder: string): QueryPlan => ({ table: 'note', where: [eq('folder', folder)] });
59
+
60
+ describe('interest', () => {
61
+ it('reads what a query can show from its plan', () => {
62
+ expect(queryInterest(columnsOf, inFolder('a'))).toEqual([{ table: 'note', where: [eq('folder', 'a')] }]);
63
+ expect(queryInterest(columnsOf, { table: 'note' })).toEqual([{ table: 'note', where: [] }]);
64
+ // A parameter is filled in from the query's own.
65
+ expect(queryInterest(columnsOf, { table: 'note', where: [{ field: 'folder', op: '=', value: undefined, paramRef: 'f' }] }, { f: 'x' })).toEqual([
66
+ { table: 'note', where: [eq('folder', 'x')] },
67
+ ]);
68
+ // `_or` groups and swapped operands keep their shape.
69
+ expect(queryInterest(columnsOf, { table: 'note', where: [{ or: [eq('folder', 'a'), { field: 'folder', op: '∈', value: ['b'], swap: true }] }] })).toEqual([
70
+ { table: 'note', where: [{ or: [eq('folder', 'a'), { field: 'folder', op: '∈', value: ['b'], swap: true }] }] },
71
+ ]);
72
+ // What the row alone cannot decide is the whole table.
73
+ for (const where of [
74
+ [{ field: 'title', op: '@@', value: 'x' }],
75
+ [eq('author.name', 'x')],
76
+ [{ field: 'folder', op: '=', value: undefined, paramRef: 'missing' }],
77
+ ]) {
78
+ expect(queryInterest(columnsOf, { table: 'note', where })).toEqual([{ table: 'note', where: null }]);
79
+ }
80
+ expect(queryInterest(columnsOf, { table: 'note', ids: ['note:1'], where: [eq('folder', 'a')] })).toEqual([{ table: 'note', where: null }]);
81
+ // Related tables: every row, however deep.
82
+ const related = queryInterest(columnsOf, {
83
+ table: 'note',
84
+ where: [eq('folder', 'a')],
85
+ relations: [{ alias: 'tags', table: 'tag', cardinality: 'many', foreignKeyField: 'note', relations: [{ alias: 'x', table: 'secret', cardinality: 'one', foreignKeyField: 'y' }] }],
86
+ });
87
+ expect(related.map((q) => [q.table, q.where === null])).toEqual([
88
+ ['note', false],
89
+ ['tag', true],
90
+ ['secret', true],
91
+ ]);
92
+ });
93
+
94
+ it('merges the open queries into one claim per shared table', () => {
95
+ const shared = (t: string) => t === 'note' || t === 'tag';
96
+ expect(mergeInterest([], shared)).toEqual({});
97
+ expect(mergeInterest([[{ table: 'secret', where: null }]], shared)).toEqual({});
98
+ expect(
99
+ mergeInterest(
100
+ [
101
+ [{ table: 'note', where: [eq('folder', 'a')] }],
102
+ [{ table: 'note', where: [eq('folder', 'b')] }, { table: 'tag', where: null }],
103
+ ],
104
+ shared
105
+ )
106
+ ).toEqual({ note: [[eq('folder', 'a')], [eq('folder', 'b')]], tag: true });
107
+ // The same filter twice is one, and the order of the queries does not show.
108
+ const twice = [[{ table: 'note', where: [eq('folder', 'b')] }], [{ table: 'note', where: [eq('folder', 'a')] }], [{ table: 'note', where: [eq('folder', 'b')] }]];
109
+ expect(mergeInterest(twice, shared)).toEqual({ note: [[eq('folder', 'a')], [eq('folder', 'b')]] });
110
+ // An unfiltered query, or one nobody described, asks for everything.
111
+ expect(mergeInterest([[{ table: 'note', where: [eq('folder', 'a')] }], [{ table: 'note', where: [] }], [{ table: 'note', where: [eq('folder', 'c')] }]], shared)).toEqual({ note: true });
112
+ expect(mergeInterest([[{ table: 'note', where: [eq('folder', 'a')] }], null], shared)).toBe('all');
113
+ const many = Array.from({ length: 30 }, (_, i) => [{ table: 'note', where: [eq('folder', `f${i}`)] }]);
114
+ expect(mergeInterest(many, shared)).toEqual({ note: true });
115
+ });
116
+
117
+ it('survives the wire, record ids and dates included', () => {
118
+ const interest = { note: [[eq('author', new RecordId('user', 'a')), { or: [eq('folder', 'a'), { field: 'at', op: '>', value: new Date(5), swap: true }] }]], tag: true as const };
119
+ const wire = JSON.parse(JSON.stringify(encodeInterest(interest)));
120
+ const back = decodeInterest(wire);
121
+ expect(back).not.toBeNull();
122
+ expect(showsRow(back!, 'note', [{ author: 'user:a', folder: 'a' }])).toBe(true);
123
+ expect(showsRow(back!, 'note', [{ author: 'user:b', folder: 'a' }])).toBe(false);
124
+ expect(showsRow(back!, 'tag', [{}])).toBe(true);
125
+ expect(showsRow(back!, 'secret', [{}])).toBe(false);
126
+ expect(decodeInterest(JSON.parse(JSON.stringify(encodeInterest('all'))))).toBe('all');
127
+ expect(showsRow('all', 'anything', [])).toBe(true);
128
+ // Before or after a write: either is enough.
129
+ expect(showsRow(back!, 'note', [{ author: 'user:b' }, { author: 'user:a', folder: 'a' }])).toBe(true);
130
+ });
131
+
132
+ it('reads a filter it cannot evaluate as the whole table, and refuses what is not an interest', () => {
133
+ for (const raw of [null, 'x', { t: 'op' }, { t: 'interest' }, { t: 'interest', v: [] }, { t: 'interest', v: null }]) expect(decodeInterest(raw)).toBeNull();
134
+ const odd = decodeInterest({
135
+ t: 'interest',
136
+ v: {
137
+ a: [[{ field: 'x', op: 'constructor', value: 1 }]],
138
+ b: [[{ field: 1, op: '=', value: 1 }]],
139
+ c: ['nope'],
140
+ d: [[{ or: [] }]],
141
+ e: Array.from({ length: 40 }, () => [eq('x', 1)]),
142
+ f: [[null]],
143
+ g: 'yes',
144
+ h: [[eq('x', 1)]],
145
+ },
146
+ });
147
+ expect(odd).toEqual({ a: true, b: true, c: true, d: true, e: true, f: true, h: [[eq('x', 1)]] });
148
+ });
149
+ });
150
+
151
+ // ---- the manager, sharing with the user's own devices -----------------------------------
152
+
153
+ /** Tabs connect as soon as both want each other's user, own user included. */
154
+ function memoryNet() {
155
+ const nodes = new Map<string, { self: PeerRef; hooks: TransportHooks; wanted: Set<string>; links: Set<string> }>();
156
+ const sent: Array<{ from: string; to: string; message: Record<string, unknown> }> = [];
157
+ const reconcile = () => {
158
+ for (const a of nodes.values()) {
159
+ for (const b of nodes.values()) {
160
+ if (a === b) continue;
161
+ const kb = peerKey(b.self);
162
+ const mutual = a.wanted.has(b.self.user) && b.wanted.has(a.self.user);
163
+ if (mutual && !a.links.has(kb)) {
164
+ a.links.add(kb);
165
+ a.hooks.onPeer(b.self, true);
166
+ } else if (!mutual && a.links.has(kb)) {
167
+ a.links.delete(kb);
168
+ a.hooks.onPeer(b.self, false);
169
+ }
170
+ }
171
+ }
172
+ };
173
+ const factory: ChannelTransportFactory = (hooks): ChannelTransport => {
174
+ const self = hooks.self()!;
175
+ const node = { self, hooks, wanted: new Set<string>(), links: new Set<string>() };
176
+ nodes.set(peerKey(self), node);
177
+ return {
178
+ supported: true,
179
+ want(users) {
180
+ node.wanted = new Set(users);
181
+ reconcile();
182
+ },
183
+ send(to, message) {
184
+ if (!node.links.has(peerKey(to))) return;
185
+ const copy = JSON.parse(JSON.stringify(message)) as Record<string, unknown>;
186
+ sent.push({ from: peerKey(self), to: peerKey(to), message: copy });
187
+ nodes.get(peerKey(to))?.hooks.onMessage(self, copy);
188
+ },
189
+ close() {
190
+ node.wanted = new Set();
191
+ reconcile();
192
+ nodes.delete(peerKey(self));
193
+ },
194
+ };
195
+ };
196
+ return { factory, sent, ops: () => sent.filter((s) => s.message.t === 'op') };
197
+ }
198
+
199
+ const share: ChannelsConfig = { share: { tables: { note: true, tag: true, call: true } } };
200
+
201
+ /** One device: a manager signed in as `user`, its local rows, and a way to subscribe. */
202
+ function device(user: string, transport: ChannelTransportFactory, config: ChannelsConfig = share, held: Row[] = []) {
203
+ const store = new Map<string, Row>(held.map((r) => [String(r.id), r]));
204
+ const calls: string[] = [];
205
+ const m = new ChannelManager(schema, {
206
+ transport,
207
+ config,
208
+ rows: {
209
+ create: async (_t, id, row) => {
210
+ calls.push(`create ${id}`);
211
+ if (store.has(id)) return false;
212
+ store.set(id, { id, ...row });
213
+ return true;
214
+ },
215
+ delete: async (_t, id) => {
216
+ calls.push(`delete ${id}`);
217
+ return store.delete(id);
218
+ },
219
+ read: async (id) => store.get(id) ?? null,
220
+ },
221
+ });
222
+ m.setUser(user);
223
+ /** Subscribe like a mounted query: its rows are what the store holds of its table. */
224
+ const show = (plan?: QueryPlan) => {
225
+ const seen: Row[][] = [];
226
+ const tap = m.tap((rows) => seen.push(rows), plan ? m.interestOf(plan) : null);
227
+ tap.feed([...store.values()].filter((r) => !plan || String(r.id).startsWith(`${plan.table}:`)));
228
+ return { seen, last: () => seen[seen.length - 1], stop: tap.stop };
229
+ };
230
+ return { m, store, calls, show };
231
+ }
232
+
233
+ const note = (id: string, extra: Row = {}): Row => ({ id: `note:${id}`, folder: 'a', title: 't', ...extra });
234
+ const flush = async () => {
235
+ for (let i = 0; i < 30; i++) await Promise.resolve();
236
+ };
237
+
238
+ describe('ChannelManager: sharing with the own devices', () => {
239
+ it('sends an update of a shared table to the other device, which shows it at once', async () => {
240
+ const net = memoryNet();
241
+ const phone = device('user:a', net.factory, share, [note('1')]);
242
+ const laptop = device('user:a', net.factory, share, [note('1')]);
243
+ const view = laptop.show(inFolder('a'));
244
+ await flush();
245
+ expect(phone.m.sharing).toBe(true);
246
+ expect(phone.m.enabled).toBe(true);
247
+ expect(phone.m.ownState()).toEqual({ status: 'connected', peers: ['user:a'] });
248
+ phone.m.local('note', 'note:1', { title: 'new' }, null);
249
+ await flush();
250
+ expect(view.last()[0].title).toBe('new');
251
+ // Never in the store: the synced row confirms it, or it expires.
252
+ expect(laptop.store.get('note:1')?.title).toBe('t');
253
+ });
254
+
255
+ it('carries creates and deletes too', async () => {
256
+ const net = memoryNet();
257
+ const phone = device('user:a', net.factory, share, [note('1')]);
258
+ const laptop = device('user:a', net.factory, share, [note('1')]);
259
+ laptop.show();
260
+ await flush();
261
+ phone.m.localCreate('note', 'note:2', { folder: 'a', title: 'two' });
262
+ await phone.m.localDelete('note', 'note:1');
263
+ await flush();
264
+ expect(laptop.calls).toEqual(['create note:2', 'delete note:1']);
265
+ expect(laptop.store.get('note:2')).toMatchObject({ folder: 'a', title: 'two' });
266
+ });
267
+
268
+ it('shares nothing of a table that was not named, or was turned off', async () => {
269
+ const net = memoryNet();
270
+ const config: ChannelsConfig = { share: { tables: { note: true, secret: false } } };
271
+ const phone = device('user:a', net.factory, config, [{ id: 'secret:1', text: 'x' }, { id: 'tag:1', note: 'note:1', label: 'l' }]);
272
+ const laptop = device('user:a', net.factory, config, [{ id: 'secret:1', text: 'x' }]);
273
+ laptop.show();
274
+ await flush();
275
+ phone.m.local('secret', 'secret:1', { text: 'y' }, null);
276
+ phone.m.local('tag', 'tag:1', { label: 'm' }, null);
277
+ await flush();
278
+ expect(net.ops()).toEqual([]);
279
+ // And a device takes none either, whoever sends it.
280
+ const peer = [...net.sent].find((s) => s.message.t === 'interest')!;
281
+ laptop.m.receive({ user: 'user:a', peer: peer.from.split('#')[1] }, { t: 'op', table: 'secret', id: 'secret:1', patch: { text: 'z' }, hlc: [1, 0, 'x'] });
282
+ await flush();
283
+ expect(laptop.calls).toEqual([]);
284
+ });
285
+
286
+ it('warns about a table the schema does not have and shares the rest', () => {
287
+ const warn = vi.fn();
288
+ const m = new ChannelManager(schema, { config: { share: { tables: { nope: true, note: true } } }, logger: { warn, debug: () => {} } });
289
+ expect(warn.mock.calls[0][1]).toMatch(/'nope'/);
290
+ expect(m.sharing).toBe(true);
291
+ expect(new ChannelManager(schema, { config: { share: { tables: { note: false } } } }).sharing).toBe(false);
292
+ expect(new ChannelManager(schema).ownState()).toEqual({ status: 'idle', peers: [] });
293
+ });
294
+
295
+ it('applies a rule given as a function on the device that writes and on the one that receives', async () => {
296
+ const net = memoryNet();
297
+ const rule = (row: Row) => row.draft !== true;
298
+ const config: ChannelsConfig = { share: { tables: { note: rule } } };
299
+ const phone = device('user:a', net.factory, config, [note('1', { draft: true }), note('2'), note('5', { draft: true })]);
300
+ const laptop = device('user:a', net.factory, config, [note('1', { draft: true }), note('2'), note('5', { draft: true })]);
301
+ const view = laptop.show();
302
+ await flush();
303
+ phone.m.local('note', 'note:1', { title: 'still a draft' }, null);
304
+ phone.m.local('note', 'note:2', { title: 'public' }, null);
305
+ await flush();
306
+ expect(net.ops().map((s) => s.message.id)).toEqual(['note:2']);
307
+ expect(view.last().map((r) => r.title)).toEqual(['t', 'public', 't']);
308
+ // Publishing a draft: the row after the write passes, so it goes out.
309
+ phone.m.local('note', 'note:1', { draft: false }, null);
310
+ await flush();
311
+ expect(net.ops().map((s) => s.message.id)).toEqual(['note:2', 'note:1']);
312
+ // A device whose own rule says no drops what another build of the app sent.
313
+ laptop.m.receive({ user: 'user:a', peer: 'other' }, { t: 'op', table: 'note', id: 'note:5', patch: { title: 'forced' }, hlc: [9e15, 0, 'x'] });
314
+ await flush();
315
+ expect(view.last()[2].title).toBe('t');
316
+ // A rule that throws shares nothing.
317
+ const bad = device('user:a', net.factory, { share: { tables: { note: () => { throw new Error('boom'); } } } }, [note('3')]);
318
+ bad.m.local('note', 'note:3', { title: 'x' }, null);
319
+ await flush();
320
+ expect(net.ops()).toHaveLength(2);
321
+ });
322
+
323
+ it('never shares with another user, and takes nothing shared from one', async () => {
324
+ const net = memoryNet();
325
+ const ann = device('user:a', net.factory, share, [note('1')]);
326
+ const bob = device('user:b', net.factory, share, [note('1')]);
327
+ const view = bob.show();
328
+ await flush();
329
+ ann.m.local('note', 'note:1', { title: 'mine' }, null);
330
+ await flush();
331
+ expect(net.sent).toEqual([]);
332
+ bob.m.receive({ user: 'user:a', peer: 'x' }, { t: 'op', table: 'note', id: 'note:1', patch: { title: 'mine' }, hlc: [1, 0, 'x'] });
333
+ bob.m.receive({ user: 'user:a', peer: 'x' }, { t: 'interest', all: true });
334
+ await flush();
335
+ expect(view.last()[0].title).toBe('t');
336
+ });
337
+
338
+ it('follows the signed-in user', async () => {
339
+ const net = memoryNet();
340
+ const phone = device('user:a', net.factory, share, [note('1')]);
341
+ const laptop = device('user:a', net.factory, share, [note('1')]);
342
+ const view = laptop.show();
343
+ await flush();
344
+ laptop.m.setUser('user:b');
345
+ phone.m.local('note', 'note:1', { title: 'for a' }, null);
346
+ await flush();
347
+ expect(net.ops()).toEqual([]);
348
+ expect(laptop.m.ownState().status).toBe('connecting');
349
+ laptop.m.setUser(null);
350
+ expect(laptop.m.ownState().status).toBe('idle');
351
+ laptop.m.setUser('user:a');
352
+ await flush();
353
+ phone.m.local('note', 'note:1', { title: 'for a' }, null);
354
+ await flush();
355
+ expect(view.last()[0].title).toBe('for a');
356
+ });
357
+
358
+ it('reports how the own devices are doing to a subscriber', async () => {
359
+ const net = memoryNet();
360
+ const phone = device('user:a', net.factory);
361
+ const states: string[] = [];
362
+ const stop = phone.m.subscribeOwn((s) => states.push(s.status));
363
+ const laptop = device('user:a', net.factory);
364
+ await flush();
365
+ laptop.m.close();
366
+ await flush();
367
+ expect(states).toEqual(['connecting', 'connected', 'connecting']);
368
+ stop();
369
+ expect(new ChannelManager(schema).subscribeOwn((s) => states.push(s.status))()).toBeUndefined();
370
+ expect(states.at(-1)).toBe('idle');
371
+ });
372
+
373
+ it('also reaches the own devices when a write goes through a channel to another user', async () => {
374
+ const net = memoryNet();
375
+ const callScope = { table: 'call', where: [] };
376
+ const phone = device('user:a', net.factory, share, [{ id: 'call:1', view_id: '' }]);
377
+ const laptop = device('user:a', net.factory, share, [{ id: 'call:1', view_id: '' }]);
378
+ const bob = device('user:b', net.factory, {}, [{ id: 'call:1', view_id: '' }]);
379
+ const toBob = phone.m.open([callScope], ['user:b']);
380
+ bob.m.open([callScope], ['user:a']);
381
+ const mine = laptop.show();
382
+ const theirs = bob.show();
383
+ await flush();
384
+ phone.m.local('call', 'call:1', { view_id: 'v' }, null, toBob);
385
+ await flush();
386
+ expect(mine.last()[0].view_id).toBe('v');
387
+ expect(theirs.last()[0].view_id).toBe('v');
388
+ });
389
+ });
390
+
391
+ describe('ChannelManager: sending only what the other device shows', () => {
392
+ it('skips a device that shows nothing of the table, and one whose filter the row is outside of', async () => {
393
+ const net = memoryNet();
394
+ const phone = device('user:a', net.factory, share, [note('1'), note('2', { folder: 'b' }), { id: 'tag:1', note: 'note:1', label: 'l' }]);
395
+ const laptop = device('user:a', net.factory, share, [note('1'), note('2', { folder: 'b' })]);
396
+ await flush();
397
+ // Nothing is mounted on the laptop: nothing is sent to it.
398
+ phone.m.local('note', 'note:1', { title: 'x' }, null);
399
+ await flush();
400
+ expect(net.ops()).toEqual([]);
401
+
402
+ const view = laptop.show(inFolder('a'));
403
+ await flush();
404
+ phone.m.local('note', 'note:1', { title: 'in a' }, null);
405
+ phone.m.local('note', 'note:2', { title: 'in b' }, null);
406
+ phone.m.local('tag', 'tag:1', { label: 'm' }, null);
407
+ await flush();
408
+ expect(net.ops().map((s) => s.message.id)).toEqual(['note:1']);
409
+ expect(view.last()[0].title).toBe('in a');
410
+
411
+ // A row moving into the folder it shows, or out of it, is sent.
412
+ phone.m.local('note', 'note:2', { folder: 'a' }, null);
413
+ phone.m.local('note', 'note:1', { folder: 'z' }, null);
414
+ await flush();
415
+ expect(net.ops().map((s) => s.message.id)).toEqual(['note:1', 'note:2', 'note:1']);
416
+ // So are a create inside it and a delete of a row inside it; outside, neither.
417
+ phone.m.localCreate('note', 'note:3', { folder: 'a', title: 'n' });
418
+ phone.m.localCreate('note', 'note:4', { folder: 'q', title: 'n' });
419
+ await flush();
420
+ expect(net.ops().map((s) => s.message.id)).toEqual(['note:1', 'note:2', 'note:1', 'note:3']);
421
+
422
+ // The query goes away: so does the claim.
423
+ view.stop();
424
+ await flush();
425
+ phone.m.localCreate('note', 'note:5', { folder: 'a', title: 'n' });
426
+ await flush();
427
+ expect(net.ops()).toHaveLength(4);
428
+ });
429
+
430
+ it('sends everything of a table read through .related(), and everything to a subscription nobody described', async () => {
431
+ const net = memoryNet();
432
+ const phone = device('user:a', net.factory, share, [{ id: 'tag:1', note: 'note:1', label: 'l' }, note('9', { folder: 'zzz' })]);
433
+ const laptop = device('user:a', net.factory, share, [{ id: 'tag:1', note: 'note:1', label: 'l' }, note('9', { folder: 'zzz' })]);
434
+ const withTags = laptop.show({ ...inFolder('a'), relations: [{ alias: 'tags', table: 'tag', cardinality: 'many', foreignKeyField: 'note' }] });
435
+ await flush();
436
+ phone.m.local('tag', 'tag:1', { label: 'm' }, null);
437
+ phone.m.local('note', 'note:9', { title: 'far' }, null);
438
+ await flush();
439
+ expect(net.ops().map((s) => s.message.id)).toEqual(['tag:1']);
440
+ withTags.stop();
441
+ laptop.show();
442
+ await flush();
443
+ phone.m.local('note', 'note:9', { title: 'far' }, null);
444
+ await flush();
445
+ expect(net.ops().map((s) => s.message.id)).toEqual(['tag:1', 'note:9']);
446
+ });
447
+
448
+ it('announces once per change, and tells a device that joins later', async () => {
449
+ const net = memoryNet();
450
+ const phone = device('user:a', net.factory, share, [note('1')]);
451
+ const laptop = device('user:a', net.factory, share, [note('1')]);
452
+ await flush();
453
+ const interests = () => net.sent.filter((s) => s.message.t === 'interest');
454
+ // Each told the other on meeting.
455
+ expect(interests()).toHaveLength(2);
456
+ const a = laptop.show(inFolder('a'));
457
+ const b = laptop.show(inFolder('a'));
458
+ laptop.show(inFolder('b'));
459
+ await flush();
460
+ expect(interests()).toHaveLength(3);
461
+ expect(interests().at(-1)!.message.v).toEqual({ note: [[eq('folder', 'a')], [eq('folder', 'b')]] });
462
+ // One of two queries on the folder goes: the claim is the same, and not said again.
463
+ a.stop();
464
+ a.stop();
465
+ await flush();
466
+ expect(interests()).toHaveLength(3);
467
+ b.stop();
468
+ await flush();
469
+ expect(interests()).toHaveLength(4);
470
+ expect(interests().at(-1)!.message.v).toEqual({ note: [[eq('folder', 'b')]] });
471
+ laptop.show(inFolder('a'));
472
+ await flush();
473
+ expect(interests()).toHaveLength(5);
474
+ const tablet = device('user:a', net.factory, share, [note('1')]);
475
+ const view = tablet.show(inFolder('a'));
476
+ await flush();
477
+ phone.m.local('note', 'note:1', { title: 'all three' }, null);
478
+ await flush();
479
+ expect(view.last()[0].title).toBe('all three');
480
+ expect(net.ops().map((s) => s.to).sort()).toEqual([...new Set(net.ops().map((s) => s.to))].sort());
481
+ expect(net.ops()).toHaveLength(2);
482
+ });
483
+
484
+ it('forgets what a device showed once it is gone', async () => {
485
+ const net = memoryNet();
486
+ const phone = device('user:a', net.factory, share, [note('1')]);
487
+ const laptop = device('user:a', net.factory, share, [note('1')]);
488
+ laptop.show(inFolder('nothing'));
489
+ await flush();
490
+ phone.m.local('note', 'note:1', { title: 'x' }, null);
491
+ await flush();
492
+ expect(net.ops()).toEqual([]);
493
+ laptop.m.close();
494
+ const again = device('user:a', net.factory, share, [note('1')]);
495
+ again.show();
496
+ await flush();
497
+ phone.m.local('note', 'note:1', { title: 'y' }, null);
498
+ await flush();
499
+ expect(net.ops()).toHaveLength(1);
500
+ // Garbage in place of an interest changes nothing.
501
+ phone.m.receive({ user: 'user:a', peer: 'x' }, { t: 'interest', v: 7 });
502
+ });
503
+ });
504
+
505
+ describe('sharing, end to end: two browsers with two tabs each', () => {
506
+ it('shows a write of one tab in the tabs of the other browser, over one link per browser', async () => {
507
+ const room = memoryRoom();
508
+ const left = fakeBrowser();
509
+ const right = fakeBrowser();
510
+ const viaHub = (b: ReturnType<typeof fakeBrowser>): ChannelTransportFactory => (hooks) =>
511
+ hubTransport(hooks, { scope: (user) => `ns/db/${user}`, link: room.link, locks: b.locks, bus: b.bus, supported: true });
512
+ const a1 = device('user:a', viaHub(left), share, [note('1')]);
513
+ const a2 = device('user:a', viaHub(left), share, [note('1')]);
514
+ const b1 = device('user:a', viaHub(right), share, [note('1')]);
515
+ const b2 = device('user:a', viaHub(right), share, [note('1')]);
516
+ const views = { a2: a2.show(inFolder('a')), b1: b1.show(inFolder('a')), b2: b2.show(inFolder('other')) };
517
+ await settle();
518
+ expect(room.members.size).toBe(2);
519
+ const frames = room.frames.length;
520
+ a1.m.local('note', 'note:1', { title: 'from a1' }, null);
521
+ await settle();
522
+ // The other browser's tab that shows the folder has it; the one that does
523
+ // not was never sent it; the sibling tab is not a peer.
524
+ expect(views.b1.last()[0].title).toBe('from a1');
525
+ expect(views.b2.last()[0].title).toBe('t');
526
+ expect(views.a2.last()[0].title).toBe('t');
527
+ expect(room.frames.length - frames).toBe(1);
528
+ expect(room.frames.at(-1)!.data).toMatchObject({ h: 'm', from: expect.any(String), to: [expect.any(String)] });
529
+ // And back, from the tab that does not hold the link.
530
+ b2.m.local('note', 'note:1', { title: 'from b2' }, null);
531
+ await settle();
532
+ expect(views.a2.last()[0].title).toBe('from b2');
533
+ expect(views.b1.last()[0].title).toBe('from a1');
534
+ });
535
+ });