@spooky-sync/client-solid2 0.0.1-alpha.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.
Files changed (44) hide show
  1. package/AGENTS.md +81 -0
  2. package/QUICK_START.md +129 -0
  3. package/README.md +19 -0
  4. package/dist/index.cjs +1290 -0
  5. package/dist/index.cjs.map +1 -0
  6. package/dist/index.d.cts +670 -0
  7. package/dist/index.d.cts.map +1 -0
  8. package/dist/index.d.ts +670 -0
  9. package/dist/index.d.ts.map +1 -0
  10. package/dist/index.js +1266 -0
  11. package/dist/index.js.map +1 -0
  12. package/package.json +63 -0
  13. package/skills/sp00ky-solid2/SKILL.md +71 -0
  14. package/src/index.ts +410 -0
  15. package/src/lib/Blurhash.ts +64 -0
  16. package/src/lib/BucketImage.ts +170 -0
  17. package/src/lib/Sp00kyProvider.ts +104 -0
  18. package/src/lib/__tests__/conflate.test.ts +120 -0
  19. package/src/lib/__tests__/create-query.test.ts +397 -0
  20. package/src/lib/__tests__/rc-semantics.test.ts +393 -0
  21. package/src/lib/__tests__/use-sync-activity.test.ts +104 -0
  22. package/src/lib/conflate.ts +74 -0
  23. package/src/lib/context.ts +28 -0
  24. package/src/lib/create-preload.ts +116 -0
  25. package/src/lib/create-query.ts +388 -0
  26. package/src/lib/create-submission.ts +57 -0
  27. package/src/lib/from-subscription.ts +32 -0
  28. package/src/lib/merge-rows.test.ts +92 -0
  29. package/src/lib/merge-rows.ts +72 -0
  30. package/src/lib/models.ts +8 -0
  31. package/src/lib/use-app-release.ts +89 -0
  32. package/src/lib/use-blurhash.ts +82 -0
  33. package/src/lib/use-bucket-image.ts +108 -0
  34. package/src/lib/use-crdt-field.ts +57 -0
  35. package/src/lib/use-download-file.ts +181 -0
  36. package/src/lib/use-feature-flag.ts +43 -0
  37. package/src/lib/use-file-upload.ts +146 -0
  38. package/src/lib/use-storage-status.ts +44 -0
  39. package/src/lib/use-sync-activity.ts +99 -0
  40. package/src/lib/use-sync-status.ts +63 -0
  41. package/src/types/index.ts +83 -0
  42. package/tsconfig.json +27 -0
  43. package/tsdown.config.ts +20 -0
  44. package/vitest.config.ts +14 -0
