@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,195 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { BucketHandle, bucketContentToBlob } from './bucket-handle';
3
+
4
+ vi.mock('../utils/blurhash', async (importOriginal) => {
5
+ const actual = await importOriginal<typeof import('../utils/blurhash')>();
6
+ return { ...actual, encodeImageToBlurhash: vi.fn(async () => 'LEHV6nWB2yk8pyo0adR*.7kCMdnj') };
7
+ });
8
+
9
+ function fakeRemote(answers: Record<string, unknown> = {}) {
10
+ const calls: Array<[string, unknown]> = [];
11
+ const remote = {
12
+ query: async (sql: string, vars?: unknown) => {
13
+ calls.push([sql, vars]);
14
+ for (const [needle, answer] of Object.entries(answers)) if (sql.includes(needle)) return [answer];
15
+ return [undefined];
16
+ },
17
+ } as any;
18
+ return { remote, calls };
19
+ }
20
+
21
+ function fakeBlobs() {
22
+ const log: string[] = [];
23
+ return {
24
+ log,
25
+ blobs: {
26
+ invalidate: async (k: { path: string }) => void log.push(`invalidate:${k.path}`),
27
+ read: async (k: { path: string }) => (k.path.endsWith('.bh') ? new Blob(['LEHV6nWB2yk8pyo0adR*.7kCMdnj']) : new Blob(['x'])),
28
+ acquireUrl: async (k: { path: string }) => ({ url: `blob:${k.path}`, release: () => undefined }),
29
+ setPinned: (k: { path: string }, pinned: boolean) => void log.push(`pin:${k.path}:${pinned}`),
30
+ prefetch: async (keys: Array<{ path: string }>) => void log.push(`prefetch:${keys.map((k) => k.path).join('+')}`),
31
+ } as any,
32
+ };
33
+ }
34
+
35
+ describe('bucketContentToBlob', () => {
36
+ it('coerces strings, buffers and views; passes blobs through; rejects the rest', async () => {
37
+ expect(bucketContentToBlob(null)).toBeNull();
38
+ expect(bucketContentToBlob(42)).toBeNull();
39
+ const b = new Blob(['a']);
40
+ expect(bucketContentToBlob(b)).toBe(b);
41
+ expect(await bucketContentToBlob('hi')!.text()).toBe('hi');
42
+ expect((await bucketContentToBlob(new ArrayBuffer(3))!.arrayBuffer()).byteLength).toBe(3);
43
+ expect((await bucketContentToBlob(new Uint8Array([1, 2]))!.arrayBuffer()).byteLength).toBe(2);
44
+ });
45
+ });
46
+
47
+ describe('BucketHandle', () => {
48
+ it('put: uploads, invalidates, writes the blurhash sidecar for images (best-effort), honours the setting', async () => {
49
+ const { remote, calls } = fakeRemote();
50
+ const { blobs, log } = fakeBlobs();
51
+ const warn = vi.fn();
52
+ const h = new BucketHandle('files', remote, blobs, { logger: { warn } });
53
+ const res = await h.put('a/pic.png', new Uint8Array([1]));
54
+ expect(res.blurhash).toBe('LEHV6nWB2yk8pyo0adR*.7kCMdnj');
55
+ expect(calls.map(([s]) => s)).toEqual(['RETURN f"files:/a/pic.png".put($content);', 'RETURN f"files:/a/pic.png.bh".put($content);']);
56
+ expect(log).toEqual(['invalidate:a/pic.png', 'invalidate:a/pic.png.bh']);
57
+ const off = new BucketHandle('files', remote, blobs, { blurhash: false });
58
+ expect((await off.put('b.png', 'x')).blurhash).toBeNull();
59
+ const perCall = new BucketHandle('files', remote, blobs, { blurhash: { componentX: 2 } });
60
+ expect((await perCall.put('c.txt', 'x', { blurhash: true })).blurhash).toBeNull();
61
+ expect((await perCall.put('c.png', 'x', { blurhash: { componentY: 3 } })).blurhash).toBeTruthy();
62
+ const failing = { query: async (sql: string) => { if (sql.includes('.bh')) throw new Error('sidecar'); return [undefined]; } } as any;
63
+ const sidecarFail = new BucketHandle('files', failing, blobs, { logger: { warn } });
64
+ expect((await sidecarFail.put('d.png', 'x')).blurhash).toBeNull();
65
+ expect(warn).toHaveBeenCalled();
66
+ const noBlobs = new BucketHandle('files', remote, null);
67
+ expect((await noBlobs.put('e.png', 'x')).blurhash).toBeTruthy();
68
+ });
69
+
70
+ it('blurhash: reads the sidecar through the cache, negative-caches misses, warns on invalid or failing reads', async () => {
71
+ const { remote } = fakeRemote();
72
+ const warn = vi.fn();
73
+ const { blobs } = fakeBlobs();
74
+ const h = new BucketHandle('bucketA', remote, blobs, { logger: { warn } });
75
+ expect(await h.blurhash('img.png')).toBe('LEHV6nWB2yk8pyo0adR*.7kCMdnj');
76
+ const missing = new BucketHandle('bucketB', remote, { ...blobs, read: async () => null } as any, { logger: { warn } });
77
+ expect(await missing.blurhash('none.png')).toBeNull();
78
+ expect(await missing.blurhash('none.png')).toBeNull();
79
+ const invalid = new BucketHandle('bucketC', remote, { ...blobs, read: async () => new Blob(['not-a-hash']) } as any, { logger: { warn } });
80
+ expect(await invalid.blurhash('bad.png')).toBeNull();
81
+ const throwing = new BucketHandle('bucketD', remote, { ...blobs, read: async () => { throw new Error('io'); } } as any, { logger: { warn } });
82
+ expect(await throwing.blurhash('err.png')).toBeNull();
83
+ expect(warn).toHaveBeenCalledTimes(2);
84
+ await new BucketHandle('bucketB', remote, blobs).put('none.png', 'x');
85
+ expect(await new BucketHandle('bucketB', remote, blobs).blurhash('none.png')).toBeTruthy();
86
+ });
87
+
88
+ it('get / read / url / pin / evict / prefetch / delete / exists / head / copy / rename / list', async () => {
89
+ const { remote, calls } = fakeRemote({ '.get()': 'content', '.exists()': true, '.head()': { size: 1 }, '.list()': ['a'] });
90
+ const { blobs, log } = fakeBlobs();
91
+ const h = new BucketHandle('files', remote, blobs);
92
+ expect(await h.get('p')).toBe('content');
93
+ expect(await (await h.read('p'))!.text()).toBe('x');
94
+ expect(await new BucketHandle('files', remote, null).read('p')).toBeInstanceOf(Blob);
95
+ expect(await h.url('p')).toEqual({ url: 'blob:p', release: expect.any(Function) });
96
+ expect(await new BucketHandle('files', remote, null).url('p')).toBeNull();
97
+ h.pin('p');
98
+ h.unpin('p');
99
+ await h.evict('p');
100
+ await h.prefetch(['a', 'b']);
101
+ await h.delete('doc.txt');
102
+ await h.delete('img.png');
103
+ const flaky = { query: async (sql: string) => { if (sql.includes('.bh".delete')) throw new Error('nope'); return [undefined]; } } as any;
104
+ await new BucketHandle('files', flaky, blobs).delete('img2.png');
105
+ expect(await h.exists('p')).toBe(true);
106
+ expect(await h.head('p')).toEqual({ size: 1 });
107
+ await h.copy('a', 'b');
108
+ await h.rename('a', 'b');
109
+ expect(await h.list()).toEqual(['a']);
110
+ expect(await h.list('pre/')).toEqual(['a']);
111
+ expect(log).toContain('pin:p:true');
112
+ expect(log).toContain('pin:p:false');
113
+ expect(log).toContain('prefetch:a+b');
114
+ expect(calls.some(([s]) => s === 'RETURN f"files:/img.png.bh".delete();')).toBe(true);
115
+ expect(calls.some(([s]) => s === 'RETURN f"files:/pre/".list();')).toBe(true);
116
+ });
117
+ });
118
+
119
+ describe('r2 buckets (files with the SSP)', () => {
120
+ function fakeSsp(files: Record<string, string> = {}) {
121
+ const requests: Array<{ method: string; url: string; auth: string | null; body: unknown }> = [];
122
+ const fetchMock = vi.fn(async (url: string, init: RequestInit) => {
123
+ const headers = (init.headers ?? {}) as Record<string, string>;
124
+ requests.push({ method: init.method ?? 'GET', url, auth: headers.Authorization ?? null, body: init.body });
125
+ const key = decodeURIComponent(new URL(url).pathname.replace(/^\/bucket\/[^/]+\//, ''));
126
+ const json = (status: number, value: unknown) => new Response(JSON.stringify(value), { status });
127
+ if (headers.Authorization !== 'Bearer tok') return json(401, { error: 'invalid or expired token' });
128
+ switch (init.method) {
129
+ case 'PUT':
130
+ files[key] = typeof init.body === 'string' ? init.body : 'bytes';
131
+ return json(200, { ok: true });
132
+ case 'GET':
133
+ return key in files ? new Response(files[key], { status: 200 }) : json(404, { error: 'no such file' });
134
+ case 'DELETE':
135
+ delete files[key];
136
+ return json(200, { ok: true });
137
+ default: {
138
+ const op = JSON.parse(String(init.body));
139
+ if (op.op === 'exists') return json(200, key in files);
140
+ if (op.op === 'head') return json(200, key in files ? { key: `/${key}`, size: files[key].length } : null);
141
+ if (!(key in files)) return json(404, { error: 'no such file' });
142
+ files[op.target] = files[key];
143
+ if (op.op === 'rename') delete files[key];
144
+ return json(200, { ok: true });
145
+ }
146
+ }
147
+ });
148
+ vi.stubGlobal('fetch', fetchMock);
149
+ return { requests, files };
150
+ }
151
+
152
+ const remote = (token: string | null = 'tok') => ({ getAuthToken: () => token, query: vi.fn() }) as any;
153
+ const r2 = (r = remote()) =>
154
+ new BucketHandle('pics', r, null, { backend: 'r2', files: { endpoint: 'https://app.db.example/' }, blurhash: false });
155
+
156
+ it('reads and writes over HTTP with the session token, never the database socket', async () => {
157
+ const { requests, files } = fakeSsp();
158
+ const db = remote();
159
+ const h = r2(db);
160
+ await h.put('u1/a b.png', 'PNG');
161
+ expect(files['u1/a b.png']).toBe('PNG');
162
+ expect(requests[0]).toMatchObject({ method: 'PUT', url: 'https://app.db.example/bucket/pics/u1/a%20b.png', auth: 'Bearer tok' });
163
+ expect(await ((await h.get('u1/a b.png')) as Blob).text()).toBe('PNG');
164
+ expect(await h.get('missing.png')).toBeNull();
165
+ expect(await h.exists('u1/a b.png')).toBe(true);
166
+ expect(await h.head('u1/a b.png')).toEqual({ key: '/u1/a b.png', size: 3 });
167
+ await h.copy('u1/a b.png', 'u1/c.png');
168
+ await h.rename('u1/c.png', 'u1/d.png');
169
+ expect(Object.keys(files).sort()).toEqual(['u1/a b.png', 'u1/d.png']);
170
+ await expect(h.copy('nope.png', 'x.png')).rejects.toThrow(/no file/);
171
+ await h.delete('u1/a b.png');
172
+ expect(await h.exists('u1/a b.png')).toBe(false);
173
+ await expect(h.list()).rejects.toThrow(/listing/);
174
+ expect(db.query).not.toHaveBeenCalled();
175
+ vi.unstubAllGlobals();
176
+ });
177
+
178
+ it('surfaces refusals and a missing endpoint as errors', async () => {
179
+ fakeSsp({ 'a.png': 'x' });
180
+ await expect(r2(remote(null)).get('a.png')).rejects.toThrow(/401.*invalid or expired token/);
181
+ const noEndpoint = new BucketHandle('pics', remote(), null, { backend: 'r2', files: {} });
182
+ await expect(noEndpoint.get('a.png')).rejects.toThrow(/files\.endpoint/);
183
+ vi.unstubAllGlobals();
184
+ });
185
+
186
+ it('a bucket without backend r2 keeps using the database', async () => {
187
+ const db = { getAuthToken: () => 'tok', query: vi.fn(async () => ['content']) } as any;
188
+ const fetchMock = vi.fn();
189
+ vi.stubGlobal('fetch', fetchMock);
190
+ const h = new BucketHandle('pics', db, null, { files: { endpoint: 'https://app.db.example' } });
191
+ expect(await h.get('a.png')).toBe('content');
192
+ expect(fetchMock).not.toHaveBeenCalled();
193
+ vi.unstubAllGlobals();
194
+ });
195
+ });
@@ -0,0 +1,372 @@
1
+ import type { RemoteDatabaseService } from '../services/database/remote';
2
+ import type { BlobCache, BlobReadOptions, BlobUrlLease } from '../services/blobs/index';
3
+ import {
4
+ blurhashSidecarPath,
5
+ encodeImageToBlurhash,
6
+ isImagePath,
7
+ isBlurhashValid,
8
+ type BlurhashSetting,
9
+ type BlurhashEncodeOptions,
10
+ } from '../utils/blurhash';
11
+
12
+ /** Coerce whatever the `.get()` RPC hands back into a Blob. */
13
+ export function bucketContentToBlob(content: unknown): Blob | null {
14
+ if (content == null) return null;
15
+ if (content instanceof Blob) return content;
16
+ if (typeof content === 'string') return new Blob([content]);
17
+ if (content instanceof ArrayBuffer) return new Blob([content]);
18
+ // Uint8Array and friends. The cast sidesteps `ArrayBufferLike` vs
19
+ // `ArrayBuffer` (SharedArrayBuffer) in lib.dom's BlobPart.
20
+ if (ArrayBuffer.isView(content)) return new Blob([content as unknown as BlobPart]);
21
+ return null;
22
+ }
23
+
24
+ export interface BucketPutOptions {
25
+ /** Override the client-level {@link Sp00kyConfig.blurhash} setting for this put. */
26
+ blurhash?: BlurhashSetting;
27
+ }
28
+
29
+ export interface BucketPutResult {
30
+ /** The computed blurhash when the content was a hashable image; else null. */
31
+ blurhash: string | null;
32
+ }
33
+
34
+ interface BucketHandleSettings {
35
+ blurhash?: BlurhashSetting;
36
+ logger?: { warn: (obj: unknown, msg?: string) => void };
37
+ /** The bucket's backend as generated (`'r2'`: files live with the SSP). */
38
+ backend?: string;
39
+ /** {@link Sp00kyConfig.files}: where `r2` bucket files are read and written. */
40
+ files?: { endpoint?: string };
41
+ }
42
+
43
+ /** A handle's settings from the client config and the bucket's generated schema. */
44
+ export function bucketSettings(
45
+ config: { blurhash?: BlurhashSetting; files?: { endpoint?: string }; schema: { buckets?: readonly { name: string; backend?: string }[] } },
46
+ name: string,
47
+ logger: { warn: (obj: unknown, msg?: string) => void }
48
+ ): BucketHandleSettings {
49
+ const backend = config.schema.buckets?.find((b) => b.name === name)?.backend;
50
+ return { blurhash: config.blurhash, logger, backend, files: config.files };
51
+ }
52
+
53
+ /** Where a bucket's bytes go: SurrealDB itself, or the SSP for `r2` buckets. */
54
+ interface BucketIo {
55
+ put(path: string, content: string | Uint8Array | Blob): Promise<void>;
56
+ /** The file, or null when it does not exist. */
57
+ get(path: string): Promise<unknown>;
58
+ delete(path: string): Promise<void>;
59
+ exists(path: string): Promise<boolean>;
60
+ head(path: string): Promise<Record<string, unknown>>;
61
+ copy(sourcePath: string, targetPath: string): Promise<void>;
62
+ rename(sourcePath: string, targetPath: string): Promise<void>;
63
+ list(prefix: string): Promise<string[]>;
64
+ }
65
+
66
+ /** `f"bucket:/path"` statements over the database connection. */
67
+ function surrealIo(bucket: string, remote: RemoteDatabaseService): BucketIo {
68
+ const file = (path: string) => `f"${bucket}:/${path}"`;
69
+ return {
70
+ async put(path, content) {
71
+ await remote.query(`RETURN ${file(path)}.put($content);`, { content });
72
+ },
73
+ async get(path) {
74
+ const [result] = await remote.query<[unknown]>(`RETURN ${file(path)}.get();`);
75
+ return result;
76
+ },
77
+ async delete(path) {
78
+ await remote.query(`RETURN ${file(path)}.delete();`);
79
+ },
80
+ async exists(path) {
81
+ const [result] = await remote.query<[boolean]>(`RETURN ${file(path)}.exists();`);
82
+ return result;
83
+ },
84
+ async head(path) {
85
+ const [result] = await remote.query<[Record<string, unknown>]>(`RETURN ${file(path)}.head();`);
86
+ return result;
87
+ },
88
+ async copy(sourcePath, targetPath) {
89
+ await remote.query(`RETURN ${file(sourcePath)}.copy($target);`, { target: targetPath });
90
+ },
91
+ async rename(sourcePath, targetPath) {
92
+ await remote.query(`RETURN ${file(sourcePath)}.rename($target);`, { target: targetPath });
93
+ },
94
+ async list(prefix) {
95
+ const [result] = await remote.query<[string[]]>(`RETURN ${file(prefix)}.list();`);
96
+ return result;
97
+ },
98
+ };
99
+ }
100
+
101
+ /**
102
+ * `BACKEND "r2"` buckets: the SSP keeps the files (R2 on Cloudflare, a
103
+ * directory under `spky dev`) and serves them at `/bucket/<name>/<key>`,
104
+ * after asking SurrealDB, as the signed-in user, whether the bucket's
105
+ * PERMISSIONS clause allows it. The request carries the session's token.
106
+ */
107
+ function sspIo(bucket: string, remote: RemoteDatabaseService, endpoint: string | undefined): BucketIo {
108
+ const base = () => {
109
+ if (!endpoint) {
110
+ throw new Error(
111
+ `Bucket '${bucket}' is stored with the SSP (BACKEND "r2"): set \`files.endpoint\` in the client config to the SSP's URL.`
112
+ );
113
+ }
114
+ return endpoint.replace(/\/+$/, '');
115
+ };
116
+ const url = (path: string) =>
117
+ `${base()}/bucket/${encodeURIComponent(bucket)}/${path
118
+ .split('/')
119
+ .filter(Boolean)
120
+ .map(encodeURIComponent)
121
+ .join('/')}`;
122
+ const send = async (method: string, path: string, body?: BodyInit, contentType?: string): Promise<Response> => {
123
+ const headers: Record<string, string> = {};
124
+ const token = remote.getAuthToken();
125
+ if (token) headers.Authorization = `Bearer ${token}`;
126
+ if (contentType) headers['Content-Type'] = contentType;
127
+ const response = await fetch(url(path), { method, headers, body, credentials: 'omit' });
128
+ if (!response.ok && response.status !== 404) {
129
+ let message = response.statusText;
130
+ try {
131
+ message = ((await response.json()) as { error?: string }).error ?? message;
132
+ } catch {
133
+ // Not JSON: keep the status text.
134
+ }
135
+ throw new Error(`Bucket '${bucket}' ${method} ${path} failed (${response.status}): ${message}`);
136
+ }
137
+ return response;
138
+ };
139
+ const op = async <T>(path: string, body: Record<string, unknown>): Promise<T | null> => {
140
+ const response = await send('POST', path, JSON.stringify(body), 'application/json');
141
+ if (response.status === 404) return null;
142
+ return (await response.json()) as T;
143
+ };
144
+ const missing = (path: string) => new Error(`Bucket '${bucket}': no file at ${path}`);
145
+ return {
146
+ async put(path, content) {
147
+ const type = content instanceof Blob ? content.type : undefined;
148
+ await send('PUT', path, content as BodyInit, type || 'application/octet-stream');
149
+ },
150
+ async get(path) {
151
+ const response = await send('GET', path);
152
+ return response.status === 404 ? null : await response.blob();
153
+ },
154
+ async delete(path) {
155
+ await send('DELETE', path);
156
+ },
157
+ async exists(path) {
158
+ return (await op<boolean>(path, { op: 'exists' })) ?? false;
159
+ },
160
+ async head(path) {
161
+ return (await op<Record<string, unknown>>(path, { op: 'head' })) as Record<string, unknown>;
162
+ },
163
+ async copy(sourcePath, targetPath) {
164
+ if ((await op(sourcePath, { op: 'copy', target: targetPath })) === null) throw missing(sourcePath);
165
+ },
166
+ async rename(sourcePath, targetPath) {
167
+ if ((await op(sourcePath, { op: 'rename', target: targetPath })) === null) throw missing(sourcePath);
168
+ },
169
+ async list() {
170
+ // SurrealDB refuses `list` to record users; the SSP does too.
171
+ throw new Error(`Bucket '${bucket}': listing is not available (BACKEND "r2")`);
172
+ },
173
+ };
174
+ }
175
+
176
+ /**
177
+ * Paths known to have no blurhash sidecar, per tab. The blob cache has no
178
+ * negative caching, so without this every mount of a hashless image would pay
179
+ * one serialized remote read. Cleared when a put writes a sidecar or a delete
180
+ * removes the image. Keyed `${bucket}:${path}` (the image path, not the sidecar).
181
+ */
182
+ const missingBlurhash = new Set<string>();
183
+
184
+ export class BucketHandle {
185
+ private io: BucketIo;
186
+
187
+ constructor(
188
+ private bucketName: string,
189
+ remote: RemoteDatabaseService,
190
+ /** Absent on the raw handle the cache itself reads through. */
191
+ private blobs?: BlobCache | null,
192
+ private settings?: BucketHandleSettings,
193
+ /**
194
+ * Resolves once the client is open; nothing to wait for when it already
195
+ * is. Every call below awaits it, so a file asked for by a component that
196
+ * rendered before the client was ready (a provider's `eager` mode) is
197
+ * fetched then, where it used to fail for want of a connection.
198
+ */
199
+ private opened?: () => Promise<void> | undefined
200
+ ) {
201
+ this.io =
202
+ settings?.backend === 'r2'
203
+ ? sspIo(bucketName, remote, settings.files?.endpoint)
204
+ : surrealIo(bucketName, remote);
205
+ }
206
+
207
+ /** Effective blurhash setting: per-call option > client config > default ON. */
208
+ private resolveBlurhash(option?: BlurhashSetting): BlurhashEncodeOptions | null {
209
+ const setting = option ?? this.settings?.blurhash ?? true;
210
+ if (setting === false) return null;
211
+ return setting === true ? {} : setting;
212
+ }
213
+
214
+ async put(
215
+ path: string,
216
+ content: string | Uint8Array | Blob,
217
+ options?: BucketPutOptions
218
+ ): Promise<BucketPutResult> {
219
+ await this.opened?.();
220
+ // Start hashing while the upload is in flight; both browser-side costs
221
+ // overlap and the sidecar put only queues once the main put resolved.
222
+ const encodeOptions = this.resolveBlurhash(options?.blurhash);
223
+ const hashPromise =
224
+ encodeOptions && isImagePath(path)
225
+ ? encodeImageToBlurhash(content, encodeOptions)
226
+ : Promise.resolve(null);
227
+
228
+ await this.io.put(path, content);
229
+ // A path can be overwritten, so anything cached under it is now wrong.
230
+ await this.blobs?.invalidate({ bucket: this.bucketName, path });
231
+
232
+ // The sidecar is best-effort: a hash or sidecar failure must never fail
233
+ // the image put that triggered it.
234
+ let hash: string | null = null;
235
+ try {
236
+ hash = await hashPromise;
237
+ if (hash) {
238
+ const sidecar = blurhashSidecarPath(path);
239
+ await this.io.put(sidecar, hash);
240
+ await this.blobs?.invalidate({ bucket: this.bucketName, path: sidecar });
241
+ missingBlurhash.delete(`${this.bucketName}:${path}`);
242
+ }
243
+ } catch (error) {
244
+ hash = null;
245
+ this.settings?.logger?.warn({ error, path }, 'blurhash sidecar put failed');
246
+ }
247
+ return { blurhash: hash };
248
+ }
249
+
250
+ /**
251
+ * The blurhash stored alongside an uploaded image (see
252
+ * {@link blurhashSidecarPath}), or null when there is none. Reads through the
253
+ * blob cache, so a warm client answers from OPFS without a network hop, and
254
+ * misses are remembered per tab so a hashless image costs at most one
255
+ * serialized remote read per session.
256
+ */
257
+ async blurhash(path: string): Promise<string | null> {
258
+ await this.opened?.();
259
+ const cacheKey = `${this.bucketName}:${path}`;
260
+ if (missingBlurhash.has(cacheKey)) return null;
261
+ try {
262
+ const blob = await this.read(blurhashSidecarPath(path), { persist: true });
263
+ if (!blob) {
264
+ missingBlurhash.add(cacheKey);
265
+ return null;
266
+ }
267
+ const hash = (await blob.text()).trim();
268
+ if (!isBlurhashValid(hash).result) {
269
+ this.settings?.logger?.warn({ path }, 'blurhash sidecar holds an invalid hash');
270
+ missingBlurhash.add(cacheKey);
271
+ return null;
272
+ }
273
+ return hash;
274
+ } catch (error) {
275
+ // Transient failure: do NOT negative-cache, the next mount may succeed.
276
+ this.settings?.logger?.warn({ error, path }, 'blurhash sidecar read failed');
277
+ return null;
278
+ }
279
+ }
280
+
281
+ async get(path: string): Promise<unknown> {
282
+ await this.opened?.();
283
+ return this.io.get(path);
284
+ }
285
+
286
+ /**
287
+ * Read through the local blob cache: OPFS first, the bucket second. Unlike
288
+ * {@link get} this survives a reload and works offline. Returns null when the
289
+ * file exists in neither place.
290
+ */
291
+ async read(path: string, options?: BlobReadOptions): Promise<Blob | null> {
292
+ await this.opened?.();
293
+ if (!this.blobs) return bucketContentToBlob(await this.get(path));
294
+ return this.blobs.read({ bucket: this.bucketName, path }, options);
295
+ }
296
+
297
+ /**
298
+ * A refcounted object URL for `path`, suitable for `<img src>`. The caller
299
+ * MUST call `release()` when the URL goes off screen. Returns null when the
300
+ * file does not exist, or when object URLs are unavailable (non-browser).
301
+ */
302
+ async url(path: string, options?: BlobReadOptions): Promise<BlobUrlLease | null> {
303
+ await this.opened?.();
304
+ if (!this.blobs) return null;
305
+ return this.blobs.acquireUrl({ bucket: this.bucketName, path }, options);
306
+ }
307
+
308
+ /** Exempt `path` from pressure eviction. Pinned bytes never expire. */
309
+ pin(path: string): void {
310
+ this.blobs?.setPinned({ bucket: this.bucketName, path }, true);
311
+ }
312
+
313
+ unpin(path: string): void {
314
+ this.blobs?.setPinned({ bucket: this.bucketName, path }, false);
315
+ }
316
+
317
+ /** Drop `path` from the local cache without touching the remote file. */
318
+ async evict(path: string): Promise<void> {
319
+ await this.opened?.();
320
+ await this.blobs?.invalidate({ bucket: this.bucketName, path });
321
+ }
322
+
323
+ /** Warm the cache for offline use. Already-cached paths are skipped. */
324
+ async prefetch(paths: string[]): Promise<void> {
325
+ await this.opened?.();
326
+ await this.blobs?.prefetch(paths.map((path) => ({ bucket: this.bucketName, path })));
327
+ }
328
+
329
+ async delete(path: string): Promise<void> {
330
+ await this.opened?.();
331
+ await this.io.delete(path);
332
+ await this.blobs?.invalidate({ bucket: this.bucketName, path });
333
+ // Symmetry with put: an image's blurhash sidecar dies with it. Best-effort,
334
+ // the sidecar may simply not exist.
335
+ if (isImagePath(path)) {
336
+ const sidecar = blurhashSidecarPath(path);
337
+ try {
338
+ await this.io.delete(sidecar);
339
+ await this.blobs?.invalidate({ bucket: this.bucketName, path: sidecar });
340
+ } catch {
341
+ // Nothing to clean up.
342
+ }
343
+ missingBlurhash.delete(`${this.bucketName}:${path}`);
344
+ }
345
+ }
346
+
347
+ async exists(path: string): Promise<boolean> {
348
+ await this.opened?.();
349
+ return this.io.exists(path);
350
+ }
351
+
352
+ async head(path: string): Promise<Record<string, unknown>> {
353
+ await this.opened?.();
354
+ return this.io.head(path);
355
+ }
356
+
357
+ async copy(sourcePath: string, targetPath: string): Promise<void> {
358
+ await this.opened?.();
359
+ await this.io.copy(sourcePath, targetPath);
360
+ }
361
+
362
+ async rename(sourcePath: string, targetPath: string): Promise<void> {
363
+ await this.opened?.();
364
+ await this.io.rename(sourcePath, targetPath);
365
+ }
366
+
367
+ async list(prefix?: string): Promise<string[]> {
368
+ await this.opened?.();
369
+ return this.io.list(prefix ?? '');
370
+ }
371
+ }
372
+
@@ -0,0 +1,82 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
+ import { Sp00kyClient } from './sp00ky-client';
3
+ import { RowsCacheEngine } from '../services/database/rows-cache-engine';
4
+ import { inProcessRows, type RowsDisks } from '../services/database/rows-transport.fixture';
5
+ import { paintKeyOf } from '../query/materialize';
6
+
7
+ /**
8
+ * The whole way from one page load to the next, with the real client and the
9
+ * real row store engine: a query renders, the engine keeps what it read, and
10
+ * the next page's client, built and not yet initialized, hands those rows to
11
+ * a component synchronously.
12
+ */
13
+ describe('painting a query before init (row store)', () => {
14
+ const g = globalThis as Record<string, unknown>;
15
+ let stored: Map<string, string>;
16
+ const schema = { tables: [{ name: 'thing', columns: { n: {} } }] } as any;
17
+ const config = {
18
+ database: { namespace: 'n', database: 'd', store: 'indexeddb' },
19
+ localEngine: 'rows',
20
+ schema,
21
+ schemaSurql: '',
22
+ logLevel: 'silent',
23
+ } as any;
24
+ const logger = { info() {}, warn() {}, error() {}, debug() {}, trace() {}, child: () => logger } as any;
25
+
26
+ beforeEach(() => {
27
+ stored = new Map();
28
+ g.localStorage = {
29
+ getItem: (k: string) => stored.get(k) ?? null,
30
+ setItem: (k: string, v: string) => void stored.set(k, v),
31
+ removeItem: (k: string) => void stored.delete(k),
32
+ key: (i: number) => [...stored.keys()][i] ?? null,
33
+ get length() {
34
+ return stored.size;
35
+ },
36
+ };
37
+ });
38
+
39
+ afterEach(() => {
40
+ delete g.localStorage;
41
+ });
42
+
43
+ /** The first page load: the engine as the client drives it for one query's membership render. */
44
+ async function lastSession(bucket: string, surql: string): Promise<Record<string, unknown>[]> {
45
+ const disks: RowsDisks = new Map();
46
+ const engine = new RowsCacheEngine(config.database, logger, { useOpfs: true });
47
+ inProcessRows(engine, disks);
48
+ await engine.connect(bucket);
49
+ await engine.upsert('thing', 'thing:a', { n: 1 }, 'replace');
50
+ await engine.upsert('thing', 'thing:b', { n: 2 }, 'replace');
51
+ // What `materialize` does: the render set by id, named after the query.
52
+ const rows = await engine.select({ table: 'thing' }, {}, { paintKey: paintKeyOf({ surql, params: {} }, []) });
53
+ (engine as unknown as { paint: { flush(): void } }).paint.flush();
54
+ await engine.close();
55
+ return rows;
56
+ }
57
+
58
+ it('hands a component the rows the query showed last time, with the client not opened', async () => {
59
+ stored.set('sp00ky:last_bucket', 'user_a');
60
+ const probe = new Sp00kyClient<any>(config);
61
+ const surql = probe.query('thing', {}).build().innerQuery.selectQuery.query;
62
+ const rows = await lastSession('user_a', surql);
63
+ expect(rows.map((r) => r.id)).toEqual(['thing:a', 'thing:b']);
64
+
65
+ // The next page load: a client that has been built and nothing more.
66
+ const client = new Sp00kyClient<any>(config);
67
+ expect(client.isLocalReady()).toBe(false);
68
+ expect(client.peekQuery(client.query('thing', {}).build())).toEqual(rows);
69
+ // Another query has no copy.
70
+ expect(client.peekQuery(client.query('thing', {}).where({ n: 1 }).build())).toBeNull();
71
+ });
72
+
73
+ it('paints nothing from another user\'s bucket', async () => {
74
+ stored.set('sp00ky:last_bucket', 'user_a');
75
+ const surql = new Sp00kyClient<any>(config).query('thing', {}).build().innerQuery.selectQuery.query;
76
+ await lastSession('user_a', surql);
77
+ // The browser was last used by someone else: boot will open their bucket.
78
+ stored.set('sp00ky:last_bucket', 'user_b');
79
+ const client = new Sp00kyClient<any>(config);
80
+ expect(client.peekQuery(client.query('thing', {}).build())).toBeNull();
81
+ });
82
+ });