@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.
@@ -1,10 +1,31 @@
1
1
  import { createSignal, createEffect, onCleanup, type Accessor } from 'solid-js';
2
2
  import type { SchemaStructure, BucketNames } from '@spooky-sync/query-builder';
3
+ import type { BlobUrlLease } from '@spooky-sync/core';
3
4
  import type { SyncedDb } from '../index';
4
5
  import { useDb } from './context';
5
6
 
6
7
  export interface UseDownloadFileOptions {
8
+ /**
9
+ * Master switch, default `true`. `false` gives every hook instance its own
10
+ * private object URL fetched fresh from the bucket and revoked on unmount —
11
+ * no sharing, no persistence, no reuse.
12
+ */
7
13
  cache?: boolean;
14
+ /**
15
+ * Keep the bytes in OPFS so they survive a reload and are available offline.
16
+ * Default `true`. Turn off for one-shot or sensitive files; the in-tab object
17
+ * URL is still shared between components rendering the same path.
18
+ */
19
+ persist?: boolean;
20
+ /** Exempt this file from pressure eviction. Pinned bytes never expire. */
21
+ pin?: boolean;
22
+ /**
23
+ * `'never'` (default) treats a bucket path as immutable, which is how paths
24
+ * are written (`crypto.randomUUID() + ext`). `'head'` spends a remote `head()`
25
+ * to compare sizes before trusting the cached copy — for paths the app
26
+ * overwrites in place.
27
+ */
28
+ revalidate?: 'never' | 'head';
8
29
  }
9
30
 
