@spooky-sync/client-solid 0.0.1-canary.98 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { Sp00kyClient, fileToUint8Array } from "@spooky-sync/core";
1
+ import { Sp00kyClient, WebPushError, decodeBlurhash, fileToUint8Array, semverGt } from "@spooky-sync/core";
2
2
  import { RecordId, Uuid } from "surrealdb";
3
- import { createComponent, createContext, createEffect, createMemo, createSignal, mergeProps, onCleanup, onMount, useContext } from "solid-js";
3
+ import { children, createComponent, createContext, createEffect, createMemo, createSignal, mergeProps, on, onCleanup, onMount, untrack, useContext } from "solid-js";
4
4
  import { createStore, reconcile } from "solid-js/store";
5
5
 
6
6
  //#region src/lib/context.ts
@@ -46,7 +46,24 @@ function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
46
46
  activeUnsub = void 0;
47
47
  };
48
48
  const sp00ky = db.getSp00ky();
49
+ /**
50
+ * Registration can fail — the canonical case is the SSP answering 503
51
+ * NOT_READY while it bootstraps. Nothing here used to catch that: the
52
+ * rejection escaped as an unhandled promise, `isFetched` stayed false, and
53
+ * `isLoading()` therefore stayed true FOREVER, which is what a spinner that
54
+ * never resolves actually was. Surface it as `error()` instead; the sync
55
+ * scheduler retries the registration underneath, so a transient failure
56
+ * still recovers on its own.
57
+ */
49
58
  const initQuery = async (query, myRun) => {
59
+ try {
60
+ await subscribeQuery(query, myRun);
61
+ } catch (err) {
62
+ if (myRun !== runId) return;
63
+ setError(err instanceof Error ? err : new Error(String(err)));
64
+ }
65
+ };
66
+ const subscribeQuery = async (query, myRun) => {
50
67
  const { hash } = await query.run();
51
68
  if (myRun !== runId) return;
52
69
  activeHash = hash;
@@ -62,10 +79,24 @@ function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
62
79
  if (!isFirstCall || hasData) setIsFetched(true);
63
80
  isFirstCall = false;
64
81
  }, { immediate: true });
65
- const unsubStatus = sp00ky.subscribeQueryStatus(hash, (status) => setIsFetching(status === "fetching"), { immediate: true });
82
+ let known = false;
83
+ let idle = false;
84
+ const settleFromServer = () => {
85
+ if (known && idle && myRun === runId) setIsFetched(true);
86
+ };
87
+ const unsubStatus = sp00ky.subscribeQueryStatus(hash, (status) => {
88
+ setIsFetching(status === "fetching");
89
+ idle = status === "idle";
90
+ settleFromServer();
91
+ }, { immediate: true });
92
+ const unsubAuthority = sp00ky.subscribeQueryAuthority(hash, (k) => {
93
+ known = k;
94
+ settleFromServer();
95
+ }, { immediate: true });
66
96
  const teardown = () => {
67
97
  unsub();
68
98
  unsubStatus();
99
+ unsubAuthority();
69
100
  };
70
101
  if (myRun !== runId) {
71
102
  teardown();
@@ -86,6 +117,7 @@ function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
86
117
  const myRun = ++runId;
87
118
  teardownActive();
88
119
  setIsFetched(false);
120
+ setError(void 0);
89
121
  initQuery(query, myRun);
90
122
  });