package/dist/index.js ADDED
@@ -0,0 +1,1266 @@
1
+ import { Sp00kyClient, decodeBlurhash, fileToUint8Array, semverGt } from "@spooky-sync/core";
2
+ import { RecordId, Uuid } from "surrealdb";
3
+ import { children, createComponent, createContext, createEffect, createMemo, createSignal, createStore, merge, onCleanup, onSettled, snapshot, useContext } from "solid-js";
4
+
5
+ //#region src/lib/conflate.ts
6
+ /**
7
+ * Latest-wins async iterable over a subscribe-callback source.
8
+ *
9
+ * Bridges spooky's push-callback subscriptions into the AsyncIterable shape
10
+ * Solid 2 computations consume natively. Each spooky emission is a full result
11
+ * set, so intermediate values are droppable: only the newest unconsumed value
12
+ * is buffered, and a pending pull resolves with it immediately.
13
+ *
14
+ * Teardown contract (probed in rc-semantics.test.ts): Solid 2 does NOT
15
+ * terminate a superseded/disposed computation's async generator — no
16
+ * `return()`, no `finally`. Consumers MUST call `it.return()` themselves from
17
+ * an `onCleanup` registered synchronously in the compute scope. `return()`
18
+ * unsubscribes (awaiting the unsubscribe if the subscribe returned a promise,
19
+ * as `sp00ky.subscribe` does) and resolves any parked pull as done.
20
+ */
21
+ function conflate(subscribe) {
22
+ return { [Symbol.asyncIterator]() {
23
+ let buffered;
24
+ let resolveNext;
25
+ let done = false;
26
+ const unsubMaybe = subscribe((v) => {
27
+ if (done) return;
28
+ if (resolveNext) {
29
+ const r = resolveNext;
30
+ resolveNext = void 0;
31
+ r({
32
+ value: v,
33
+ done: false
34
+ });
35
+ } else buffered = { v };
36
+ });
37
+ const finish = () => {
38
+ if (done) return;
39
+ done = true;
40
+ buffered = void 0;
41
+ Promise.resolve(unsubMaybe).then((unsub) => unsub()).catch(() => {});
42
+ if (resolveNext) {
43
+ const r = resolveNext;
44
+ resolveNext = void 0;
45
+ r({
46
+ value: void 0,
47
+ done: true
48
+ });
49
+ }
50
+ };
51
+ return {
52
+ next() {
53
+ if (done) return Promise.resolve({
54
+ value: void 0,
55
+ done: true
56
+ });
57
+ if (buffered) {
58
+ const v = buffered.v;
59
+ buffered = void 0;
60
+ return Promise.resolve({
61
+ value: v,
62
+ done: false
63
+ });
64
+ }
65
+ return new Promise((r) => resolveNext = r);
66
+ },
67
+ return() {
68
+ finish();
69
+ return Promise.resolve({
70
+ value: void 0,
71
+ done: true
72
+ });
73
+ },
74
+ throw(e) {
75
+ finish();
76
+ return Promise.reject(e);
77
+ }
78
+ };
79
+ } };
80
+ }
81
+
82
+ //#endregion
83
+ //#region src/lib/from-subscription.ts
84
+ /**
85
+ * Reactive view over a spooky subscribe-callback API.
86
+ *
87
+ * The memo's async generator pulls from a conflated (latest-wins) iterator;
88
+ * `initial` is committed as the memo's `loadingValue`, so the accessor is
89
+ * readable synchronously from birth and never suspends. Spooky's subscribe
90
+ * APIs fire immediately with the current value, so the real value lands within
91
+ * a tick of the first read.
92
+ *
93
+ * Teardown is manual by contract (see conflate.ts): onCleanup terminates the
94
+ * iterator, which unsubscribes.
95
+ */
96
+ function fromSubscription(subscribe, initial) {
97
+ return createMemo(async function* () {
98
+ const it = conflate(subscribe)[Symbol.asyncIterator]();
99
+ onCleanup(() => void it.return?.());
100
+ while (true) {
101
+ const r = await it.next();
102
+ if (r.done) break;
103
+ yield r.value;
104
+ }
105
+ }, { loadingValue: initial });
106
+ }
107
+
108
+ //#endregion
109
+ //#region src/lib/context.ts
110
+ const Sp00kyContext = createContext();
111
+ function useDb() {
112
+ try {
113
+ return useContext(Sp00kyContext);
114
+ } catch {
115
+ throw new Error("useDb must be used within a <Sp00kyProvider>. Wrap your app in <Sp00kyProvider config={...}>.");
116
+ }
117
+ }
118
+ /**
119
+ * Count of locally-committed mutations not yet acknowledged by the server.
120
+ * Drive an "unsaved changes" indicator off this.
121
+ */
122
+ function usePendingMutations() {
123
+ const db = useDb();
124
+ return fromSubscription((cb) => db.subscribeToPendingMutations(cb), db.pendingMutationCount);
125
+ }
126
+
127
+ //#endregion
128
+ //#region src/lib/merge-rows.ts
129
+ /**
130
+ * Keyed in-place merge of a fresh row list into a store draft array.
131
+ *
132
+ * Why not `reconcile(rows, 'id')`: in Solid 2 rc.1 a reconcile REPLACES the row
133
+ * objects, so a component that captured `data()[0]` sees a different object
134
+ * after the next emission, and anything keyed on row identity (`<For>` without
135
+ * an explicit key, a memo comparing rows) re-creates its subtree on every live
136
+ * update. Mutating the draft in place keeps the identity AND keeps updates
137
+ * fine-grained: only the fields that actually changed are written, so a row
138
+ * whose data is unchanged notifies nobody.
139
+ *
140
+ * Rows are matched by `key` (default `id`); unmatched incoming rows are
141
+ * inserted as-is and trailing rows are dropped, so add / remove / reorder all
142
+ * reach coarse readers.
143
+ */
144
+ /**
145
+ * Field-level equality for the merge. `===` is not enough: the decoder hands
146
+ * out a fresh RecordId / Date instance for every record-link and datetime
147
+ * column on every emission, so by identity every one of those fields "changed"
148
+ * on every update - and a store write on an unchanged `id` re-ran everything a
149
+ * page keyed on that row (a thread's anchor, its composer, its whole subtree).
150
+ * Compare those wrappers by value; everything else stays identity (nested
151
+ * objects and arrays are reconciled by their own writes).
152
+ */
153
+ function sameValue(a, b) {
154
+ if (a === b) return true;
155
+ if (a == null || b == null) return false;
156
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
157
+ if (typeof a === "object" && typeof b === "object") {
158
+ const ctor = a.constructor;
159
+ if (ctor && ctor === b.constructor && ctor !== Object && ctor !== Array) return String(a) === String(b);
160
+ }
161
+ return false;
162
+ }
163
+ function mergeRows(draft, next, key = "id") {
164
+ const byKey = /* @__PURE__ */ new Map();
165
+ for (const row of draft) {
166
+ const k = row?.[key];
167
+ if (k !== void 0) byKey.set(String(k), row);
168
+ }
169
+ for (let i = 0; i < next.length; i++) {
170
+ const incoming = next[i];
171
+ const k = incoming?.[key];
172
+ const reuse = k !== void 0 ? byKey.get(String(k)) : void 0;
173
+ if (reuse) {
174
+ for (const field of Object.keys(incoming)) if (!sameValue(reuse[field], incoming[field])) reuse[field] = incoming[field];
175
+ for (const field of Object.keys(snapshot(reuse))) if (!(field in incoming)) delete reuse[field];
176
+ if (draft[i] !== reuse) draft[i] = reuse;
177
+ } else if (draft[i] !== incoming) draft[i] = incoming;
178
+ }
179
+ if (draft.length > next.length) draft.splice(next.length);
180
+ }
181
+
182
+ //#endregion
183
+ //#region src/lib/create-query.ts
184
+ function createQuery(dbOrQuery, queryOrOptions, maybeOptions) {
185
+ let db;
186
+ let finalQuery;
187
+ let options;
188
+ if (dbOrQuery instanceof SyncedDb) {
189
+ db = dbOrQuery;
190
+ finalQuery = queryOrOptions;
191
+ options = maybeOptions;
192
+ } else {
193
+ db = useDb();
194
+ finalQuery = dbOrQuery;
195
+ options = queryOrOptions;
196
+ }
197
+ const sp00ky = db.getSp00ky();
198
+ const [error, setError] = createSignal(void 0, { ownedWrite: true });
199
+ const [isAuthoritative, setIsAuthoritative] = createSignal(false, { ownedWrite: true });
200
+ const [hasPainted, setHasPainted] = createSignal(false, { ownedWrite: true });
201
+ const [isFetching, setIsFetching] = createSignal(false, { ownedWrite: true });
202
+ let activeHash;
203
+ const [store, setStore] = createStore({ value: null });
204
+ let runId = 0;
205
+ let readyWaiters = [];
206
+ const wakeReady = () => {
207
+ const waiters = readyWaiters;
208
+ readyWaiters = [];
209
+ for (const w of waiters) w();
210
+ };
211
+ createEffect(() => {
212
+ return {
213
+ enabled: options?.enabled?.() ?? true,
214
+ query: typeof finalQuery === "function" ? finalQuery() : finalQuery
215
+ };
216
+ }, ({ enabled, query }) => {
217
+ const myRun = ++runId;
218
+ setIsAuthoritative(false);
219
+ setHasPainted(false);
220
+ setError(void 0);
221
+ if (!enabled || !query) return;
222
+ const cleanups = [];
223
+ let disposed = false;
224
+ const addCleanup = (c) => {
225
+ if (!c) return;
226
+ if (typeof c === "function") {
227
+ if (disposed) c();
228
+ else cleanups.push(c);
229
+ return;
230
+ }
231
+ Promise.resolve(c).then((fn) => {
232
+ if (typeof fn !== "function") return;
233
+ if (disposed) fn();
234
+ else cleanups.push(fn);
235
+ });
236
+ };
237
+ /**
238
+ * Registration can fail — the canonical case is the SSP answering 503
239
+ * NOT_READY while it bootstraps. Surface it as `error()` instead of
240
+ * throwing into the graph: the sync scheduler retries the registration
241
+ * underneath, so a transient failure still recovers, and a spinner
242
+ * driven by `isLoading()` resolves via `error()`.
243
+ */
244
+ query.run().then(({ hash }) => {
245
+ if (disposed || myRun !== runId) return;
246
+ activeHash = hash;
247
+ addCleanup(sp00ky.subscribeQueryStatus(hash, (status) => setIsFetching(status === "fetching"), { immediate: true }));
248
+ addCleanup(sp00ky.subscribeQueryAuthority(hash, (known) => {
249
+ if (disposed || myRun !== runId) return;
250
+ setIsAuthoritative(known);
251
+ if (known) wakeReady();
252
+ else setHasPainted(false);
253
+ }, { immediate: true }));
254
+ addCleanup(sp00ky.subscribe(hash, (rows) => {
255
+ if (disposed || myRun !== runId) return;
256
+ const queryData = query.isOne ? rows[0] ?? null : rows;
257
+ if (query.isOne ? queryData !== null && queryData !== void 0 : rows.length > 0) {
258
+ setHasPainted(true);
259
+ wakeReady();
260
+ }
261
+ const t0 = performance.now();
262
+ setStore((s) => {
263
+ if (query.isOne || queryData === null || !Array.isArray(s.value)) s.value = queryData;
264
+ else mergeRows(s.value, queryData);
265
+ });
266
+ sp00ky.reportFrontendTiming(hash, performance.now() - t0);
267
+ }, { immediate: true }));
268
+ }).catch((err) => {
269
+ if (disposed || myRun !== runId) return;
270
+ setError(err instanceof Error ? err : new Error(String(err)));
271
+ wakeReady();
272
+ });
273
+ return () => {
274
+ disposed = true;
275
+ for (const c of cleanups) c();
276
+ };
277
+ });
278
+ const emptyList = [];
279
+ const data = () => {
280
+ const v = store.value;
281
+ if (v === null || v === void 0) {
282
+ const query = typeof finalQuery === "function" ? finalQuery() : finalQuery;
283
+ if (query && !query.isOne) return emptyList;
284
+ }
285
+ return v;
286
+ };
287
+ const readyGate = createMemo(async () => {
288
+ if (isAuthoritative() || hasPainted() || error()) return true;
289
+ await new Promise((resolve) => readyWaiters.push(resolve));
290
+ return true;
291
+ }, { lazy: true });
292
+ const ready = () => {
293
+ readyGate();
294
+ return data();
295
+ };
296
+ onCleanup(() => {
297
+ if (options?.deregisterOnCleanup && activeHash) sp00ky.deregisterQuery(activeHash);
298
+ });
299
+ const hasData = () => {
300
+ const v = store.value;
301
+ return Array.isArray(v) ? v.length > 0 : v !== null && v !== void 0;
302
+ };
303
+ const isLoading = () => !isAuthoritative() && !hasPainted() && error() === void 0;
304
+ const isEmpty = () => isAuthoritative() && !hasData();
305
+ const isSettled = () => isAuthoritative() && !isFetching();
306
+ return {
307
+ data,
308
+ ready,
309
+ error,
310
+ isLoading,
311
+ isFetching,
312
+ isAuthoritative,
313
+ hasData,
314
+ isEmpty,
315
+ isSettled
316
+ };
317
+ }
318
+ /** @deprecated Renamed `createQuery` in the Solid 2 binding. */
319
+ const useQuery = createQuery;
320
+
321
+ //#endregion
322
+ //#region src/lib/create-preload.ts
323
+ /**
324
+ * Reactive, fire-and-forget prewarm. Resolves the query (calling it if it's a
325
+ * function so it tracks reactive deps), dedupes on the query's stable identity
326
+ * hash, and registers it via `db.preload`: a live query nobody subscribes to,
327
+ * evicted a ttl after it was registered unless a view mounts it first. Nothing
328
+ * to clean up here.
329
+ *
330
+ * Typical use: inside a list row, preload the detail query the user is likely
331
+ * to open next, so navigation paints from cache instead of the network.
332
+ */
333
+ function createPreload(dbOrQuery, queryOrOptions, maybeOptions) {
334
+ let db;
335
+ let finalQuery;
336
+ let options;
337
+ if (dbOrQuery instanceof SyncedDb) {
338
+ db = dbOrQuery;
339
+ finalQuery = queryOrOptions;
340
+ options = maybeOptions;
341
+ } else {
342
+ db = useDb();
343
+ finalQuery = dbOrQuery;
344
+ options = queryOrOptions;
345
+ }
346
+ let prevHash;
347
+ createEffect(() => {
348
+ if (!(options?.enabled?.() ?? true)) return void 0;
349
+ const query = typeof finalQuery === "function" ? finalQuery() : finalQuery;
350
+ if (!query) return void 0;
351
+ if (query.hash === prevHash) return void 0;
352
+ prevHash = query.hash;
353
+ return query;
354
+ }, (query) => {
355
+ if (!query) return;
356
+ db.getSp00ky().preload(query, { signal: options?.signal });
357
+ });
358
+ }
359
+
360
+ //#endregion
361
+ //#region src/lib/use-sync-status.ts
362
+ /**
363
+ * Observe sync health for a "can't reach the server" banner / indicator.
364
+ *
365
+ * Backed by `db.subscribeToSyncHealth`. Individual sync failures (a transient
366
+ * remote 500 on query registration, a dropped socket) are absorbed by the
367
+ * retry and never flip this; `isDegraded()` only goes true once failures
368
+ * persist for the configured number of consecutive rounds (sp00ky core config
369
+ * `syncHealth.degradeAfterConsecutiveFailures`, default 3), and flips back on
370
+ * the next successful round. Must be used within a `<Sp00kyProvider>`.
371
+ */
372
+ function useSyncStatus() {
373
+ const db = useDb();
374
+ const health = fromSubscription((cb) => db.subscribeToSyncHealth(cb), db.syncHealth);
375
+ return {
376
+ health,
377
+ status: () => health().status,
378
+ isHealthy: () => health().status === "healthy",
379
+ isDegraded: () => health().status === "degraded",
380
+ everConnected: () => health().everConnected,
381
+ isOffline: () => health().status === "degraded" && health().everConnected,
382
+ connection: () => health().connection,
383
+ isReconnecting: () => health().connection === "reconnecting"
384
+ };
385
+ }
386
+
387
+ //#endregion
388
+ //#region src/lib/use-sync-activity.ts
389
+ /**
390
+ * The two directions of sync traffic, for an indicator in the app chrome.
391
+ *
392
+ * `fetchingQueries` is one subscription on the engine's aggregate fetch count,
393
+ * not one per query; `pendingMutations` is the outbox depth. `isDownloading`
394
+ * is the fetch count debounced ON by `downloadDelayMs` (and off at once), so a
395
+ * local-first page that answers from cache and confirms with the server in a
396
+ * few milliseconds never flickers. Must be used within a `<Sp00kyProvider>`, or
397
+ * pass the `SyncedDb` explicitly.
398
+ */
399
+ function useSyncActivity(dbOrOptions, maybeOptions) {
400
+ const explicitDb = dbOrOptions && typeof dbOrOptions.subscribeToFetchActivity === "function" ? dbOrOptions : void 0;
401
+ const options = (explicitDb ? maybeOptions : dbOrOptions) ?? {};
402
+ const db = explicitDb ?? useDb();
403
+ const downloadDelayMs = options.downloadDelayMs ?? 200;
404
+ const uploadThreshold = options.uploadThreshold ?? 1;
405
+ const fetchingQueries = fromSubscription((cb) => db.subscribeToFetchActivity(cb), db.fetchingQueryCount);
406
+ const pendingMutations = fromSubscription((cb) => db.subscribeToPendingMutations(cb), db.pendingMutationCount);
407
+ const [isDownloading, setIsDownloading] = createSignal(false, { ownedWrite: true });
408
+ let timer;
409
+ createEffect(() => fetchingQueries() > 0, (busy) => {
410
+ if (timer !== void 0) {
411
+ clearTimeout(timer);
412
+ timer = void 0;
413
+ }
414
+ if (!busy) {
415
+ setIsDownloading(false);
416
+ return;
417
+ }
418
+ if (downloadDelayMs <= 0) {
419
+ setIsDownloading(true);
420
+ return;
421
+ }
422
+ timer = setTimeout(() => {
423
+ timer = void 0;
424
+ setIsDownloading(true);
425
+ }, downloadDelayMs);
426
+ });
427
+ onCleanup(() => {
428
+ if (timer !== void 0) clearTimeout(timer);
429
+ });
430
+ return {
431
+ fetchingQueries,
432
+ pendingMutations,
433
+ isDownloading,
434
+ isUploading: () => pendingMutations() > uploadThreshold
435
+ };
436
+ }
437
+
438
+ //#endregion
439
+ //#region src/lib/use-storage-status.ts
440
+ /**
441
+ * Observe how durable the LOCAL cache is, for a "no local storage" warning.
442
+ *
443
+ * Under `localEngine: 'sqlite'` with `store: 'indexeddb'` the durable store is
444
+ * the OPFS SAHPool VFS, and only ONE client per bucket can hold it open: a
445
+ * second tab of the same app cannot get it and runs in memory instead (the
446
+ * engine retries first, so a closing tab's lock is usually waited out). Must be
447
+ * used within a `<Sp00kyProvider>`.
448
+ */
449
+ function useStorageStatus() {
450
+ const db = useDb();
451
+ const health = fromSubscription((cb) => db.subscribeToStorageHealth(cb), db.storageHealth);
452
+ return {
453
+ health,
454
+ status: () => health().status,
455
+ isPersistent: () => health().status === "persistent",
456
+ isMemoryFallback: () => health().fallback
457
+ };
458
+ }
459
+
460
+ //#endregion
461
+ //#region src/lib/use-crdt-field.ts
462
+ function useCrdtField(table, recordId, field, fallbackText) {
463
+ const db = useDb();
464
+ const [crdtField, setCrdtField] = createSignal(null, { ownedWrite: true });
465
+ createEffect(() => recordId(), (id) => {
466
+ if (!id) {
467
+ setCrdtField(null);
468
+ return;
469
+ }
470
+ const sp00ky = db.getSp00ky();
471
+ let superseded = false;
472
+ const text = fallbackText?.();
473
+ sp00ky.openCrdtField(table, id, field, text).then((cf) => {
474
+ if (!superseded) setCrdtField(cf);
475
+ else sp00ky.closeCrdtField(table, id, field);
476
+ }).catch((err) => {
477
+ console.error(`[useCrdtField] Failed to open CRDT field ${table}.${field} on ${id}:`, err);
478
+ });
479
+ return () => {
480
+ superseded = true;
481
+ if (crdtField()) {
482
+ sp00ky.closeCrdtField(table, id, field);
483
+ setCrdtField(null);
484
+ }
485
+ };
486
+ });
487
+ return crdtField;
488
+ }
489
+
490
+ //#endregion
491
+ //#region src/lib/use-feature-flag.ts
492
+ /**
493
+ * Subscribe to a feature flag for the currently authenticated user.
494
+ *
495
+ * Returns three Solid accessors that update reactively whenever the
496
+ * server-materialized assignment in `_00_user_feature` changes. Backed by
497
+ * the same SSP + sync pipeline that powers `createQuery`, so toggling a flag
498
+ * via `spky flag enable <key>` propagates to the UI without a refresh.
499
+ *
500
+ * `enabled()` is `true` when the resolved variant exists and is not 'off'.
501
+ * For multi-variant flags, prefer `variant()` directly.
502
+ */
503
+ function useFeatureFlag(key, options) {
504
+ const handle = useDb().getSp00ky().feature(key, options);
505
+ onCleanup(() => handle.close());
506
+ const state = fromSubscription((cb) => handle.subscribe((s) => cb({
507
+ variant: s.variant ?? options?.fallback,
508
+ payload: s.payload
509
+ })), {
510
+ variant: handle.variant(),
511
+ payload: handle.payload()
512
+ });
513
+ return {
514
+ variant: () => state().variant,
515
+ payload: () => state().payload,
516
+ enabled: () => {
517
+ const v = state().variant;
518
+ return v !== void 0 && v !== "off";
519
+ }
520
+ };
521
+ }
522
+
523
+ //#endregion
524
+ //#region src/lib/use-app-release.ts
525
+ async function reloadForSnapshot(snapshot) {
526
+ if (typeof window === "undefined") return;
527
+ if (snapshot.cacheBust) try {
528
+ if (window.caches) {
529
+ const keys = await window.caches.keys();
530
+ await Promise.all(keys.map((k) => window.caches.delete(k)));
531
+ }
532
+ if (navigator.serviceWorker) {
533
+ const regs = await navigator.serviceWorker.getRegistrations();
534
+ for (const r of regs) r.update().catch(() => {});
535
+ }
536
+ window.location.href = window.location.pathname + "?cb=" + Date.now();
537
+ return;
538
+ } catch {}
539
+ window.location.reload();
540
+ }
541
+ /**
542
+ * Observe the app's announced release (`_00_app_release:<app>`, written by
543
+ * `spky deploy` / `spky release`) and compare it against the running build.
544
+ *
545
+ * Typical use: mount a small "new version available — Reload" notification
546
+ * gated on `updateAvailable()`, auto-invoking `reload()` when `mandatory()`
547
+ * (guard the auto path against reload loops with a per-version marker, since
548
+ * a client can reload while the deploy is still rolling out and land on the
549
+ * old bundle again).
550
+ */
551
+ function useAppRelease(options) {
552
+ const handle = useDb().getSp00ky().appRelease(options.app, { ttl: options.ttl });
553
+ onCleanup(() => handle.close());
554
+ const snapshot = fromSubscription((cb) => handle.subscribe(cb), handle.snapshot());
555
+ const updateAvailable = () => semverGt(snapshot().version, options.currentVersion);
556
+ return {
557
+ latestVersion: () => snapshot().version,
558
+ updateAvailable,
559
+ mandatory: () => updateAvailable() && snapshot().mandatory,
560
+ cacheBust: () => snapshot().cacheBust,
561
+ reload: () => reloadForSnapshot(snapshot())
562
+ };
563
+ }
564
+
565
+ //#endregion
566
+ //#region src/lib/use-file-upload.ts
567
+ function useFileUpload(dbOrBucketName, maybeBucketName) {
568
+ let db;
569
+ let bucketName;
570
+ if (typeof dbOrBucketName === "string") {
571
+ db = useDb();
572
+ bucketName = dbOrBucketName;
573
+ } else {
574
+ db = dbOrBucketName;
575
+ bucketName = maybeBucketName;
576
+ }
577
+ const [isUploading, setIsUploading] = createSignal(false, { ownedWrite: true });
578
+ const [error, setError] = createSignal(null, { ownedWrite: true });
579
+ const objectUrls = [];
580
+ onCleanup(() => {
581
+ for (const url of objectUrls) URL.revokeObjectURL(url);
582
+ });
583
+ const clearError = () => setError(null);
584
+ const validate = (file) => {
585
+ const config = db.getBucketConfig(bucketName);
586
+ if (!config) return;
587
+ if (config.maxSize !== null && config.maxSize !== void 0 && file.size > config.maxSize) {
588
+ const maxMB = (config.maxSize / (1024 * 1024)).toFixed(1);
589
+ throw new Error(`File exceeds maximum size of ${maxMB} MB.`);
590
+ }
591
+ if (config.allowedExtensions && config.allowedExtensions.length > 0) {
592
+ const fileName = file.name;
593
+ if (fileName) {
594
+ const ext = fileName.split(".").pop()?.toLowerCase();
595
+ if (!ext || !config.allowedExtensions.includes(ext)) throw new Error(`File type not allowed. Accepted: ${config.allowedExtensions.join(", ")}.`);
596
+ }
597
+ }
598
+ };
599
+ const upload = async (path, file, options) => {
600
+ setError(null);
601
+ try {
602
+ validate(file);
603
+ } catch (e) {
604
+ setError(e instanceof Error ? e : new Error(String(e)));
605
+ return;
606
+ }
607
+ setIsUploading(true);
608
+ try {
609
+ const bytes = await fileToUint8Array(file);
610
+ return await db.bucket(bucketName).put(path, bytes, options);
611
+ } catch (e) {
612
+ setError(e instanceof Error ? e : new Error(String(e)));
613
+ } finally {
614
+ setIsUploading(false);
615
+ }
616
+ };
617
+ const download = async (path) => {
618
+ setError(null);
619
+ try {
620
+ const content = await db.bucket(bucketName).get(path);
621
+ if (!content) return null;
622
+ const objectUrl = URL.createObjectURL(new Blob([content]));
623
+ objectUrls.push(objectUrl);
624
+ return objectUrl;
625
+ } catch (e) {
626
+ setError(e instanceof Error ? e : new Error(String(e)));
627
+ return null;
628
+ }
629
+ };
630
+ const remove = async (path) => {
631
+ setError(null);
632
+ try {
633
+ await db.bucket(bucketName).delete(path);
634
+ } catch (e) {
635
+ setError(e instanceof Error ? e : new Error(String(e)));
636
+ }
637
+ };
638
+ const exists = async (path) => {
639
+ setError(null);
640
+ try {
641
+ return await db.bucket(bucketName).exists(path);
642
+ } catch (e) {
643
+ setError(e instanceof Error ? e : new Error(String(e)));
644
+ return false;
645
+ }
646
+ };
647
+ return {
648
+ isUploading,
649
+ error,
650
+ clearError,
651
+ upload,
652
+ download,
653
+ remove,
654
+ exists
655
+ };
656
+ }
657
+
658
+ //#endregion
659
+ //#region src/lib/use-download-file.ts
660
+ function useDownloadFile(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeOptions) {
661
+ let db;
662
+ let bucketName;
663
+ let path;
664
+ let options;
665
+ if (typeof dbOrBucketName === "string") {
666
+ db = useDb();
667
+ bucketName = dbOrBucketName;
668
+ path = bucketNameOrPath;
669
+ options = pathOrOptions ?? {};
670
+ } else {
671
+ db = dbOrBucketName;
672
+ bucketName = bucketNameOrPath;
673
+ path = pathOrOptions;
674
+ options = maybeOptions ?? {};
675
+ }
676
+ const useCache = options.cache !== false;
677
+ const [url, setUrl] = createSignal(null, { ownedWrite: true });
678
+ const [isLoading, setIsLoading] = createSignal(false, { ownedWrite: true });
679
+ const [error, setError] = createSignal(null, { ownedWrite: true });
680
+ let lease = null;
681
+ let privateUrl = null;
682
+ const [refetchSignal, setRefetchSignal] = createSignal(0);
683
+ /** Consumed by the next effect run, so `refetch()` bypasses every layer once. */
684
+ let reloadOnce = false;
685
+ function releaseCurrent() {
686
+ lease?.release();
687
+ lease = null;
688
+ if (privateUrl) {
689
+ URL.revokeObjectURL(privateUrl);
690
+ privateUrl = null;
691
+ }
692
+ }
693
+ createEffect(() => {
694
+ refetchSignal();
695
+ return path();
696
+ }, (filePath) => {
697
+ releaseCurrent();
698
+ if (!filePath) {
699
+ setUrl(null);
700
+ setIsLoading(false);
701
+ setError(null);
702
+ return;
703
+ }
704
+ const reload = reloadOnce;
705
+ reloadOnce = false;
706
+ let cancelled = false;
707
+ setIsLoading(true);
708
+ setError(null);
709
+ const bucket = db.bucket(bucketName);
710
+ (useCache ? bucket.url(filePath, {
711
+ persist: options.persist !== false,
712
+ pin: options.pin,
713
+ revalidate: options.revalidate,
714
+ reload
715
+ }).then((acquired) => {
716
+ if (!acquired) return null;
717
+ if (cancelled) {
718
+ acquired.release();
719
+ return null;
720
+ }
721
+ lease = acquired;
722
+ return acquired.url;
723
+ }) : bucket.read(filePath, {
724
+ persist: false,
725
+ reload: true
726
+ }).then((blob) => {
727
+ if (!blob || cancelled) return null;
728
+ privateUrl = URL.createObjectURL(blob);
729
+ return privateUrl;
730
+ })).then((result) => {
731
+ if (!cancelled) {
732
+ setUrl(result);
733
+ setIsLoading(false);
734
+ }
735
+ }, (err) => {
736
+ if (!cancelled) {
737
+ setError(err instanceof Error ? err : new Error(String(err)));
738
+ setIsLoading(false);
739
+ }
740
+ });
741
+ return () => {
742
+ cancelled = true;
743
+ };
744
+ });
745
+ onCleanup(() => {
746
+ releaseCurrent();
747
+ });
748
+ const refetch = () => {
749
+ reloadOnce = true;
750
+ setRefetchSignal((n) => n + 1);
751
+ };
752
+ return {
753
+ url,
754
+ isLoading,
755
+ error,
756
+ refetch
757
+ };
758
+ }
759
+
760
+ //#endregion
761
+ //#region src/lib/use-blurhash.ts
762
+ function useBlurhash(dbOrBucketName, bucketNameOrPath, maybePath) {
763
+ let db;
764
+ let bucketName;
765
+ let path;
766
+ if (typeof dbOrBucketName === "string") {
767
+ db = useDb();
768
+ bucketName = dbOrBucketName;
769
+ path = bucketNameOrPath;
770
+ } else {
771
+ db = dbOrBucketName;
772
+ bucketName = bucketNameOrPath;
773
+ path = maybePath;
774
+ }
775
+ const [hash, setHash] = createSignal(null, { ownedWrite: true });
776
+ const [isLoading, setIsLoading] = createSignal(false, { ownedWrite: true });
777
+ createEffect(() => path(), (filePath) => {
778
+ if (!filePath) {
779
+ setHash(null);
780
+ setIsLoading(false);
781
+ return;
782
+ }
783
+ let cancelled = false;
784
+ setIsLoading(true);
785
+ db.bucket(bucketName).blurhash(filePath).then((result) => {
786
+ if (cancelled) return;
787
+ setHash(result);
788
+ setIsLoading(false);
789
+ }).catch(() => {
790
+ if (cancelled) return;
791
+ setHash(null);
792
+ setIsLoading(false);
793
+ });
794
+ return () => {
795
+ cancelled = true;
796
+ };
797
+ });
798
+ return {
799
+ hash,
800
+ isLoading
801
+ };
802
+ }
803
+
804
+ //#endregion
805
+ //#region src/lib/use-bucket-image.ts
806
+ function useBucketImage(dbOrBucketName, bucketNameOrPath, pathOrOptions, maybeOptions) {
807
+ let db;
808
+ let bucketName;
809
+ let path;
810
+ let options;
811
+ if (typeof dbOrBucketName === "string") {
812
+ db = useDb();
813
+ bucketName = dbOrBucketName;
814
+ path = bucketNameOrPath;
815
+ options = pathOrOptions ?? {};
816
+ } else {
817
+ db = dbOrBucketName;
818
+ bucketName = bucketNameOrPath;
819
+ path = pathOrOptions;
820
+ options = maybeOptions ?? {};
821
+ }
822
+ const wantHash = options.blurhash !== false;
823
+ const { hash } = useBlurhash(db, bucketName, () => wantHash ? path() : null);
824
+ const file = useDownloadFile(db, bucketName, path, options);
825
+ const [ready, setReady] = createSignal(false, { ownedWrite: true });
826
+ createEffect(file.url, () => {
827
+ setReady(false);
828
+ }, { defer: true });
829
+ const gate = (img) => {
830
+ const done = () => setReady(true);
831
+ if (typeof img.decode === "function") img.decode().then(done, done);
832
+ else if (img.complete) done();
833
+ else {
834
+ img.onload = done;
835
+ img.onerror = done;
836
+ }
837
+ };
838
+ return {
839
+ ...file,
840
+ blurhash: hash,
841
+ ready,
842
+ gate
843
+ };
844
+ }
845
+
846
+ //#endregion
847
+ //#region src/lib/Blurhash.ts
848
+ /**
849
+ * A blurhash painted onto a canvas, once per hash change. Size the canvas via
850
+ * `class`/`style` (e.g. `absolute inset-0 w-full h-full`); the internal decode
851
+ * resolution stays tiny regardless of the displayed size.
852
+ */
853
+ function Blurhash(props) {
854
+ if (typeof document === "undefined") return null;
855
+ const canvas = document.createElement("canvas");
856
+ createEffect(() => props.class ?? "", (className) => {
857
+ canvas.className = className;
858
+ });
859
+ createEffect(() => props.style ?? "", (style) => {
860
+ canvas.style.cssText = style;
861
+ });
862
+ createEffect(() => ({
863
+ width: props.width ?? 32,
864
+ height: props.height ?? 32,
865
+ hash: props.hash,
866
+ punch: props.punch ?? 1
867
+ }), ({ width, height, hash, punch }) => {
868
+ canvas.width = width;
869
+ canvas.height = height;
870
+ if (!hash) return;
871
+ try {
872
+ const pixels = decodeBlurhash(hash, width, height, punch);
873
+ const ctx = canvas.getContext("2d");
874
+ if (!ctx) return;
875
+ const imageData = ctx.createImageData(width, height);
876
+ imageData.data.set(pixels);
877
+ ctx.putImageData(imageData, 0, 0);
878
+ } catch {}
879
+ });
880
+ return canvas;
881
+ }
882
+
883
+ //#endregion
884
+ //#region src/lib/BucketImage.ts
885
+ const LAYER_STYLE = "position:absolute;inset:0;width:100%;height:100%;";
886
+ /**
887
+ * A bucket image that never pops in: it layers (bottom to top) your `fallback`
888
+ * plate, the automatically stored blurhash, and the real image, which stays
889
+ * transparent until the bitmap is DECODED and then crossfades over the
890
+ * placeholders. Placeholder layers unmount once the fade settles. Respects
891
+ * prefers-reduced-motion (instant swap). The container is made
892
+ * `position: relative` unless your `class` positions it already.
893
+ *
894
+ * ```tsx
895
+ * <BucketImage bucket="covers" path={row.cover_key} class="absolute inset-0"
896
+ * fallback={<MyPlate />} alt="" />
897
+ * ```
898
+ */
899
+ function BucketImage(props) {
900
+ if (typeof document === "undefined") return null;
901
+ const image = useBucketImage(props.bucket, () => props.path, {
902
+ ...props.options,
903
+ blurhash: props.blurhash !== false
904
+ });
905
+ const reducedMotion = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
906
+ const root = document.createElement("div");
907
+ createEffect(() => props.class ?? "", (className) => {
908
+ root.className = className;
909
+ });
910
+ onSettled(() => {
911
+ if (getComputedStyle(root).position === "static") root.style.position = "relative";
912
+ });
913
+ const placeholder = document.createElement("div");
914
+ placeholder.style.cssText = LAYER_STYLE;
915
+ const fallbackHolder = document.createElement("div");
916
+ fallbackHolder.style.cssText = LAYER_STYLE;
917
+ placeholder.append(fallbackHolder);
918
+ const resolvedFallback = children(() => props.fallback);
919
+ createEffect(() => resolvedFallback.toArray().filter((node) => node instanceof Node), (nodes) => {
920
+ fallbackHolder.replaceChildren(...nodes);
921
+ });
922
+ const hashCanvas = Blurhash({
923
+ get hash() {
924
+ return image.blurhash();
925
+ },
926
+ style: LAYER_STYLE
927
+ });
928
+ if (hashCanvas instanceof Node) placeholder.append(hashCanvas);
929
+ const img = document.createElement("img");
930
+ img.decoding = "async";
931
+ img.style.cssText = `${LAYER_STYLE}opacity:0;`;
932
+ createEffect(() => props.imgClass ?? "", (className) => {
933
+ img.className = className;
934
+ });
935
+ createEffect(() => props.fit ?? "cover", (fit) => {
936
+ img.style.objectFit = fit;
937
+ });
938
+ createEffect(() => props.alt ?? "", (alt) => {
939
+ img.alt = alt;
940
+ });
941
+ createEffect(() => reducedMotion ? "none" : `opacity ${props.transition ?? 300}ms ${props.easing ?? "cubic-bezier(0.16, 1, 0.3, 1)"}`, (transition) => {
942
+ img.style.transition = transition;
943
+ });
944
+ createEffect(() => image.url(), (url) => {
945
+ if (!url) {
946
+ img.removeAttribute("src");
947
+ return;
948
+ }
949
+ img.src = url;
950
+ image.gate(img);
951
+ });
952
+ createEffect(() => image.ready(), (ready) => {
953
+ img.style.opacity = ready ? "1" : "0";
954
+ });
955
+ const [settled, setSettled] = createSignal(false, { ownedWrite: true });
956
+ createEffect(() => ({
957
+ ready: image.ready(),
958
+ transition: props.transition ?? 300
959
+ }), ({ ready, transition }) => {
960
+ if (!ready) {
961
+ setSettled(false);
962
+ return;
963
+ }
964
+ const wait = (reducedMotion ? 0 : transition) + 120;
965
+ const timer = setTimeout(() => setSettled(true), wait);
966
+ return () => clearTimeout(timer);
967
+ });
968
+ createEffect(() => settled(), (isSettled) => {
969
+ if (isSettled) placeholder.remove();
970
+ else if (!placeholder.isConnected) root.insertBefore(placeholder, img);
971
+ });
972
+ root.append(placeholder, img);
973
+ return root;
974
+ }
975
+
976
+ //#endregion
977
+ //#region src/lib/Sp00kyProvider.ts
978
+ function Sp00kyProvider(props) {
979
+ const merged = merge({ fallback: void 0 }, props);
980
+ const [db, setDb] = createSignal(void 0, { ownedWrite: true });
981
+ let disposed = false;
982
+ onCleanup(() => {
983
+ disposed = true;
984
+ });
985
+ onSettled(() => {
986
+ (async () => {
987
+ try {
988
+ const instance = new SyncedDb(merged.config);
989
+ await instance.init();
990
+ if (disposed) {
991
+ await instance.close();
992
+ return;
993
+ }
994
+ if (merged.preload) try {
995
+ await merged.preload(instance);
996
+ } catch (e) {
997
+ console.error("Sp00kyProvider: preload failed; revealing UI anyway", e);
998
+ }
999
+ setDb(() => instance);
1000
+ merged.onReady?.(instance);
1001
+ } catch (e) {
1002
+ const error = e instanceof Error ? e : new Error(String(e));
1003
+ if (merged.onError) merged.onError(error);
1004
+ else console.error("Sp00kyProvider: Failed to initialize database", error);
1005
+ }
1006
+ })();
1007
+ });
1008
+ return createMemo(() => {
1009
+ const instance = db();
1010
+ if (!instance) return merged.fallback;
1011
+ return createComponent(Sp00kyContext, {
1012
+ value: instance,
1013
+ get children() {
1014
+ return merged.children;
1015
+ }
1016
+ });
1017
+ });
1018
+ }
1019
+
1020
+ //#endregion
1021
+ //#region src/lib/create-submission.ts
1022
+ /**
1023
+ * Thin submission-state wrapper for mutations — button spinner/disable state
1024
+ * around `db.create/update/delete/run` calls.
1025
+ *
1026
+ * Deliberately NOT built on Solid 2's `action()`/`createOptimisticStore`: the
1027
+ * spooky engine is already optimistic local-first (writes commit to the local
1028
+ * DB and re-render through live queries before sync; `run()` is an outbox
1029
+ * CREATE), so a transaction/revert layer on top buys nothing and `action()`'s
1030
+ * await-vs-yield transaction escape is a real footgun. Errors here mean the
1031
+ * LOCAL commit failed — sync/push failures surface through `useSyncStatus`
1032
+ * and `usePendingMutations` instead.
1033
+ */
1034
+ function createSubmission(fn) {
1035
+ const [inFlight, setInFlight] = createSignal(0, { ownedWrite: true });
1036
+ const [error, setError] = createSignal(void 0, { ownedWrite: true });
1037
+ const [result, setResult] = createSignal(void 0, { ownedWrite: true });
1038
+ const submit = async (...args) => {
1039
+ setError(void 0);
1040
+ setInFlight((n) => n + 1);
1041
+ try {
1042
+ const r = await fn(...args);
1043
+ setResult(() => r);
1044
+ return r;
1045
+ } catch (e) {
1046
+ setError(e instanceof Error ? e : new Error(String(e)));
1047
+ return;
1048
+ } finally {
1049
+ setInFlight((n) => n - 1);
1050
+ }
1051
+ };
1052
+ return {
1053
+ submit,
1054
+ pending: () => inFlight() > 0,
1055
+ error,
1056
+ result,
1057
+ clearError: () => setError(void 0)
1058
+ };
1059
+ }
1060
+
1061
+ //#endregion
1062
+ //#region src/index.ts
1063
+ /**
1064
+ * SyncedDb - A thin wrapper around sp00ky-ts for Solid.js integration.
1065
+ * Delegates all logic to the underlying sp00ky-ts instance.
1066
+ *
1067
+ * NOTE: keep in sync with packages/client-solid/src/index.ts (SyncedDb).
1068
+ * Copied rather than shared so this package's dependency graph never pulls
1069
+ * in solid-js 1.x; fold the two together once client-solid moves to Solid 2.
1070
+ * Solid-2-only differences: `delete` accepts 'bound RecordId', and write
1071
+ * payloads go through `snapshot()` (see `unproxy` below).
1072
+ */
1073
+ /**
1074
+ * Solid 2 stores wrap every object read out of them (query rows, their nested
1075
+ * arrays, `createStore` docs) in a Proxy. Those proxies cannot cross
1076
+ * `postMessage` (the sqlite and shared-tabs workers): structuredClone throws
1077
+ * DataCloneError. `snapshot()` returns the underlying plain value for store
1078
+ * proxies and passes anything else through untouched.
1079
+ */
1080
+ function unproxy(value) {
1081
+ if (value === null || typeof value !== "object") return value;
1082
+ return snapshot(value);
1083
+ }
1084
+ var SyncedDb = class {
1085
+ constructor(config) {
1086
+ this.sp00ky = null;
1087
+ this._initialized = false;
1088
+ this.config = config;
1089
+ }
1090
+ getSp00ky() {
1091
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1092
+ return this.sp00ky;
1093
+ }
1094
+ /**
1095
+ * Initialize the sp00ky-ts instance
1096
+ */
1097
+ async init() {
1098
+ if (this._initialized) return;
1099
+ this.sp00ky = new Sp00kyClient(this.config);
1100
+ await this.sp00ky.init();
1101
+ this._initialized = true;
1102
+ }
1103
+ /**
1104
+ * Tear down the client: leaves the tabs broker, closes the local store and
1105
+ * remote socket, and frees the wasm circuit. Without this a remounted provider
1106
+ * (or an HMR reload) strands a whole client, and the abandoned wasm heaps stay
1107
+ * resident because V8 cannot see how much wasm memory a dropped wrapper holds.
1108
+ */
1109
+ async close() {
1110
+ const instance = this.sp00ky;
1111
+ this.sp00ky = null;
1112
+ this._initialized = false;
1113
+ if (instance) await instance.close();
1114
+ }
1115
+ /**
1116
+ * Create a new record in the database
1117
+ */
1118
+ async create(id, payload) {
1119
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1120
+ await this.sp00ky.create(id, unproxy(payload));
1121
+ }
1122
+ /**
1123
+ * Update an existing record in the database
1124
+ */
1125
+ async update(tableName, recordId, payload, options) {
1126
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1127
+ await this.sp00ky.update(tableName, recordId, unproxy(payload), options);
1128
+ }
1129
+ /**
1130
+ * Delete an existing record in the database
1131
+ */
1132
+ async delete(tableName, selector) {
1133
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1134
+ const raw = unproxy(selector);
1135
+ const ctorName = raw?.constructor?.name;
1136
+ const isRecordId = raw instanceof RecordId || ctorName === "RecordId" || ctorName === "bound RecordId";
1137
+ let id;
1138
+ if (typeof raw === "string") id = raw;
1139
+ else if (isRecordId) id = `${tableName}:${raw.id}`;
1140
+ else throw new Error("Only string ID or RecordId selectors are supported currently with core");
1141
+ await this.sp00ky.delete(tableName, id);
1142
+ }
1143
+ /**
1144
+ * Preload/prewarm a built query into the local cache without registering a
1145
+ * live view. Fetches once and stores the rows (+ embedded related children)
1146
+ * locally so a later `createQuery` for the same data paints instantly. Best-effort.
1147
+ */
1148
+ async preload(finalQuery, options) {
1149
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1150
+ await this.sp00ky.preload(finalQuery, options);
1151
+ }
1152
+ /**
1153
+ * Query data from the database
1154
+ */
1155
+ query(table) {
1156
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1157
+ return this.sp00ky.query(table, {});
1158
+ }
1159
+ /**
1160
+ * Run a backend operation
1161
+ */
1162
+ async run(backend, path, payload, options) {
1163
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1164
+ await this.sp00ky.run(backend, path, unproxy(payload), options);
1165
+ }
1166
+ /**
1167
+ * Sign out, clear session and local storage
1168
+ */
1169
+ async signOut() {
1170
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1171
+ await this.sp00ky.auth.signOut();
1172
+ }
1173
+ /**
1174
+ * Execute a function with direct access to the remote database connection
1175
+ */
1176
+ async useRemote(fn) {
1177
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1178
+ return await this.sp00ky.useRemote(fn);
1179
+ }
1180
+ /**
1181
+ * Access the remote database service directly
1182
+ */
1183
+ get remote() {
1184
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1185
+ return this.sp00ky.remoteClient;
1186
+ }
1187
+ /**
1188
+ * Access the local database service directly
1189
+ */
1190
+ get local() {
1191
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1192
+ return this.sp00ky.localClient;
1193
+ }
1194
+ /**
1195
+ * Access the auth service
1196
+ */
1197
+ get auth() {
1198
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1199
+ return this.sp00ky.auth;
1200
+ }
1201
+ get pendingMutationCount() {
1202
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1203
+ return this.sp00ky.pendingMutationCount;
1204
+ }
1205
+ /** Diagnostic — see `Sp00kyClient.liveRetryCount`. */
1206
+ get liveRetryCount() {
1207
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1208
+ return this.sp00ky.liveRetryCount;
1209
+ }
1210
+ subscribeToPendingMutations(cb) {
1211
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1212
+ return this.sp00ky.subscribeToPendingMutations(cb);
1213
+ }
1214
+ /** Queries mid-fetch right now. See {@link useSyncActivity}. */
1215
+ get fetchingQueryCount() {
1216
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1217
+ return this.sp00ky.fetchingQueryCount;
1218
+ }
1219
+ /**
1220
+ * Observe how many queries are fetching from the server. Fires immediately
1221
+ * and on every change. Prefer the `useSyncActivity` hook in components.
1222
+ */
1223
+ subscribeToFetchActivity(cb) {
1224
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1225
+ return this.sp00ky.subscribeToFetchActivity(cb);
1226
+ }
1227
+ /** Current sync-health snapshot. See {@link useSyncStatus}. */
1228
+ get syncHealth() {
1229
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1230
+ return this.sp00ky.syncHealth;
1231
+ }
1232
+ /**
1233
+ * Observe sync health. Fires immediately with the current status and again
1234
+ * on every healthy↔degraded transition. Prefer the `useSyncStatus` hook in
1235
+ * components; this is the imperative escape hatch.
1236
+ */
1237
+ subscribeToSyncHealth(cb) {
1238
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1239
+ return this.sp00ky.subscribeToSyncHealth(cb);
1240
+ }
1241
+ /** Current local-store durability snapshot. See {@link useStorageStatus}. */
1242
+ get storageHealth() {
1243
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1244
+ return this.sp00ky.storageHealth;
1245
+ }
1246
+ /**
1247
+ * Observe local-store durability. Fires immediately with the current snapshot
1248
+ * and again on change. Prefer the `useStorageStatus` hook in components; this
1249
+ * is the imperative escape hatch.
1250
+ */
1251
+ subscribeToStorageHealth(cb) {
1252
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1253
+ return this.sp00ky.subscribeToStorageHealth(cb);
1254
+ }
1255
+ bucket(name) {
1256
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
1257
+ return this.sp00ky.bucket(name);
1258
+ }
1259
+ getBucketConfig(name) {
1260
+ return this.config.schema.buckets?.find((b) => b.name === name);
1261
+ }
1262
+ };
1263
+
1264
+ //#endregion
1265
+ export { Blurhash, BucketImage, RecordId, Sp00kyProvider, SyncedDb, Uuid, conflate, createPreload, createQuery, createSubmission, fromSubscription, useAppRelease, useBlurhash, useBucketImage, useCrdtField, useDb, useDownloadFile, useFeatureFlag, useFileUpload, usePendingMutations, useQuery, useStorageStatus, useSyncActivity, useSyncStatus };
1266
+ //# sourceMappingURL=index.js.map