10
31
  export interface UseDownloadFileResult {
@@ -14,28 +35,6 @@ export interface UseDownloadFileResult {
14
35
  refetch: () => void;
15
36
  }
16
37
 
17
- interface CacheEntry {
18
- url: string;
19
- refCount: number;
20
- }
21
-
22
- const downloadCache = new Map<string, CacheEntry>();
23
- const inflightRequests = new Map<string, Promise<string | null>>();
24
-
25
- function cacheKey(bucket: string, path: string): string {
26
- return `${bucket}:${path}`;
27
- }
28
-
29
- function releaseEntry(key: string): void {
30
- const entry = downloadCache.get(key);
31
- if (!entry) return;
32
- entry.refCount--;
33
- if (entry.refCount <= 0) {
34
- URL.revokeObjectURL(entry.url);
35
- downloadCache.delete(key);
36
- }
37
- }
38
-
39
38
  export function useDownloadFile<S extends SchemaStructure>(
40
39
  bucketName: BucketNames<S>,
41
40
  path: Accessor<string | null | undefined>,
@@ -76,68 +75,19 @@ export function useDownloadFile<S extends SchemaStructure>(
76
75
  const [isLoading, setIsLoading] = createSignal(false);
77
76
  const [error, setError] = createSignal<Error | null>(null);
78
77
 
79
- let currentKey: string | null = null;
78
+ // Exactly one of these is held at a time: a refcounted lease on the shared
79
+ // cache entry, or a private URL this instance minted and must revoke itself.
80
+ let lease: BlobUrlLease | null = null;
80
81
  let privateUrl: string | null = null;
82
+
81
83
  const [refetchSignal, setRefetchSignal] = createSignal(0);
82
- const refetchTrigger = () => setRefetchSignal((n) => n + 1);
83
-
84
- async function doDownload(key: string, filePath: string): Promise<string | null> {
85
- if (useCache) {
86
- // Check cache
87
- const cached = downloadCache.get(key);
88
- if (cached) {
89
- cached.refCount++;
90
- currentKey = key;
91
- return cached.url;
92
- }
93
-
94
- // Check inflight
95
- const inflight = inflightRequests.get(key);
96
- if (inflight) {
97
- const result = await inflight;
98
- if (result) {
99
- const entry = downloadCache.get(key);
100
- if (entry) {
101
- entry.refCount++;
102
- currentKey = key;
103
- }
104
- }
105
- return result;
106
- }
107
-
108
- // Start new download
109
- const promise = (async () => {
110
- const content = await db.bucket(bucketName).get(filePath);
111
- if (!content) return null;
112
- const objectUrl = URL.createObjectURL(new Blob([content as BlobPart]));
113
- downloadCache.set(key, { url: objectUrl, refCount: 1 });
114
- return objectUrl;
115
- })();
116
-
117
- inflightRequests.set(key, promise);
118
- try {
119
- const result = await promise;
120
- currentKey = key;
121
- return result;
122
- } finally {
123
- inflightRequests.delete(key);
124
- }
125
- } else {
126
- // No caching — private URL per instance
127
- const content = await db.bucket(bucketName).get(filePath);
128
- if (!content) return null;
129
- const objectUrl = URL.createObjectURL(new Blob([content as BlobPart]));
130
- privateUrl = objectUrl;
131
- return objectUrl;
132
- }
133
- }
84
+ /** Consumed by the next effect run, so `refetch()` bypasses every layer once. */
85
+ let reloadOnce = false;
134
86
 
135
- function releaseCurrentEntry() {
136
- if (useCache && currentKey) {
137
- releaseEntry(currentKey);
138
- currentKey = null;
139
- }
140
- if (!useCache && privateUrl) {
87
+ function releaseCurrent() {
88
+ lease?.release();
89
+ lease = null;
90
+ if (privateUrl) {
141
91
  URL.revokeObjectURL(privateUrl);
142
92
  privateUrl = null;
143
93
  }
@@ -148,8 +98,7 @@ export function useDownloadFile<S extends SchemaStructure>(
148
98
  // Subscribe to refetch signal so effect re-runs
149
99
  refetchSignal();
150
100
 
151
- // Release previous entry
152
- releaseCurrentEntry();
101
+ releaseCurrent();
153
102
 
154
103
  if (!filePath) {
155
104
  setUrl(null);
@@ -158,26 +107,41 @@ export function useDownloadFile<S extends SchemaStructure>(
158
107
  return;
159
108
  }
160
109
 
161
- const key = cacheKey(bucketName as string, filePath);
162
-
163
- // Synchronous cache hit
164
- if (useCache) {
165
- const cached = downloadCache.get(key);
166
- if (cached) {
167
- cached.refCount++;
168
- currentKey = key;
169
- setUrl(cached.url);
170
- setIsLoading(false);
171
- setError(null);
172
- return;
173
- }
174
- }
110
+ const reload = reloadOnce;
111
+ reloadOnce = false;
175
112
 
176
113
  let cancelled = false;
177
114
  setIsLoading(true);
178
115
  setError(null);
179
116
 
180
- doDownload(key, filePath).then(
117
+ const bucket = db.bucket(bucketName);
118
+ const resolve = useCache
119
+ ? bucket
120
+ .url(filePath, {
121
+ persist: options.persist !== false,
122
+ pin: options.pin,
123
+ revalidate: options.revalidate,
124
+ reload,
125
+ })
126
+ .then((acquired) => {
127
+ if (!acquired) return null;
128
+ if (cancelled) {
129
+ // Unmounted or the path changed mid-flight — hand the reference
130
+ // straight back, or the entry never drops to zero and its object
131
+ // URL leaks for the life of the tab.
132
+ acquired.release();
133
+ return null;
134
+ }
135
+ lease = acquired;
136
+ return acquired.url;
137
+ })
138
+ : bucket.read(filePath, { persist: false, reload: true }).then((blob) => {
139
+ if (!blob || cancelled) return null;
140
+ privateUrl = URL.createObjectURL(blob);
141
+ return privateUrl;
142
+ });
143
+
144
+ resolve.then(
181
145
  (result) => {
182
146
  if (!cancelled) {
183
147
  setUrl(result);
@@ -199,20 +163,12 @@ export function useDownloadFile<S extends SchemaStructure>(
199
163
  });
200
164
 
201
165
  onCleanup(() => {
202
- releaseCurrentEntry();
166
+ releaseCurrent();
203
167
  });
204
168
 
205
169
  const refetch = () => {
206
- // Evict current entry from cache before re-triggering
207
- if (useCache && currentKey) {
208
- const entry = downloadCache.get(currentKey);
209
- if (entry) {
210
- URL.revokeObjectURL(entry.url);
211
- downloadCache.delete(currentKey);
212
- }
213
- currentKey = null;
214
- }
215
- refetchTrigger();
170
+ reloadOnce = true;
171
+ setRefetchSignal((n) => n + 1);
216
172
  };
217
173
 
218
174
  return { url, isLoading, error, refetch };
@@ -1,6 +1,7 @@
1
1
  import { createSignal, onCleanup } from 'solid-js';
2
2
  import type { SchemaStructure, BucketNames } from '@spooky-sync/query-builder';
3
3
  import { fileToUint8Array } from '@spooky-sync/core';
4
+ import type { BucketPutOptions, BucketPutResult } from '@spooky-sync/core';
4
5
  import type { SyncedDb } from '../index';
5
6
  import { useDb } from './context';
6
7
 
@@ -8,7 +9,7 @@ export interface FileUploadResult {
8
9
  isUploading: () => boolean;
9
10
  error: () => Error | null;
10
11
  clearError: () => void;
11
- upload: (path: string, file: File | Blob) => Promise<void>;
12
+ upload: (path: string, file: File | Blob, options?: BucketPutOptions) => Promise<BucketPutResult | void>;
12
13
  download: (path: string) => Promise<string | null>;
13
14
  remove: (path: string) => Promise<void>;
14
15
  exists: (path: string) => Promise<boolean>;
@@ -71,7 +72,11 @@ export function useFileUpload<S extends SchemaStructure>(
71
72
  }
72
73
  };
73
74
 
74
- const upload = async (path: string, file: File | Blob): Promise<void> => {
75
+ const upload = async (
76
+ path: string,
77
+ file: File | Blob,
78
+ options?: BucketPutOptions
79
+ ): Promise<BucketPutResult | void> => {
75
80
  setError(null);
76
81
  try {
77
82
  validate(file);
@@ -83,7 +88,7 @@ export function useFileUpload<S extends SchemaStructure>(
83
88
  setIsUploading(true);
84
89
  try {
85
90
  const bytes = await fileToUint8Array(file);
86
- await db.bucket(bucketName).put(path, bytes);
91
+ return await db.bucket(bucketName).put(path, bytes, options);
87
92
  } catch (e) {
88
93
  setError(e instanceof Error ? e : new Error(String(e)));
89
94
  } finally {
@@ -0,0 +1,44 @@
1
+ import { createEffect, createSignal, onCleanup, type Accessor } from 'solid-js';
2
+ import { useDb } from './context';
3
+ import type { ImpersonationInfo } from '@spooky-sync/core';
4
+
5
+ export interface UseImpersonationOptions {
6
+ /**
7
+ * This component renders the app's own impersonation banner. Required with
8
+ * `impersonationBanner: { mode: 'custom' }`: it acknowledges the banner, so
9
+ * the client does not fall back to its built-in one.
10
+ */
11
+ rendersBanner?: boolean;
12
+ }
13
+
14
+ export interface UseImpersonation {
15
+ /** The active impersonation, or `null`. */
16
+ impersonation: Accessor<ImpersonationInfo | null>;
17
+ isImpersonating: Accessor<boolean>;
18
+ /** Return to the admin session. */
19
+ stop: () => Promise<void>;
20
+ }
21
+
22
+ /**
23
+ * Observe admin impersonation (started from the DevTools). The client already
24
+ * shows its own warning bar with a Stop button; use this for anything extra,
25
+ * such as hiding actions an admin should not take on someone's behalf.
26
+ * Must be used within a `<Sp00kyProvider>`.
27
+ */
28
+ export function useImpersonation(options: UseImpersonationOptions = {}): UseImpersonation {
29
+ const db = useDb();
30
+ const [impersonation, setImpersonation] = createSignal<ImpersonationInfo | null>(
31
+ db.auth.impersonation
32
+ );
33
+ onCleanup(db.auth.subscribeImpersonation(setImpersonation));
34
+ // Re-acknowledged per session: a new impersonation restarts the client's
35
+ // fallback timer, and this component is what cancels it.
36
+ createEffect(() => {
37
+ if (options.rendersBanner && impersonation()) db.acknowledgeImpersonationBanner();
38
+ });
39
+ return {
40
+ impersonation,
41
+ isImpersonating: () => impersonation() !== null,
42
+ stop: () => db.auth.stopImpersonating(),
43
+ };
44
+ }
@@ -52,6 +52,7 @@ export function useQuery<
52
52
  error: () => Error | undefined;
53
53
  isLoading: () => boolean;
54
54
  isFetching: () => boolean;
55
+ isSettled: () => boolean;
55
56
  };
56
57
 
57
58
  // Overload: explicit db (backward-compatible)
@@ -71,6 +72,7 @@ export function useQuery<
71
72
  error: () => Error | undefined;
72
73
  isLoading: () => boolean;
73
74
  isFetching: () => boolean;
75
+ isSettled: () => boolean;
74
76
  };
75
77
 
76
78
  // Implementation
@@ -157,9 +159,31 @@ export function useQuery<
157
159
 
158
160
  const sp00ky = db.getSp00ky();
159
161
 
162
+ /**
163
+ * Registration can fail — the canonical case is the SSP answering 503
164
+ * NOT_READY while it bootstraps. Nothing here used to catch that: the
165
+ * rejection escaped as an unhandled promise, `isFetched` stayed false, and
166
+ * `isLoading()` therefore stayed true FOREVER, which is what a spinner that
167
+ * never resolves actually was. Surface it as `error()` instead; the sync
168
+ * scheduler retries the registration underneath, so a transient failure
169
+ * still recovers on its own.
170
+ */
160
171
  const initQuery = async (
161
172
  query: FinalQuery<S, TableName, T, RelatedFields, IsOne, Sp00kyQueryResultPromise>,
162
173
  myRun: number
174
+ ) => {
175
+ try {
176
+ await subscribeQuery(query, myRun);
177
+ } catch (err) {
178
+ // A superseded run's failure is not this subscription's problem.
179
+ if (myRun !== runId) return;
180
+ setError(err instanceof Error ? err : new Error(String(err)));
181
+ }
182
+ };
183
+
184
+ const subscribeQuery = async (
185
+ query: FinalQuery<S, TableName, T, RelatedFields, IsOne, Sp00kyQueryResultPromise>,
186
+ myRun: number
163
187
  ) => {
164
188
  const { hash } = await query.run();
165
189
  // A newer query identity (or disposal) won the race while we awaited run().
@@ -193,17 +217,42 @@ export function useQuery<
193
217
  { immediate: true }
194
218
  );
195
219
 
220
+ // A result that is empty and stays empty (a new account's list) produces
221
+ // no second callback above, so `isFetched` also follows the engine: once
222
+ // the rows of a known membership are painted (authority, which the core
223
+ // flips only after it delivered them) and no fetch is in flight, the
224
+ // (possibly empty) result is the answer. Without this the hook sat in
225
+ // `isLoading()` until a reload.
226
+ let known = false;
227
+ let idle = false;
228
+ const settleFromServer = () => {
229
+ if (known && idle && myRun === runId) setIsFetched(true);
230
+ };
231
+
196
232
  // Mirror the query's fetch status so the UI can show a "loading more"
197
233
  // state while the sync engine pulls missing records in the background.
198
234
  const unsubStatus = sp00ky.subscribeQueryStatus(
199
235
  hash,
200
- (status) => setIsFetching(status === 'fetching'),
236
+ (status) => {
237
+ setIsFetching(status === 'fetching');
238
+ idle = status === 'idle';
239
+ settleFromServer();
240
+ },
241
+ { immediate: true }
242
+ );
243
+ const unsubAuthority = sp00ky.subscribeQueryAuthority(
244
+ hash,
245
+ (k) => {
246
+ known = k;
247
+ settleFromServer();
248
+ },
201
249
  { immediate: true }
202
250
  );
203
251
 
204
252
  const teardown = () => {
205
253
  unsub();
206
254
  unsubStatus();
255
+ unsubAuthority();
207
256
  };
208
257
 
209
258
  // Superseded while awaiting subscribe()? Don't leak — tear down immediately.
@@ -243,7 +292,10 @@ export function useQuery<
243
292
  const myRun = ++runId;
244
293
  teardownActive();
245
294
  setIsFetched(false);
246
- initQuery(query, myRun);
295
+ // A new identity starts clean: a previous identity's failure must not keep
296
+ // this one out of its loading state.
297
+ setError(undefined);
298
+ void initQuery(query, myRun);
247
299
  });
248
300
 
249
301
  // Tear down the live subscription when the hook's owner is disposed. Registered
@@ -265,10 +317,21 @@ export function useQuery<
265
317
  return !isFetched() && error() === undefined;
266
318
  };
267
319
 
320
+ // True once the query has delivered a result AND no fetch cycle is in flight
321
+ // (registration + initial sync included — the core holds `fetching` across
322
+ // the whole registration and flushes debounced results before flipping back
323
+ // to idle). While settled, the results are authoritative: a windowed query
324
+ // returning fewer rows than its LIMIT really is the end of the list, so
325
+ // virtualized lists may size themselves to it without the scrollbar jumping
326
+ // when a still-syncing window transiently reports short. Resets to false
327
+ // whenever the query identity changes.
328
+ const isSettled = () => isFetched() && !isFetching();
329
+
268
330
  return {
269
331
  data,
270
332
  error,
271
333
  isLoading,
272
334
  isFetching,
335
+ isSettled,
273
336
  };
274
337
  }
@@ -0,0 +1,44 @@
1
+ import { createSignal, onCleanup, type Accessor } from 'solid-js';
2
+ import { useDb } from './context';
3
+ import type { StorageHealth, StorageHealthStatus } from '@spooky-sync/core';
4
+
5
+ export interface UseStorageStatus {
6
+ /** Full durability snapshot; updates reactively. */
7
+ health: Accessor<StorageHealth>;
8
+ /** `'unknown'` | `'persistent'` | `'memory'`. */
9
+ status: Accessor<StorageHealthStatus>;
10
+ /** `true` when the local store survives a reload. */
11
+ isPersistent: Accessor<boolean>;
12
+ /**
13
+ * `true` only when durable storage was requested and could NOT be opened, so
14
+ * the dataset is sitting in RAM and local writes die on reload. Drive a
15
+ * warning off this, not off `status`: a store configured as in-memory reports
16
+ * `'memory'` too, and that is a choice rather than a problem.
17
+ */
18
+ isMemoryFallback: Accessor<boolean>;
19
+ }
20
+
21
+ /**
22
+ * Observe how durable the LOCAL cache is, for a "no local storage" warning.
23
+ *
24
+ * Under `localEngine: 'sqlite'` with `store: 'indexeddb'` the durable store is
25
+ * the OPFS SAHPool VFS, and only ONE client per bucket can hold it open: a
26
+ * second tab of the same app cannot get it and runs in memory instead (the
27
+ * engine retries first, so a closing tab's lock is usually waited out). Must be
28
+ * used within a `<Sp00kyProvider>`.
29
+ */
30
+ export function useStorageStatus(): UseStorageStatus {
31
+ const db = useDb();
32
+ // subscribeToStorageHealth fires synchronously with the current snapshot, so
33
+ // the signal is correct from the first read; the initial value avoids a flash.
34
+ const [health, setHealth] = createSignal<StorageHealth>(db.storageHealth);
35
+ const unsub = db.subscribeToStorageHealth(setHealth);
36
+ onCleanup(unsub);
37
+
38
+ return {
39
+ health,
40
+ status: () => health().status,
41
+ isPersistent: () => health().status === 'persistent',
42
+ isMemoryFallback: () => health().fallback,
43
+ };
44
+ }
@@ -1,6 +1,6 @@
1
1
  import { createSignal, onCleanup, type Accessor } from 'solid-js';
2
2
  import { useDb } from './context';
3
- import type { SyncHealth, SyncHealthStatus } from '@spooky-sync/core';
3
+ import type { ConnectionState, SyncHealth, SyncHealthStatus } from '@spooky-sync/core';
4
4
 
5
5
  export interface UseSyncStatus {
6
6
  /** Full health snapshot; updates reactively on every transition. */
@@ -10,6 +10,27 @@ export interface UseSyncStatus {
10
10
  isHealthy: Accessor<boolean>;
11
11
  /** `true` once sync has failed for a sustained run — drive a banner off this. */
12
12
  isDegraded: Accessor<boolean>;
13
+ /** `true` once at least one sync round has succeeded this session. */
14
+ everConnected: Accessor<boolean>;
15
+ /**
16
+ * `true` only for a real lost connection: degraded AFTER a first successful
17
+ * sync. Stays `false` during the initial "connecting" phase (degraded but
18
+ * never reached the server yet), so an indicator can show nothing until the
19
+ * app has actually connected once.
20
+ */
21
+ isOffline: Accessor<boolean>;
22
+ /**
23
+ * Transport state of the remote WebSocket. Flips the instant the socket
24
+ * drops, unlike `status`, which only degrades after a sustained run of failed
25
+ * sync rounds — so this is what to drive a "reconnecting…" affordance off.
26
+ */
27
+ connection: Accessor<ConnectionState>;
28
+ /**
29
+ * `true` while the connection is being re-established. Usually still
30
+ * `isHealthy()`: a short reconnect is invisible to sync, and writes made
31
+ * during it are queued locally and pushed once the socket is back.
32
+ */
33
+ isReconnecting: Accessor<boolean>;
13
34
  }
14
35
 
15
36
  /**
@@ -35,5 +56,9 @@ export function useSyncStatus(): UseSyncStatus {
35
56
  status: () => health().status,
36
57
  isHealthy: () => health().status === 'healthy',
37
58
  isDegraded: () => health().status === 'degraded',
59
+ everConnected: () => health().everConnected,
60
+ isOffline: () => health().status === 'degraded' && health().everConnected,
61
+ connection: () => health().connection,
62
+ isReconnecting: () => health().connection === 'reconnecting',
38
63
  };
39
64
  }