91
123
  onCleanup(() => {
@@ -96,14 +128,54 @@ function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
96
128
  const isLoading = () => {
97
129
  return !isFetched() && error() === void 0;
98
130
  };
131
+ const isSettled = () => isFetched() && !isFetching();
99
132
  return {
100
133
  data,
101
134
  error,
102
135
  isLoading,
103
- isFetching
136
+ isFetching,
137
+ isSettled
104
138
  };
105
139
  }
106
140
 
141
+ //#endregion
142
+ //#region src/lib/create-preload.ts
143
+ /**
144
+ * Reactive, fire-and-forget prewarm. Resolves the query (calling it if it's a
145
+ * function so it tracks reactive deps), dedupes on the query's stable identity
146
+ * hash, and registers it via `db.preload`: a live query nobody subscribes to,
147
+ * evicted a ttl after it was registered unless a view mounts it first. Nothing
148
+ * to clean up here.
149
+ *
150
+ * Typical use: inside a list row, preload the detail query the user is likely
151
+ * to open next, so navigation paints from cache instead of the network.
152
+ */
153
+ function createPreload(dbOrQuery, queryOrOptions, maybeOptions) {
154
+ let db;
155
+ let finalQuery;
156
+ let options;
157
+ if (dbOrQuery instanceof SyncedDb) {
158
+ db = dbOrQuery;
159
+ finalQuery = queryOrOptions;
160
+ options = maybeOptions;
161
+ } else {
162
+ const contextDb = useContext(Sp00kyContext);
163
+ if (!contextDb) throw new Error("createPreload: No db argument provided and no Sp00kyContext found. Either pass a SyncedDb instance or wrap your app in <Sp00kyProvider>.");
164
+ db = contextDb;
165
+ finalQuery = dbOrQuery;
166
+ options = queryOrOptions;
167
+ }
168
+ let prevHash;
169
+ createEffect(() => {
170
+ if (!(options?.enabled?.() ?? true)) return;
171
+ const query = typeof finalQuery === "function" ? finalQuery() : finalQuery;
172
+ if (!query) return;
173
+ if (query.hash === prevHash) return;
174
+ prevHash = query.hash;
175
+ db.getSp00ky().preload(query, { signal: options?.signal });
176
+ });
177
+ }
178
+
107
179
  //#endregion
108
180
  //#region src/lib/use-sync-status.ts
109
181
  /**
@@ -124,45 +196,179 @@ function useSyncStatus() {
124
196
  health,
125
197
  status: () => health().status,
126
198
  isHealthy: () => health().status === "healthy",
127
- isDegraded: () => health().status === "degraded"
199
+ isDegraded: () => health().status === "degraded",
200
+ everConnected: () => health().everConnected,
201
+ isOffline: () => health().status === "degraded" && health().everConnected,
202
+ connection: () => health().connection,
203
+ isReconnecting: () => health().connection === "reconnecting"
204
+ };
205
+ }
206
+
207
+ //#endregion
208
+ //#region src/lib/use-impersonation.ts
209
+ /**
210
+ * Observe admin impersonation (started from the DevTools). The client already
211
+ * shows its own warning bar with a Stop button; use this for anything extra,
212
+ * such as hiding actions an admin should not take on someone's behalf.
213
+ * Must be used within a `<Sp00kyProvider>`.
214
+ */
215
+ function useImpersonation(options = {}) {
216
+ const db = useDb();
217
+ const [impersonation, setImpersonation] = createSignal(db.auth.impersonation);
218
+ onCleanup(db.auth.subscribeImpersonation(setImpersonation));
219
+ createEffect(() => {
220
+ if (options.rendersBanner && impersonation()) db.acknowledgeImpersonationBanner();
221
+ });
222
+ return {
223
+ impersonation,
224
+ isImpersonating: () => impersonation() !== null,
225
+ stop: () => db.auth.stopImpersonating()
226
+ };
227
+ }
228
+
229
+ //#endregion
230
+ //#region src/lib/use-storage-status.ts
231
+ /**
232
+ * Observe how durable the LOCAL cache is, for a "no local storage" warning.
233
+ *
234
+ * Under `localEngine: 'sqlite'` with `store: 'indexeddb'` the durable store is
235
+ * the OPFS SAHPool VFS, and only ONE client per bucket can hold it open: a
236
+ * second tab of the same app cannot get it and runs in memory instead (the
237
+ * engine retries first, so a closing tab's lock is usually waited out). Must be
238
+ * used within a `<Sp00kyProvider>`.
239
+ */
240
+ function useStorageStatus() {
241
+ const db = useDb();
242
+ const [health, setHealth] = createSignal(db.storageHealth);
243
+ onCleanup(db.subscribeToStorageHealth(setHealth));
244
+ return {
245
+ health,
246
+ status: () => health().status,
247
+ isPersistent: () => health().status === "persistent",
248
+ isMemoryFallback: () => health().fallback
128
249
  };
129
250
  }
130
251
 
131
252
  //#endregion
132
253
  //#region src/lib/use-crdt-field.ts
133
- function useCrdtField(table, recordId, field, fallbackText) {
254
+ /**
255
+ * Open a `@crdt` field of the record `recordId()` names, for an editor to bind
256
+ * to (`field()?.getDoc()`). Re-opens when the id changes; closes on cleanup.
257
+ *
258
+ * The accessor stays `null` until the field is loaded (`CrdtField.isLoaded`):
259
+ * this device had the document, or the server answered. Until then the
260
+ * document may be empty only because nothing has arrived yet, so show the
261
+ * column's text instead of binding an editor to it.
262
+ */
263
+ function useCrdtField(table, recordId, field) {
134
264
  const db = useContext(Sp00kyContext);
135
265
  if (!db) throw new Error("useCrdtField must be used within a <Sp00kyProvider>");
136
266
  const [crdtField, setCrdtField] = createSignal(null);
137
- let currentId;
138
- let initialized = false;
139
- createEffect(() => {
140
- const id = recordId();
141
- if (initialized && id === currentId) return;
142
- if (currentId && crdtField()) {
143
- db.getSp00ky().closeCrdtField(table, currentId, field);
144
- setCrdtField(null);
145
- }
146
- currentId = id;
147
- initialized = true;
148
- if (!id) return;
267
+ createEffect(on(createMemo(recordId), (current) => {
268
+ if (!current) return;
149
269
  const sp00ky = db.getSp00ky();
150
- const text = fallbackText?.();
151
- sp00ky.openCrdtField(table, id, field, text).then((cf) => {
152
- if (currentId === id) setCrdtField(cf);
270
+ let active = true;
271
+ let opened = false;
272
+ let offLoaded = () => {};
273
+ sp00ky.openCrdtField(table, current, field).then((cf) => {
274
+ opened = true;
275
+ if (!active) {
276
+ sp00ky.closeCrdtField(table, current, field);
277
+ return;
278
+ }
279
+ offLoaded = cf.onLoaded(() => {
280
+ if (active) setCrdtField(cf);
281
+ });
153
282
  }).catch((err) => {
154
- console.error(`[useCrdtField] Failed to open CRDT field ${table}.${field} on ${id}:`, err);
283
+ console.error(`[useCrdtField] Failed to open CRDT field ${table}.${field} on ${current}:`, err);
155
284
  });
156
- });
157
- onCleanup(() => {
158
- if (currentId && crdtField()) {
159
- db.getSp00ky().closeCrdtField(table, currentId, field);
285
+ onCleanup(() => {
286
+ active = false;
287
+ offLoaded();
160
288
  setCrdtField(null);
161
- }
162
- });
289
+ if (opened) sp00ky.closeCrdtField(table, current, field);
290
+ });
291
+ }));
163
292
  return crdtField;
164
293
  }
165
294
 
295
+ //#endregion
296
+ //#region src/lib/use-channel.ts
297
+ const IDLE = {
298
+ status: "idle",
299
+ peers: []
300
+ };
301
+ /**
302
+ * Open a peer to peer channel to `peers` for the rows `query` matches, for
303
+ * the lifetime of the component. The query must be on a `-- @channel` table
304
+ * and only its `where` counts; it is checked against each row, never
305
+ * registered. Writes to matching rows (`db.update` / `db.create` /
306
+ * `db.delete`, or the channel's own) reach the peers over WebRTC in tens of
307
+ * ms; `-- @ephemeral` fields travel only this way. A connection forms when
308
+ * both sides list each other; your own id is skipped.
309
+ *
310
+ * ```ts
311
+ * const ch = useChannel(
312
+ * () => db.query('message').where({ conversation: convoId() }),
313
+ * () => [me(), other()]
314
+ * );
315
+ * ```
316
+ *
317
+ * `query` may be an accessor (re-read when it changes; `null` closes the
318
+ * channel until it returns a query again) or a list of queries.
319
+ */
320
+ function useChannel(query, peers) {
321
+ const db = useContext(Sp00kyContext);
322
+ if (!db) throw new Error("useChannel must be used within a <Sp00kyProvider>.");
323
+ const queries = query;
324
+ const readQueries = () => typeof queries === "function" ? queries() : queries;
325
+ const readPeers = () => typeof peers === "function" ? peers() ?? [] : peers;
326
+ const [state, setState] = createSignal(IDLE);
327
+ let channel = null;
328
+ let stop = () => {};
329
+ const close = () => {
330
+ stop();
331
+ channel?.close();
332
+ channel = null;
333
+ setState(IDLE);
334
+ };
335
+ const sync = (q) => {
336
+ if (!q) return close();
337
+ if (channel) return channel.setQueries(q);
338
+ channel = db.channel(q, untrack(readPeers));
339
+ stop = channel.subscribe(setState);
340
+ };
341
+ sync(untrack(readQueries));
342
+ if (typeof queries === "function") {
343
+ let first = true;
344
+ createEffect(() => {
345
+ const q = queries();
346
+ if (first) return void (first = false);
347
+ sync(q);
348
+ });
349
+ }
350
+ if (typeof peers === "function") {
351
+ let first = true;
352
+ createEffect(() => {
353
+ const next = [...readPeers()];
354
+ if (first) return void (first = false);
355
+ channel?.setPeers(next);
356
+ });
357
+ }
358
+ onCleanup(close);
359
+ const open = () => {
360
+ if (!channel) throw new Error("This channel is closed (its query accessor returned nothing).");
361
+ return channel;
362
+ };
363
+ return {
364
+ status: () => state().status,
365
+ peers: () => state().peers,
366
+ update: ((...args) => open().update(...args)),
367
+ create: ((...args) => open().create(...args)),
368
+ delete: ((...args) => open().delete(...args))
369
+ };
370
+ }
371
+
166
372
  //#endregion
167
373
  //#region src/lib/use-feature-flag.ts
168
374
  /**
@@ -198,6 +404,52 @@ function useFeatureFlag(key, options) {
198
404
  };
199
405
  }
200
406
 
407
+ //#endregion
408
+ //#region src/lib/use-app-release.ts
409
+ async function reloadForSnapshot(snapshot) {
410
+ if (typeof window === "undefined") return;
411
+ if (snapshot.cacheBust) try {
412
+ if (window.caches) {
413
+ const keys = await window.caches.keys();
414
+ await Promise.all(keys.map((k) => window.caches.delete(k)));
415
+ }
416
+ if (navigator.serviceWorker) {
417
+ const regs = await navigator.serviceWorker.getRegistrations();
418
+ for (const r of regs) r.update().catch(() => {});
419
+ }
420
+ window.location.href = window.location.pathname + "?cb=" + Date.now();
421
+ return;
422
+ } catch {}
423
+ window.location.reload();
424
+ }
425
+ /**
426
+ * Observe the app's announced release (`_00_app_release:<app>`, written by
427
+ * `spky deploy` / `spky release`) and compare it against the running build.
428
+ *
429
+ * Typical use: mount a small "new version available — Reload" notification
430
+ * gated on `updateAvailable()`, auto-invoking `reload()` when `mandatory()`
431
+ * (guard the auto path against reload loops with a per-version marker, since
432
+ * a client can reload while the deploy is still rolling out and land on the
433
+ * old bundle again).
434
+ */
435
+ function useAppRelease(options) {
436
+ const handle = useDb().getSp00ky().appRelease(options.app, { ttl: options.ttl });
437
+ const [snapshot, setSnapshot] = createSignal(handle.snapshot());
438
+ const unsub = handle.subscribe(setSnapshot);
439
+ onCleanup(() => {
440
+ unsub();
441
+ handle.close();
442
+ });
443
+ const updateAvailable = () => semverGt(snapshot().version, options.currentVersion);
444
+ return {
445
+ latestVersion: () => snapshot().version,
446
+ updateAvailable,
447
+ mandatory: () => updateAvailable() && snapshot().mandatory,
448
+ cacheBust: () => snapshot().cacheBust,
449
+ reload: () => reloadForSnapshot(snapshot())
450
+ };
451
+ }
452
+
201
453
  //#endregion
202
454
  //#region src/lib/use-file-upload.ts
203
455
  function useFileUpload(dbOrBucketName, maybeBucketName) {
@@ -232,7 +484,7 @@ function useFileUpload(dbOrBucketName, maybeBucketName) {
232
484
  }
233
485
  }
234
486
  };
235
- const upload = async (path, file) => {
487
+ const upload = async (path, file, options) => {
236
488
  setError(null);
237
489
  try {
238
490
  validate(file);
@@ -243,7 +495,7 @@ function useFileUpload(dbOrBucketName, maybeBucketName) {
243
495
  setIsUploading(true);
244
496
  try {
245
497
  const bytes = await fileToUint8Array(file);
246
- await db.bucket(bucketName).put(path, bytes);
498
+ return await db.bucket(bucketName).put(path, bytes, options);
247
499
  } catch (e) {
248
500
  setError(e instanceof Error ? e : new Error(String(e)));
249
501
  } finally {
@@ -293,20 +545,6 @@ function useFileUpload(dbOrBucketName, maybeBucketName) {
293
545
 
294
546
  //#endregion
295
547
  //#region src/lib/use-download-file.ts
296
- const downloadCache = /* @__PURE__ */ new Map();
297
- const inflightRequests = /* @__PURE__ */ new Map();
298
- function cacheKey(bucket, path) {
299
- return `${bucket}:${path}`;
300
- }
301
- function releaseEntry(key) {
302
- const entry = downloadCache.get(key);
303
- if (!entry) return;
304
- entry.refCount--;
305
- if (entry.refCount <= 0) {
306
- URL.revokeObjectURL(entry.url);
307
- downloadCache.delete(key);
308
- }
309
- }
310
548
  function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeOptions) {
311
549
  let db;
312
550
  let bucketName;
@@ -327,62 +565,15 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
327
565
  const [url, setUrl] = createSignal(null);
328
566
  const [isLoading, setIsLoading] = createSignal(false);
329
567
  const [error, setError] = createSignal(null);
330
- let currentKey = null;
568
+ let lease = null;
331
569
  let privateUrl = null;
332
570
  const [refetchSignal, setRefetchSignal] = createSignal(0);
333
- const refetchTrigger = () => setRefetchSignal((n) => n + 1);
334
- async function doDownload(key, filePath) {
335
- if (useCache) {
336
- const cached = downloadCache.get(key);
337
- if (cached) {
338
- cached.refCount++;
339
- currentKey = key;
340
- return cached.url;
341
- }
342
- const inflight = inflightRequests.get(key);
343
- if (inflight) {
344
- const result = await inflight;
345
- if (result) {
346
- const entry = downloadCache.get(key);
347
- if (entry) {
348
- entry.refCount++;
349
- currentKey = key;
350
- }
351
- }
352
- return result;
353
- }
354
- const promise = (async () => {
355
- const content = await db.bucket(bucketName).get(filePath);
356
- if (!content) return null;
357
- const objectUrl = URL.createObjectURL(new Blob([content]));
358
- downloadCache.set(key, {
359
- url: objectUrl,
360
- refCount: 1
361
- });
362
- return objectUrl;
363
- })();
364
- inflightRequests.set(key, promise);
365
- try {
366
- const result = await promise;
367
- currentKey = key;
368
- return result;
369
- } finally {
370
- inflightRequests.delete(key);
371
- }
372
- } else {
373
- const content = await db.bucket(bucketName).get(filePath);
374
- if (!content) return null;
375
- const objectUrl = URL.createObjectURL(new Blob([content]));
376
- privateUrl = objectUrl;
377
- return objectUrl;
378
- }
379
- }
380
- function releaseCurrentEntry() {
381
- if (useCache && currentKey) {
382
- releaseEntry(currentKey);
383
- currentKey = null;
384
- }
385
- if (!useCache && privateUrl) {
571
+ /** Consumed by the next effect run, so `refetch()` bypasses every layer once. */
572
+ let reloadOnce = false;
573
+ function releaseCurrent() {
574
+ lease?.release();
575
+ lease = null;
576
+ if (privateUrl) {
386
577
  URL.revokeObjectURL(privateUrl);
387
578
  privateUrl = null;
388
579
  }
@@ -390,29 +581,40 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
390
581
  createEffect(() => {
391
582
  const filePath = path();
392
583
  refetchSignal();
393
- releaseCurrentEntry();
584
+ releaseCurrent();
394
585
  if (!filePath) {
395
586
  setUrl(null);
396
587
  setIsLoading(false);
397
588
  setError(null);
398
589
  return;
399
590
  }
400
- const key = cacheKey(bucketName, filePath);
401
- if (useCache) {
402
- const cached = downloadCache.get(key);
403
- if (cached) {
404
- cached.refCount++;
405
- currentKey = key;
406
- setUrl(cached.url);
407
- setIsLoading(false);
408
- setError(null);
409
- return;
410
- }
411
- }
591
+ const reload = reloadOnce;
592
+ reloadOnce = false;
412
593
  let cancelled = false;
413
594
  setIsLoading(true);
414
595
  setError(null);
415
- doDownload(key, filePath).then((result) => {
596
+ const bucket = db.bucket(bucketName);
597
+ (useCache ? bucket.url(filePath, {
598
+ persist: options.persist !== false,
599
+ pin: options.pin,
600
+ revalidate: options.revalidate,
601
+ reload
602
+ }).then((acquired) => {
603
+ if (!acquired) return null;
604
+ if (cancelled) {
605
+ acquired.release();
606
+ return null;
607
+ }
608
+ lease = acquired;
609
+ return acquired.url;
610
+ }) : bucket.read(filePath, {
611
+ persist: false,
612
+ reload: true
613
+ }).then((blob) => {
614
+ if (!blob || cancelled) return null;
615
+ privateUrl = URL.createObjectURL(blob);
616
+ return privateUrl;
617
+ })).then((result) => {
416
618
  if (!cancelled) {
417
619
  setUrl(result);
418
620
  setIsLoading(false);
@@ -428,18 +630,11 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
428
630
  });
429
631
  });
430
632
  onCleanup(() => {
431
- releaseCurrentEntry();
633
+ releaseCurrent();
432
634
  });
433
635
  const refetch = () => {
434
- if (useCache && currentKey) {
435
- const entry = downloadCache.get(currentKey);
436
- if (entry) {
437
- URL.revokeObjectURL(entry.url);
438
- downloadCache.delete(currentKey);
439
- }
440
- currentKey = null;
441
- }
442
- refetchTrigger();
636
+ reloadOnce = true;
637
+ setRefetchSignal((n) => n + 1);
443
638
  };
444
639
  return {
445
640
  url,
@@ -449,15 +644,240 @@ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeO
449
644
  };
450
645
  }
451
646
 
647
+ //#endregion
648
+ //#region src/lib/use-blurhash.ts
649
+ function useBlurhash(dbOrBucketName, bucketNameOrPath, maybePath) {
650
+ let db;
651
+ let bucketName;
652
+ let path;
653
+ if (typeof dbOrBucketName === "string") {
654
+ db = useDb();
655
+ bucketName = dbOrBucketName;
656
+ path = bucketNameOrPath;
657
+ } else {
658
+ db = dbOrBucketName;
659
+ bucketName = bucketNameOrPath;
660
+ path = maybePath;
661
+ }
662
+ const [hash, setHash] = createSignal(null);
663
+ const [isLoading, setIsLoading] = createSignal(false);
664
+ createEffect(() => {
665
+ const filePath = path();
666
+ if (!filePath) {
667
+ setHash(null);
668
+ setIsLoading(false);
669
+ return;
670
+ }
671
+ let cancelled = false;
672
+ setIsLoading(true);
673
+ db.bucket(bucketName).blurhash(filePath).then((result) => {
674
+ if (cancelled) return;
675
+ setHash(result);
676
+ setIsLoading(false);
677
+ }).catch(() => {
678
+ if (cancelled) return;
679
+ setHash(null);
680
+ setIsLoading(false);
681
+ });
682
+ onCleanup(() => {
683
+ cancelled = true;
684
+ });
685
+ });
686
+ return {
687
+ hash,
688
+ isLoading
689
+ };
690
+ }
691
+
692
+ //#endregion
693
+ //#region src/lib/use-bucket-image.ts
694
+ function useBucketImage(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeOptions) {
695
+ let db;
696
+ let bucketName;
697
+ let path;
698
+ let options;
699
+ if (typeof dbOrBucketName === "string") {
700
+ db = useDb();
701
+ bucketName = dbOrBucketName;
702
+ path = bucketNameOrPath;
703
+ options = pathOrOptions ?? {};
704
+ } else {
705
+ db = dbOrBucketName;
706
+ bucketName = bucketNameOrPath;
707
+ path = pathOrOptions;
708
+ options = maybeOptions ?? {};
709
+ }
710
+ const wantHash = options.blurhash !== false;
711
+ const { hash } = useBlurhash(db, bucketName, () => wantHash ? path() : null);
712
+ const file = useDownloadFile(db, bucketName, path, options);
713
+ const [ready, setReady] = createSignal(false);
714
+ createEffect(on(file.url, () => setReady(false), { defer: true }));
715
+ const gate = (img) => {
716
+ const done = () => setReady(true);
717
+ if (typeof img.decode === "function") img.decode().then(done, done);
718
+ else if (img.complete) done();
719
+ else {
720
+ img.onload = done;
721
+ img.onerror = done;
722
+ }
723
+ };
724
+ return {
725
+ ...file,
726
+ blurhash: hash,
727
+ ready,
728
+ gate
729
+ };
730
+ }
731
+
732
+ //#endregion
733
+ //#region src/lib/Blurhash.ts
734
+ /**
735
+ * A blurhash painted onto a canvas, once per hash change. Size the canvas via
736
+ * `class`/`style` (e.g. `absolute inset-0 w-full h-full`); the internal decode
737
+ * resolution stays tiny regardless of the displayed size.
738
+ */
739
+ function Blurhash(props) {
740
+ if (typeof document === "undefined") return null;
741
+ const canvas = document.createElement("canvas");
742
+ createEffect(() => {
743
+ canvas.className = props.class ?? "";
744
+ });
745
+ createEffect(() => {
746
+ canvas.style.cssText = props.style ?? "";
747
+ });
748
+ createEffect(() => {
749
+ const width = props.width ?? 32;
750
+ const height = props.height ?? 32;
751
+ canvas.width = width;
752
+ canvas.height = height;
753
+ const hash = props.hash;
754
+ if (!hash) return;
755
+ try {
756
+ const pixels = decodeBlurhash(hash, width, height, props.punch ?? 1);
757
+ const ctx = canvas.getContext("2d");
758
+ if (!ctx) return;
759
+ const imageData = ctx.createImageData(width, height);
760
+ imageData.data.set(pixels);
761
+ ctx.putImageData(imageData, 0, 0);
762
+ } catch {}
763
+ });
764
+ return canvas;
765
+ }
766
+
767
+ //#endregion
768
+ //#region src/lib/BucketImage.ts
769
+ const LAYER_STYLE = "position:absolute;inset:0;width:100%;height:100%;";
770
+ /**
771
+ * A bucket image that never pops in: it layers (bottom to top) your `fallback`
772
+ * plate, the automatically stored blurhash, and the real image, which stays
773
+ * transparent until the bitmap is DECODED and then crossfades over the
774
+ * placeholders. Placeholder layers unmount once the fade settles. Respects
775
+ * prefers-reduced-motion (instant swap). The container is made
776
+ * `position: relative` unless your `class` positions it already.
777
+ *
778
+ * ```tsx
779
+ * <BucketImage bucket="covers" path={row.cover_key} class="absolute inset-0"
780
+ * fallback={<MyPlate />} alt="" />
781
+ * ```
782
+ */
783
+ function BucketImage(props) {
784
+ if (typeof document === "undefined") return null;
785
+ const image = useBucketImage(props.bucket, () => props.path, {
786
+ ...props.options,
787
+ blurhash: props.blurhash !== false
788
+ });
789
+ const reducedMotion = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
790
+ const root = document.createElement("div");
791
+ createEffect(() => {
792
+ root.className = props.class ?? "";
793
+ });
794
+ onMount(() => {
795
+ if (getComputedStyle(root).position === "static") root.style.position = "relative";
796
+ });
797
+ const placeholder = document.createElement("div");
798
+ placeholder.style.cssText = LAYER_STYLE;
799
+ const fallbackHolder = document.createElement("div");
800
+ fallbackHolder.style.cssText = LAYER_STYLE;
801
+ placeholder.append(fallbackHolder);
802
+ const resolvedFallback = children(() => props.fallback);
803
+ createEffect(() => {
804
+ const nodes = resolvedFallback.toArray().filter((node) => node instanceof Node);
805
+ fallbackHolder.replaceChildren(...nodes);
806
+ });
807
+ const hashCanvas = Blurhash({
808
+ get hash() {
809
+ return image.blurhash();
810
+ },
811
+ style: LAYER_STYLE
812
+ });
813
+ if (hashCanvas instanceof Node) placeholder.append(hashCanvas);
814
+ const img = document.createElement("img");
815
+ img.decoding = "async";
816
+ img.style.cssText = `${LAYER_STYLE}opacity:0;`;
817
+ createEffect(() => {
818
+ img.className = props.imgClass ?? "";
819
+ });
820
+ createEffect(() => {
821
+ img.style.objectFit = props.fit ?? "cover";
822
+ });
823
+ createEffect(() => {
824
+ img.alt = props.alt ?? "";
825
+ });
826
+ createEffect(() => {
827
+ img.style.transition = reducedMotion ? "none" : `opacity ${props.transition ?? 300}ms ${props.easing ?? "cubic-bezier(0.16, 1, 0.3, 1)"}`;
828
+ });
829
+ createEffect(() => {
830
+ const url = image.url();
831
+ if (!url) {
832
+ img.removeAttribute("src");
833
+ return;
834
+ }
835
+ img.src = url;
836
+ image.gate(img);
837
+ });
838
+ createEffect(() => {
839
+ img.style.opacity = image.ready() ? "1" : "0";
840
+ });
841
+ const [settled, setSettled] = createSignal(false);
842
+ createEffect(() => {
843
+ if (!image.ready()) {
844
+ setSettled(false);
845
+ return;
846
+ }
847
+ const wait = (reducedMotion ? 0 : props.transition ?? 300) + 120;
848
+ const timer = setTimeout(() => setSettled(true), wait);
849
+ onCleanup(() => clearTimeout(timer));
850
+ });
851
+ createEffect(() => {
852
+ if (settled()) placeholder.remove();
853
+ else if (!placeholder.isConnected) root.insertBefore(placeholder, img);
854
+ });
855
+ root.append(placeholder, img);
856
+ return root;
857
+ }
858
+
452
859
  //#endregion
453
860
  //#region src/lib/Sp00kyProvider.ts
454
861
  function Sp00kyProvider(props) {
455
862
  const merged = mergeProps({ fallback: void 0 }, props);
456
863
  const [db, setDb] = createSignal(void 0);
864
+ let disposed = false;
865
+ onCleanup(() => {
866
+ disposed = true;
867
+ });
457
868
  onMount(async () => {
458
869
  try {
459
870
  const instance = new SyncedDb(merged.config);
460
871
  await instance.init();
872
+ if (disposed) {
873
+ await instance.close();
874
+ return;
875
+ }
876
+ if (merged.preload) try {
877
+ await merged.preload(instance);
878
+ } catch (e) {
879
+ console.error("Sp00kyProvider: preload failed; revealing UI anyway", e);
880
+ }
461
881
  setDb(() => instance);
462
882
  merged.onReady?.(instance);
463
883
  } catch (e) {
@@ -504,6 +924,18 @@ var SyncedDb = class {
504
924
  this._initialized = true;
505
925
  }
506
926
  /**
927
+ * Tear down the client: leaves the tabs broker, closes the local store and
928
+ * remote socket, and frees the wasm circuit. Without this a remounted provider
929
+ * (or an HMR reload) strands a whole client, and the abandoned wasm heaps stay
930
+ * resident because V8 cannot see how much wasm memory a dropped wrapper holds.
931
+ */
932
+ async close() {
933
+ const instance = this.sp00ky;
934
+ this.sp00ky = null;
935
+ this._initialized = false;
936
+ if (instance) await instance.close();
937
+ }
938
+ /**
507
939
  * Create a new record in the database
508
940
  */
509
941
  async create(id, payload) {
@@ -530,6 +962,15 @@ var SyncedDb = class {
530
962
  await this.sp00ky.delete(tableName, id);
531
963
  }
532
964
  /**
965
+ * Preload/prewarm a built query into the local cache without registering a
966
+ * live view. Fetches once and stores the rows (+ embedded related children)
967
+ * locally so a later `useQuery` for the same data paints instantly. Best-effort.
968
+ */
969
+ async preload(finalQuery, options) {
970
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
971
+ await this.sp00ky.preload(finalQuery, options);
972
+ }
973
+ /**
533
974
  * Query data from the database
534
975
  */
535
976
  query(table) {
@@ -537,6 +978,15 @@ var SyncedDb = class {
537
978
  return this.sp00ky.query(table, {});
538
979
  }
539
980
  /**
981
+ * Open a peer to peer channel to `peers` for the rows `query` matches (a
982
+ * query on a `-- @channel` table; only its `where` counts). Prefer the
983
+ * `useChannel` hook, which closes it with the component.
984
+ */
985
+ channel(query, peers) {
986
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
987
+ return this.sp00ky.channel(query, peers);
988
+ }
989
+ /**
540
990
  * Run a backend operation
541
991
  */
542
992
  async run(backend, path, payload, options) {
@@ -558,6 +1008,15 @@ var SyncedDb = class {
558
1008
  await this.signOut();
559
1009
  }
560
1010
  /**
1011
+ * Tell the client that this app's own impersonation banner is on screen.
1012
+ * Only needed with `impersonationBanner: { mode: 'custom' }`; the
1013
+ * `useImpersonation({ rendersBanner: true })` hook calls it for you.
1014
+ */
1015
+ acknowledgeImpersonationBanner() {
1016
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1017
+ this.sp00ky.acknowledgeImpersonationBanner();
1018
+ }
1019
+ /**
561
1020
  * Sign out, clear session and local storage
562
1021
  */
563
1022
  async signOut() {
@@ -572,6 +1031,19 @@ var SyncedDb = class {
572
1031
  return await this.sp00ky.useRemote(fn);
573
1032
  }
574
1033
  /**
1034
+ * Run one SurrealQL statement on the server and return its result array.
1035
+ * Nothing is cached locally. Prefer this over `useRemote(s => s.query(...))`
1036
+ * for a plain read or write: the bare SDK client that callback receives
1037
+ * skips the connect gate, so a statement issued while the socket is being
1038
+ * rebuilt fails with "Specify a namespace to use" instead of waiting for
1039
+ * the session. This one is also bounded by the remote service's
1040
+ * concurrency limit and query timeout.
1041
+ */
1042
+ async remoteQuery(sql, vars) {
1043
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1044
+ return await this.sp00ky.remoteQuery(sql, vars);
1045
+ }
1046
+ /**
575
1047
  * Access the remote database service directly
576
1048
  */
577
1049
  get remote() {
@@ -619,6 +1091,29 @@ var SyncedDb = class {
619
1091
  if (!this.sp00ky) throw new Error("SyncedDb not initialized");
620
1092
  return this.sp00ky.subscribeToSyncHealth(cb);
621
1093
  }
1094
+ /** Current local-store durability snapshot. See {@link useStorageStatus}. */
1095
+ get storageHealth() {
1096
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1097
+ return this.sp00ky.storageHealth;
1098
+ }
1099
+ /**
1100
+ * Observe local-store durability. Fires immediately with the current snapshot
1101
+ * and again on change. Prefer the `useStorageStatus` hook in components; this
1102
+ * is the imperative escape hatch.
1103
+ */
1104
+ subscribeToStorageHealth(cb) {
1105
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1106
+ return this.sp00ky.subscribeToStorageHealth(cb);
1107
+ }
1108
+ /**
1109
+ * Web Push for this browser: `support()`, `subscribe()` (from a click),
1110
+ * `devices()`, `notify()` / `test()` (push to yourself), `bridge()` for the
1111
+ * service worker. See the push-notifications docs page.
1112
+ */
1113
+ get webPush() {
1114
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1115
+ return this.sp00ky.webPush;
1116
+ }
622
1117
  bucket(name) {
623
1118
  if (!this.sp00ky) throw new Error("SyncedDb not initialized");
624
1119
  return this.sp00ky.bucket(name);
@@ -629,5 +1124,5 @@ var SyncedDb = class {
629
1124
  };
630
1125
 
631
1126
  //#endregion
632
- export { RecordId, Sp00kyProvider, SyncedDb, Uuid, useCrdtField, useDb, useDownloadFile, useFeatureFlag, useFileUpload, useQuery, useSyncStatus };
1127
+ export { Blurhash, BucketImage, RecordId, Sp00kyProvider, SyncedDb, Uuid, WebPushError, createPreload, useAppRelease, useBlurhash, useBucketImage, useChannel, useCrdtField, useDb, useDownloadFile, useFeatureFlag, useFileUpload, useImpersonation, useQuery, useStorageStatus, useSyncStatus };
633
1128
  //# sourceMappingURL=index.js.map