@spooky-sync/client-react 0.0.0-stage → 0.0.1-canary.383

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 ADDED
@@ -0,0 +1,1312 @@
1
+ 'use client';
2
+ import { RecordId, RecordId as RecordId$1, Uuid } from "surrealdb";
3
+ import { Sp00kyClient, WebPushError, decodeBlurhash, fileToUint8Array, semverGt } from "@spooky-sync/core";
4
+ import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
5
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
6
+
7
+ //#region src/db.ts
8
+ /**
9
+ * SyncedDb - a thin wrapper around the sp00ky core client for React.
10
+ * Delegates all logic to the underlying `Sp00kyClient` instance.
11
+ *
12
+ * NOTE: keep in sync with packages/client-solid/src/index.ts and
13
+ * packages/client-solid2/src/index.ts (SyncedDb). Copied rather than shared so
14
+ * this package's dependency graph never pulls in solid-js. React rows are plain
15
+ * objects (no store proxies), so unlike the Solid 2 copy nothing is unwrapped
16
+ * before a write.
17
+ */
18
+ var SyncedDb = class {
19
+ constructor(config) {
20
+ this.sp00ky = null;
21
+ this._initialized = false;
22
+ this.config = config;
23
+ }
24
+ getSp00ky() {
25
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
26
+ return this.sp00ky;
27
+ }
28
+ /** Initialize the core client. */
29
+ async init() {
30
+ if (this._initialized) return;
31
+ this.sp00ky = new Sp00kyClient(this.config);
32
+ await this.sp00ky.init();
33
+ this._initialized = true;
34
+ }
35
+ /**
36
+ * Tear down the client: leaves the tabs broker, closes the local store and
37
+ * remote socket, and frees the wasm circuit.
38
+ */
39
+ async close() {
40
+ const instance = this.sp00ky;
41
+ this.sp00ky = null;
42
+ this._initialized = false;
43
+ if (instance) await instance.close();
44
+ }
45
+ /** Create a new record in the database. */
46
+ async create(id, payload) {
47
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
48
+ await this.sp00ky.create(id, payload);
49
+ }
50
+ /** Update an existing record in the database. */
51
+ async update(tableName, recordId, payload, options) {
52
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
53
+ await this.sp00ky.update(tableName, recordId, payload, options);
54
+ }
55
+ /** Delete an existing record in the database. */
56
+ async delete(tableName, selector) {
57
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
58
+ const isRecordId = selector instanceof RecordId$1 || selector?.constructor?.name === "RecordId";
59
+ let id;
60
+ if (typeof selector === "string") id = selector;
61
+ else if (isRecordId) id = `${tableName}:${selector.id}`;
62
+ else throw new Error("Only string ID or RecordId selectors are supported currently with core");
63
+ await this.sp00ky.delete(tableName, id);
64
+ }
65
+ /**
66
+ * Preload/prewarm a built query into the local cache without a component
67
+ * subscribing to it, so a later `useQuery` for the same data paints
68
+ * instantly. Best-effort.
69
+ */
70
+ async preload(finalQuery, options) {
71
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
72
+ await this.sp00ky.preload(finalQuery, options);
73
+ }
74
+ /** Start a query on `table`. Finish it with `.build()` and pass it to `useQuery`. */
75
+ query(table) {
76
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
77
+ return this.sp00ky.query(table, {});
78
+ }
79
+ /**
80
+ * Open a peer to peer channel to `peers` for the rows `query` matches (a
81
+ * query on a `-- @channel` table; only its `where` counts). Prefer the
82
+ * `useChannel` hook, which closes it with the component.
83
+ */
84
+ channel(query, peers) {
85
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
86
+ return this.sp00ky.channel(query, peers);
87
+ }
88
+ /** Run a backend operation (writes an outbox job row). */
89
+ async run(backend, path, payload, options) {
90
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
91
+ await this.sp00ky.run(backend, path, payload, options);
92
+ }
93
+ /** Authenticate the remote connection with a token. */
94
+ async authenticate(token) {
95
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
96
+ await this.sp00ky.authenticate(token);
97
+ }
98
+ /**
99
+ * Tell the client that this app's own impersonation banner is on screen.
100
+ * Only needed with `impersonationBanner: { mode: 'custom' }`; the
101
+ * `useImpersonation({ rendersBanner: true })` hook calls it for you.
102
+ */
103
+ acknowledgeImpersonationBanner() {
104
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
105
+ this.sp00ky.acknowledgeImpersonationBanner();
106
+ }
107
+ /** Sign out, clear session and local storage. */
108
+ async signOut() {
109
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
110
+ await this.sp00ky.auth.signOut();
111
+ }
112
+ /** Execute a function with direct access to the remote database connection. */
113
+ async useRemote(fn) {
114
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
115
+ return await this.sp00ky.useRemote(fn);
116
+ }
117
+ /**
118
+ * Run one SurrealQL statement against the REMOTE database, results shaped
119
+ * like the SDK's own `.query()` (one entry per statement). Nothing is cached
120
+ * locally. Prefer this over `useRemote(s => s.query(...))` for a plain read:
121
+ * the bare SDK client that callback receives skips the connect gate, so a
122
+ * statement issued while the socket is being rebuilt fails with "Specify a
123
+ * namespace to use" instead of waiting for the session.
124
+ */
125
+ async remoteQuery(sql, vars) {
126
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
127
+ return await this.sp00ky.remoteQuery(sql, vars);
128
+ }
129
+ /** Access the remote database service directly. */
130
+ get remote() {
131
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
132
+ return this.sp00ky.remoteClient;
133
+ }
134
+ /** Access the local database service directly. */
135
+ get local() {
136
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
137
+ return this.sp00ky.localClient;
138
+ }
139
+ /** Access the auth service. */
140
+ get auth() {
141
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
142
+ return this.sp00ky.auth;
143
+ }
144
+ get pendingMutationCount() {
145
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
146
+ return this.sp00ky.pendingMutationCount;
147
+ }
148
+ /** Diagnostic, see `Sp00kyClient.liveRetryCount`. */
149
+ get liveRetryCount() {
150
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
151
+ return this.sp00ky.liveRetryCount;
152
+ }
153
+ subscribeToPendingMutations(cb) {
154
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
155
+ return this.sp00ky.subscribeToPendingMutations(cb);
156
+ }
157
+ /** Queries mid-fetch right now. See {@link useSyncActivity}. */
158
+ get fetchingQueryCount() {
159
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
160
+ return this.sp00ky.fetchingQueryCount;
161
+ }
162
+ /**
163
+ * Observe how many queries are fetching from the server. Fires immediately
164
+ * and on every change. Prefer the `useSyncActivity` hook in components.
165
+ */
166
+ subscribeToFetchActivity(cb) {
167
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
168
+ return this.sp00ky.subscribeToFetchActivity(cb);
169
+ }
170
+ /** Current sync-health snapshot. See {@link useSyncStatus}. */
171
+ get syncHealth() {
172
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
173
+ return this.sp00ky.syncHealth;
174
+ }
175
+ /**
176
+ * Observe sync health. Fires immediately with the current status and again
177
+ * on every healthy/degraded transition. Prefer the `useSyncStatus` hook in
178
+ * components; this is the imperative escape hatch.
179
+ */
180
+ subscribeToSyncHealth(cb) {
181
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
182
+ return this.sp00ky.subscribeToSyncHealth(cb);
183
+ }
184
+ /** Current local-store durability snapshot. See {@link useStorageStatus}. */
185
+ get storageHealth() {
186
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
187
+ return this.sp00ky.storageHealth;
188
+ }
189
+ /**
190
+ * Observe local-store durability. Fires immediately with the current
191
+ * snapshot and again on change. Prefer the `useStorageStatus` hook.
192
+ */
193
+ subscribeToStorageHealth(cb) {
194
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
195
+ return this.sp00ky.subscribeToStorageHealth(cb);
196
+ }
197
+ /**
198
+ * Web Push for this browser: `support()`, `subscribe()` (from a click),
199
+ * `devices()`, `notify()` / `test()` (push to yourself), `bridge()` for the
200
+ * service worker. See the push-notifications docs page.
201
+ */
202
+ get webPush() {
203
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
204
+ return this.sp00ky.webPush;
205
+ }
206
+ bucket(name) {
207
+ if (!this.sp00ky) throw new Error("SyncedDb not initialized");
208
+ return this.sp00ky.bucket(name);
209
+ }
210
+ getBucketConfig(name) {
211
+ return this.config.schema.buckets?.find((b) => b.name === name);
212
+ }
213
+ };
214
+
215
+ //#endregion
216
+ //#region src/provider.tsx
217
+ /** `useLayoutEffect` in the browser, `useEffect` on the server (no warning, same order). */
218
+ const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
219
+ /** Ref that always holds the latest value, for callbacks read from async continuations. */
220
+ function useLatest(value) {
221
+ const ref = useRef(value);
222
+ useIsomorphicLayoutEffect(() => {
223
+ ref.current = value;
224
+ });
225
+ return ref;
226
+ }
227
+ const Sp00kyContext = createContext(null);
228
+ /** The provider's `SyncedDb`, or `null` outside one. */
229
+ function useOptionalDb() {
230
+ return useContext(Sp00kyContext);
231
+ }
232
+ /**
233
+ * The `SyncedDb` the nearest `<Sp00kyProvider>` initialized. Throws outside a
234
+ * provider; every hook in this package goes through it.
235
+ */
236
+ function useDb() {
237
+ const db = useContext(Sp00kyContext);
238
+ if (!db) throw new Error("useDb must be used within a <Sp00kyProvider>. Wrap your app in <Sp00kyProvider config={...}>.");
239
+ return db;
240
+ }
241
+ /**
242
+ * Initializes a sp00ky client and provides it to `useDb()` and every hook
243
+ * below. Renders `fallback` until the client is ready.
244
+ *
245
+ * The client is created in an effect, never during render, so a server render
246
+ * only produces the fallback and StrictMode's double render creates nothing.
247
+ */
248
+ function Sp00kyProvider(props) {
249
+ const [db, setDb] = useState(null);
250
+ const boot = useRef(null);
251
+ const callbacks = useLatest({
252
+ onError: props.onError,
253
+ onReady: props.onReady,
254
+ preload: props.preload
255
+ });
256
+ const config = useRef(props.config).current;
257
+ useEffect(() => {
258
+ let active = true;
259
+ let current = boot.current;
260
+ if (current?.disposeTimer !== void 0) {
261
+ clearTimeout(current.disposeTimer);
262
+ current.disposeTimer = void 0;
263
+ }
264
+ if (!current) {
265
+ const instance = new SyncedDb(config);
266
+ current = boot.current = {
267
+ instance,
268
+ init: instance.init(),
269
+ revealed: false
270
+ };
271
+ }
272
+ const b = current;
273
+ b.init.then(async () => {
274
+ if (!active) return;
275
+ const preload = callbacks.current.preload;
276
+ if (preload && !b.revealed) try {
277
+ await preload(b.instance);
278
+ } catch (e) {
279
+ console.error("Sp00kyProvider: preload failed; revealing UI anyway", e);
280
+ }
281
+ if (!active) return;
282
+ const first = !b.revealed;
283
+ b.revealed = true;
284
+ setDb(b.instance);
285
+ if (first) callbacks.current.onReady?.(b.instance);
286
+ }, (e) => {
287
+ if (!active) return;
288
+ const error = e instanceof Error ? e : new Error(String(e));
289
+ if (callbacks.current.onError) callbacks.current.onError(error);
290
+ else console.error("Sp00kyProvider: Failed to initialize database", error);
291
+ });
292
+ return () => {
293
+ active = false;
294
+ b.disposeTimer = setTimeout(() => {
295
+ b.disposeTimer = void 0;
296
+ if (boot.current !== b) return;
297
+ boot.current = null;
298
+ if (!b.revealed) b.init.then(() => b.instance.close(), () => {});
299
+ }, 0);
300
+ };
301
+ }, []);
302
+ if (!db) return /* @__PURE__ */ jsx(Fragment, { children: props.fallback ?? null });
303
+ return /* @__PURE__ */ jsx(Sp00kyContext.Provider, {
304
+ value: db,
305
+ children: props.children
306
+ });
307
+ }
308
+
309
+ //#endregion
310
+ //#region src/query.ts
311
+ const isPlainObject = (v) => {
312
+ if (v === null || typeof v !== "object") return false;
313
+ const proto = Object.getPrototypeOf(v);
314
+ return proto === Object.prototype || proto === null;
315
+ };
316
+ /**
317
+ * Value equality for the leaves `share` does not descend into. The decoder
318
+ * hands out a fresh RecordId / Date / Uuid / Duration for every record-link
319
+ * and datetime column on every emission, so by identity every such field
320
+ * "changed" every time. Two instances of the same class that print alike are
321
+ * the same value. A class whose `toString` is the default `[object X]`
322
+ * (ArrayBuffer, Map, ...) cannot be compared that way and counts as changed.
323
+ */
324
+ function sameValue(a, b) {
325
+ if (a === b) return true;
326
+ if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
327
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
328
+ const ctor = a.constructor;
329
+ if (!ctor || ctor !== b.constructor || ctor === Object || ctor === Array) return false;
330
+ const text = String(a);
331
+ return !text.startsWith("[object ") && text === String(b);
332
+ }
333
+ const keyOf = (v) => {
334
+ if (!isPlainObject(v)) return void 0;
335
+ const id = v.id;
336
+ return id === void 0 || id === null ? void 0 : String(id);
337
+ };
338
+ /**
339
+ * Structural sharing between two emissions: returns `prev` itself where
340
+ * `next` is deep-equal to it, and a new value that reuses every unchanged
341
+ * subtree otherwise. Array items with an `id` are matched by id, so a row keeps
342
+ * its object identity across reorders, inserts and deletes; `React.memo` rows
343
+ * and `useMemo` deps keyed on a row only re-run when that row changed.
344
+ *
345
+ * Never mutates either argument: the engine may hand the same row objects to
346
+ * several subscribers.
347
+ */
348
+ function share(prev, next) {
349
+ if (prev === next) return next;
350
+ if (Array.isArray(prev) && Array.isArray(next)) {
351
+ const byKey = /* @__PURE__ */ new Map();
352
+ for (const item of prev) {
353
+ const k = keyOf(item);
354
+ if (k !== void 0) byKey.set(k, item);
355
+ }
356
+ let same = prev.length === next.length;
357
+ const out = next.map((item, i) => {
358
+ const k = keyOf(item);
359
+ const base = k !== void 0 ? byKey.get(k) : prev[i];
360
+ const v = base === void 0 ? item : share(base, item);
361
+ if (v !== prev[i]) same = false;
362
+ return v;
363
+ });
364
+ return same ? prev : out;
365
+ }
366
+ if (isPlainObject(prev) && isPlainObject(next)) {
367
+ const keys = Object.keys(next);
368
+ let same = keys.length === Object.keys(prev).length;
369
+ const out = {};
370
+ for (const k of keys) {
371
+ const v = k in prev ? share(prev[k], next[k]) : next[k];
372
+ if (v !== prev[k] || !(k in prev)) same = false;
373
+ out[k] = v;
374
+ }
375
+ return same ? prev : out;
376
+ }
377
+ return sameValue(prev, next) ? prev : next;
378
+ }
379
+ const initialQueryState = {
380
+ data: null,
381
+ error: void 0,
382
+ isAuthoritative: false,
383
+ hasPainted: false,
384
+ isFetching: false
385
+ };
386
+ /**
387
+ * The query state machine, the same contract as the Solid 2 binding:
388
+ *
389
+ * - `reset` (a new identity) clears authority, the paint latch and the error.
390
+ * The previous `data` stays until the new identity emits, so growing a
391
+ * `.limit()` does not flash an empty list.
392
+ * - `rows` applies every emission as-is (the core only emits what it decided
393
+ * the query holds); one WITH data ends the cold load on its own.
394
+ * - `authority` is the channel that ends a cold load whose honest answer is
395
+ * zero rows. A flip back to false is a bucket switch (another principal):
396
+ * what is painted is the previous one's, so the paint latch goes too.
397
+ *
398
+ * Returns `state` itself when nothing changed, so React skips the render.
399
+ */
400
+ function reduceQuery(state, event) {
401
+ switch (event.type) {
402
+ case "reset":
403
+ if (!state.isAuthoritative && !state.hasPainted && !state.error && !state.isFetching) return state;
404
+ return {
405
+ ...state,
406
+ isAuthoritative: false,
407
+ hasPainted: false,
408
+ error: void 0,
409
+ isFetching: false
410
+ };
411
+ case "rows": {
412
+ const next = event.isOne ? event.rows[0] ?? null : event.rows;
413
+ const hasRows = event.isOne ? next !== null && next !== void 0 : event.rows.length > 0;
414
+ const data = share(state.data, next);
415
+ const hasPainted = state.hasPainted || hasRows;
416
+ if (data === state.data && hasPainted === state.hasPainted) return state;
417
+ return {
418
+ ...state,
419
+ data,
420
+ hasPainted
421
+ };
422
+ }
423
+ case "status": return event.fetching === state.isFetching ? state : {
424
+ ...state,
425
+ isFetching: event.fetching
426
+ };
427
+ case "authority": {
428
+ const hasPainted = event.known ? state.hasPainted : false;
429
+ if (event.known === state.isAuthoritative && hasPainted === state.hasPainted) return state;
430
+ return {
431
+ ...state,
432
+ isAuthoritative: event.known,
433
+ hasPainted
434
+ };
435
+ }
436
+ case "error": return {
437
+ ...state,
438
+ error: event.error
439
+ };
440
+ }
441
+ }
442
+ var QueryStore = class {
443
+ constructor() {
444
+ this.state = initialQueryState;
445
+ this.listeners = /* @__PURE__ */ new Set();
446
+ this.subscribe = (listener) => {
447
+ this.listeners.add(listener);
448
+ return () => {
449
+ this.listeners.delete(listener);
450
+ };
451
+ };
452
+ this.getSnapshot = () => this.state;
453
+ }
454
+ dispatch(event) {
455
+ const next = reduceQuery(this.state, event);
456
+ if (next === this.state) return;
457
+ this.state = next;
458
+ for (const l of this.listeners) l();
459
+ }
460
+ /** Clear the identity flags: the query went away or was disabled. */
461
+ reset() {
462
+ this.dispatch({ type: "reset" });
463
+ }
464
+ /**
465
+ * Register `query` and mirror its rows, fetch status and authority until the
466
+ * returned cleanup runs. Registration can fail (canonically the SSP
467
+ * answering 503 NOT_READY while it bootstraps): that surfaces as `error`, and
468
+ * the sync scheduler retries the registration underneath.
469
+ */
470
+ attach(sp00ky, query) {
471
+ this.dispatch({ type: "reset" });
472
+ let disposed = false;
473
+ const cleanups = [];
474
+ const addCleanup = (c) => {
475
+ if (typeof c === "function") {
476
+ if (disposed) c();
477
+ else cleanups.push(c);
478
+ return;
479
+ }
480
+ c.then((fn) => {
481
+ if (disposed) fn();
482
+ else cleanups.push(fn);
483
+ }, () => {});
484
+ };
485
+ query.run().then(({ hash }) => {
486
+ if (disposed) return;
487
+ this.activeHash = hash;
488
+ addCleanup(sp00ky.subscribeQueryStatus(hash, (status) => {
489
+ if (!disposed) this.dispatch({
490
+ type: "status",
491
+ fetching: status === "fetching"
492
+ });
493
+ }, { immediate: true }));
494
+ addCleanup(sp00ky.subscribe(hash, (rows) => {
495
+ if (disposed) return;
496
+ const t0 = performance.now();
497
+ this.dispatch({
498
+ type: "rows",
499
+ rows,
500
+ isOne: query.isOne
501
+ });
502
+ sp00ky.reportFrontendTiming(hash, performance.now() - t0);
503
+ }, { immediate: true }));
504
+ addCleanup(sp00ky.subscribeQueryAuthority(hash, (known) => {
505
+ if (!disposed) this.dispatch({
506
+ type: "authority",
507
+ known
508
+ });
509
+ }, { immediate: true }));
510
+ }, (err) => {
511
+ if (disposed) return;
512
+ this.dispatch({
513
+ type: "error",
514
+ error: err instanceof Error ? err : new Error(String(err))
515
+ });
516
+ });
517
+ return () => {
518
+ disposed = true;
519
+ for (const c of cleanups) c();
520
+ };
521
+ }
522
+ };
523
+ const EMPTY_LIST = Object.freeze([]);
524
+ function useQuery(dbOrQuery, queryOrOptions, maybeOptions) {
525
+ const explicit = dbOrQuery instanceof SyncedDb ? dbOrQuery : null;
526
+ const contextDb = useOptionalDb();
527
+ const db = explicit ?? contextDb;
528
+ if (!db) throw new Error("useQuery: no db argument and no <Sp00kyProvider> above. Pass a SyncedDb or wrap your app in <Sp00kyProvider>.");
529
+ const query = explicit ? queryOrOptions : dbOrQuery;
530
+ const options = explicit ? maybeOptions : queryOrOptions;
531
+ const [store] = useState(() => new QueryStore());
532
+ const state = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
533
+ const identity = (options?.enabled ?? true) && query ? query.hash : null;
534
+ useEffect(() => {
535
+ if (identity === null || !query) {
536
+ store.reset();
537
+ return;
538
+ }
539
+ return store.attach(db.getSp00ky(), query);
540
+ }, [
541
+ store,
542
+ db,
543
+ identity
544
+ ]);
545
+ const deregister = options?.deregisterOnCleanup ?? false;
546
+ useEffect(() => {
547
+ if (!deregister) return;
548
+ return () => {
549
+ if (store.activeHash) db.getSp00ky().deregisterQuery(store.activeHash);
550
+ };
551
+ }, [
552
+ store,
553
+ db,
554
+ deregister
555
+ ]);
556
+ const isOne = query?.isOne;
557
+ let data = state.data;
558
+ if (isOne === false && !Array.isArray(data)) data = EMPTY_LIST;
559
+ else if (isOne === true && Array.isArray(data)) data = null;
560
+ const hasData = Array.isArray(data) ? data.length > 0 : data !== null && data !== void 0;
561
+ return {
562
+ data,
563
+ error: state.error,
564
+ isLoading: !state.isAuthoritative && !state.hasPainted && state.error === void 0,
565
+ isFetching: state.isFetching,
566
+ isAuthoritative: state.isAuthoritative,
567
+ hasData,
568
+ isEmpty: state.isAuthoritative && !hasData,
569
+ isSettled: state.isAuthoritative && !state.isFetching
570
+ };
571
+ }
572
+ /**
573
+ * Fire-and-forget prewarm: registers `query` via `db.preload` (a live query
574
+ * nobody subscribes to, evicted a ttl after registration unless a view mounts
575
+ * it first) whenever its identity changes. Nothing to clean up.
576
+ *
577
+ * Typical use: inside a list row, preload the detail query the user is likely
578
+ * to open next, so navigation paints from cache instead of the network.
579
+ */
580
+ function usePreload(query, options) {
581
+ const db = useDb();
582
+ const identity = (options?.enabled ?? true) && query ? query.hash : null;
583
+ const signal = options?.signal;
584
+ useEffect(() => {
585
+ if (identity === null || !query) return;
586
+ db.getSp00ky().preload(query, { signal }).catch(() => {});
587
+ }, [db, identity]);
588
+ }
589
+
590
+ //#endregion
591
+ //#region src/status.ts
592
+ /** Shallow equality for the snapshot objects the engine re-creates on every callback. */
593
+ function shallowEqual(a, b) {
594
+ if (Object.is(a, b)) return true;
595
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
596
+ const ka = Object.keys(a);
597
+ if (ka.length !== Object.keys(b).length) return false;
598
+ return ka.every((k) => Object.is(a[k], b[k]));
599
+ }
600
+ /**
601
+ * React view over an engine subscribe-callback API. The engine's subscribe
602
+ * methods fire immediately with the current value, and `read` seeds the
603
+ * first render so nothing flashes before that lands. `deps` identify the
604
+ * source: a change re-reads and re-subscribes.
605
+ */
606
+ function useEngineValue(subscribe, read, deps) {
607
+ const source = useMemo(() => {
608
+ let value = read();
609
+ return {
610
+ subscribe: (onChange) => subscribe((next) => {
611
+ if (shallowEqual(value, next)) return;
612
+ value = next;
613
+ onChange();
614
+ }),
615
+ getSnapshot: () => value
616
+ };
617
+ }, deps);
618
+ return useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot);
619
+ }
620
+ /**
621
+ * Count of locally committed mutations the server has not acknowledged yet.
622
+ * Drive an "unsaved changes" indicator off this.
623
+ */
624
+ function usePendingMutations() {
625
+ const db = useDb();
626
+ return useEngineValue((cb) => db.subscribeToPendingMutations(cb), () => db.pendingMutationCount, [db]);
627
+ }
628
+ /**
629
+ * Sync health for a "can't reach the server" banner. Single sync failures are
630
+ * absorbed by the retry; `isDegraded` only turns on once failures persist for
631
+ * `syncHealth.degradeAfterConsecutiveFailures` rounds (default 3).
632
+ */
633
+ function useSyncStatus() {
634
+ const db = useDb();
635
+ const health = useEngineValue((cb) => db.subscribeToSyncHealth(cb), () => db.syncHealth, [db]);
636
+ return {
637
+ health,
638
+ status: health.status,
639
+ isHealthy: health.status === "healthy",
640
+ isDegraded: health.status === "degraded",
641
+ everConnected: health.everConnected,
642
+ isOffline: health.status === "degraded" && health.everConnected,
643
+ connection: health.connection,
644
+ isReconnecting: health.connection === "reconnecting"
645
+ };
646
+ }
647
+ /** `busy` once it has held for `delayMs`; off the same render it clears. */
648
+ function useDelayedOn(busy, delayMs) {
649
+ const [on, setOn] = useState(false);
650
+ useEffect(() => {
651
+ if (!busy) {
652
+ setOn(false);
653
+ return;
654
+ }
655
+ if (delayMs <= 0) {
656
+ setOn(true);
657
+ return;
658
+ }
659
+ const timer = setTimeout(() => setOn(true), delayMs);
660
+ return () => clearTimeout(timer);
661
+ }, [busy, delayMs]);
662
+ return busy && on;
663
+ }
664
+ /**
665
+ * The two directions of sync traffic, for an indicator in the app chrome. Both
666
+ * flags are debounced ON by their delay and drop at once, so a local-first
667
+ * page that answers from cache and confirms within a few ms never flickers.
668
+ */
669
+ function useSyncActivity(dbOrOptions, maybeOptions) {
670
+ const explicitDb = dbOrOptions instanceof SyncedDb ? dbOrOptions : void 0;
671
+ const options = (explicitDb ? maybeOptions : dbOrOptions) ?? {};
672
+ const contextDb = useOptionalDb();
673
+ const db = explicitDb ?? contextDb;
674
+ if (!db) throw new Error("useSyncActivity must be used within a <Sp00kyProvider>, or pass the SyncedDb.");
675
+ const fetchingQueries = useEngineValue((cb) => db.subscribeToFetchActivity(cb), () => db.fetchingQueryCount, [db]);
676
+ const pendingMutations = useEngineValue((cb) => db.subscribeToPendingMutations(cb), () => db.pendingMutationCount, [db]);
677
+ return {
678
+ fetchingQueries,
679
+ pendingMutations,
680
+ isDownloading: useDelayedOn(fetchingQueries > 0, options.downloadDelayMs ?? 200),
681
+ isUploading: useDelayedOn(pendingMutations > (options.uploadThreshold ?? 0), options.uploadDelayMs ?? 150)
682
+ };
683
+ }
684
+ /** How durable the LOCAL cache is, for a "no local storage" warning. */
685
+ function useStorageStatus() {
686
+ const db = useDb();
687
+ const health = useEngineValue((cb) => db.subscribeToStorageHealth(cb), () => db.storageHealth, [db]);
688
+ return {
689
+ health,
690
+ status: health.status,
691
+ isPersistent: health.status === "persistent",
692
+ isMemoryFallback: health.fallback
693
+ };
694
+ }
695
+ /** Observe admin impersonation (started from the DevTools). */
696
+ function useImpersonation(options = {}) {
697
+ const db = useDb();
698
+ const impersonation = useEngineValue((cb) => db.auth.subscribeImpersonation(cb), () => db.auth.impersonation, [db]);
699
+ useEffect(() => {
700
+ if (options.rendersBanner && impersonation) db.acknowledgeImpersonationBanner();
701
+ }, [
702
+ db,
703
+ options.rendersBanner,
704
+ impersonation
705
+ ]);
706
+ const stop = useCallback(() => db.auth.stopImpersonating(), [db]);
707
+ return {
708
+ impersonation,
709
+ isImpersonating: impersonation !== null,
710
+ stop
711
+ };
712
+ }
713
+ /**
714
+ * A feature flag for the signed-in user. Updates live when the assignment in
715
+ * `_00_user_feature` changes (e.g. `spky flag enable <key>`).
716
+ */
717
+ function useFeatureFlag(key, options) {
718
+ const db = useDb();
719
+ const fallback = options?.fallback;
720
+ const ttl = options?.ttl;
721
+ const state = useEngineValue((cb) => {
722
+ const handle = db.getSp00ky().feature(key, {
723
+ fallback,
724
+ ttl
725
+ });
726
+ const off = handle.subscribe((s) => cb({
727
+ variant: s.variant ?? fallback,
728
+ payload: s.payload
729
+ }));
730
+ return () => {
731
+ off();
732
+ handle.close();
733
+ };
734
+ }, () => {
735
+ const peek = db.getSp00ky().feature(key, {
736
+ fallback,
737
+ ttl
738
+ });
739
+ const value = {
740
+ variant: peek.variant(),
741
+ payload: peek.payload()
742
+ };
743
+ peek.close();
744
+ return value;
745
+ }, [
746
+ db,
747
+ key,
748
+ fallback,
749
+ ttl
750
+ ]);
751
+ return {
752
+ variant: state.variant,
753
+ payload: state.payload,
754
+ enabled: state.variant !== void 0 && state.variant !== "off"
755
+ };
756
+ }
757
+ async function reloadForSnapshot(snapshot) {
758
+ if (typeof window === "undefined") return;
759
+ if (snapshot.cacheBust) try {
760
+ if (window.caches) {
761
+ const keys = await window.caches.keys();
762
+ await Promise.all(keys.map((k) => window.caches.delete(k)));
763
+ }
764
+ if (navigator.serviceWorker) {
765
+ const regs = await navigator.serviceWorker.getRegistrations();
766
+ for (const r of regs) r.update().catch(() => {});
767
+ }
768
+ window.location.href = window.location.pathname + "?cb=" + Date.now();
769
+ return;
770
+ } catch {}
771
+ window.location.reload();
772
+ }
773
+ /**
774
+ * The app's announced release (`_00_app_release:<app>`, written by
775
+ * `spky deploy` / `spky release`) compared against the running build.
776
+ */
777
+ function useAppRelease(options) {
778
+ const db = useDb();
779
+ const { app, ttl, currentVersion } = options;
780
+ const snapshot = useEngineValue((cb) => {
781
+ const handle = db.getSp00ky().appRelease(app, { ttl });
782
+ const off = handle.subscribe(cb);
783
+ return () => {
784
+ off();
785
+ handle.close();
786
+ };
787
+ }, () => {
788
+ const peek = db.getSp00ky().appRelease(app, { ttl });
789
+ const value = peek.snapshot();
790
+ peek.close();
791
+ return value;
792
+ }, [
793
+ db,
794
+ app,
795
+ ttl
796
+ ]);
797
+ const updateAvailable = semverGt(snapshot.version, currentVersion);
798
+ const latest = useLatest(snapshot);
799
+ const reload = useCallback(() => reloadForSnapshot(latest.current), [latest]);
800
+ return {
801
+ latestVersion: snapshot.version,
802
+ updateAvailable,
803
+ mandatory: updateAvailable && snapshot.mandatory,
804
+ cacheBust: snapshot.cacheBust,
805
+ reload
806
+ };
807
+ }
808
+ /**
809
+ * Pending/error state around a mutation, for a button spinner. The engine is
810
+ * already optimistic local-first (a write commits locally and re-renders
811
+ * through live queries before it syncs), so there is no optimistic layer here.
812
+ * An error means the LOCAL commit failed; sync failures surface through
813
+ * `useSyncStatus` and `usePendingMutations`.
814
+ *
815
+ * `submit` is stable across renders and always calls the latest `fn`.
816
+ */
817
+ function useSubmission(fn) {
818
+ const latest = useLatest(fn);
819
+ const [inFlight, setInFlight] = useState(0);
820
+ const [error, setError] = useState(void 0);
821
+ const [result, setResult] = useState(void 0);
822
+ const submit = useCallback(async (...args) => {
823
+ setError(void 0);
824
+ setInFlight((n) => n + 1);
825
+ try {
826
+ const r = await latest.current(...args);
827
+ setResult(() => r);
828
+ return r;
829
+ } catch (e) {
830
+ setError(e instanceof Error ? e : new Error(String(e)));
831
+ return;
832
+ } finally {
833
+ setInFlight((n) => n - 1);
834
+ }
835
+ }, [latest]);
836
+ const clearError = useCallback(() => setError(void 0), []);
837
+ return {
838
+ submit,
839
+ pending: inFlight > 0,
840
+ error,
841
+ result,
842
+ clearError
843
+ };
844
+ }
845
+
846
+ //#endregion
847
+ //#region src/realtime.ts
848
+ /**
849
+ * Open a `@crdt` field of the record `recordId` names, for an editor to bind
850
+ * to (`field?.getDoc()`). Re-opens when the id changes, closes on unmount.
851
+ *
852
+ * `null` until the field is loaded (`CrdtField.isLoaded`): this device had the
853
+ * document, or the server answered. Until then show the column's text instead
854
+ * of binding an editor to a document still arriving.
855
+ */
856
+ function useCrdtField(table, recordId, field) {
857
+ const db = useDb();
858
+ const key = recordId ? `${table}\u0000${recordId}\u0000${field}` : null;
859
+ const [opened, setOpened] = useState(null);
860
+ useEffect(() => {
861
+ if (!key || !recordId) return;
862
+ const sp00ky = db.getSp00ky();
863
+ let superseded = false;
864
+ let isOpen = false;
865
+ let offLoaded = () => {};
866
+ sp00ky.openCrdtField(table, recordId, field).then((cf) => {
867
+ isOpen = true;
868
+ if (superseded) {
869
+ sp00ky.closeCrdtField(table, recordId, field);
870
+ return;
871
+ }
872
+ offLoaded = cf.onLoaded(() => {
873
+ if (!superseded) setOpened({
874
+ key,
875
+ field: cf
876
+ });
877
+ });
878
+ }).catch((err) => {
879
+ console.error(`[useCrdtField] Failed to open CRDT field ${table}.${field} on ${recordId}:`, err);
880
+ });
881
+ return () => {
882
+ superseded = true;
883
+ offLoaded();
884
+ if (isOpen) sp00ky.closeCrdtField(table, recordId, field);
885
+ setOpened(null);
886
+ };
887
+ }, [db, key]);
888
+ return opened && opened.key === key ? opened.field : null;
889
+ }
890
+ const IDLE = {
891
+ status: "idle",
892
+ peers: []
893
+ };
894
+ /** Identity of a channel's queries: their hashes (a builder is built first). */
895
+ function queriesKey(q) {
896
+ if (!q) return null;
897
+ return (Array.isArray(q) ? q : [q]).map((item) => String("build" in item && typeof item.build === "function" ? item.build().hash : item.hash)).join(",");
898
+ }
899
+ const peersKey = (peers) => [...peers].map((p) => String(p)).join("\0");
900
+ /**
901
+ * Open a peer to peer channel to `peers` for the rows `query` matches, while
902
+ * the component is mounted. The query must be on a `-- @channel` table and
903
+ * only its `where` counts; it is checked against each row, never registered.
904
+ * Writes to matching rows (`db.update` / `db.create` / `db.delete`, or the
905
+ * channel's own) reach the peers over WebRTC in tens of ms; `-- @ephemeral`
906
+ * fields travel only this way. A connection forms when both sides list each
907
+ * other; your own id is skipped.
908
+ *
909
+ * ```tsx
910
+ * const ch = useChannel(db.query('message').where({ conversation: convoId }), [me, other]);
911
+ * ```
912
+ *
913
+ * `query` may be `null` (closes the channel until a query is passed again) or
914
+ * a list of queries. Query and peers are compared by value, so building them
915
+ * inline is fine.
916
+ */
917
+ function useChannel(query, peers) {
918
+ const db = useDb();
919
+ const [state, setState] = useState(IDLE);
920
+ const channel = useRef(null);
921
+ const qKey = queriesKey(query);
922
+ const pKey = peersKey(peers);
923
+ const latest = useLatest({
924
+ query,
925
+ peers
926
+ });
927
+ const isOpen = qKey !== null;
928
+ useEffect(() => {
929
+ if (!isOpen) return;
930
+ const { query: q, peers: p } = latest.current;
931
+ const ch = db.channel(q, p);
932
+ channel.current = ch;
933
+ const stop = ch.subscribe(setState);
934
+ return () => {
935
+ stop();
936
+ ch.close();
937
+ if (channel.current === ch) channel.current = null;
938
+ setState(IDLE);
939
+ };
940
+ }, [db, isOpen]);
941
+ useEffect(() => {
942
+ const q = latest.current.query;
943
+ if (q) channel.current?.setQueries(q);
944
+ }, [qKey]);
945
+ useEffect(() => {
946
+ channel.current?.setPeers(latest.current.peers);
947
+ }, [pKey]);
948
+ const open = useCallback(() => {
949
+ if (!channel.current) throw new Error("This channel is closed (no query was passed).");
950
+ return channel.current;
951
+ }, []);
952
+ const writes = useMemo(() => ({
953
+ update: ((...args) => open().update(...args)),
954
+ create: ((...args) => open().create(...args)),
955
+ delete: ((...args) => open().delete(...args))
956
+ }), [open]);
957
+ return {
958
+ status: state.status,
959
+ peers: state.peers,
960
+ ...writes
961
+ };
962
+ }
963
+
964
+ //#endregion
965
+ //#region src/files.tsx
966
+ const toError = (e) => e instanceof Error ? e : new Error(String(e));
967
+ /** `(bucket, ...rest)` with the provider's db, or `(db, bucket, ...rest)`. */
968
+ function useDbAndArgs(hook, args) {
969
+ const contextDb = useOptionalDb();
970
+ if (args[0] instanceof SyncedDb) return args;
971
+ if (!contextDb) throw new Error(`${hook} must be used within a <Sp00kyProvider>, or pass the SyncedDb.`);
972
+ return [contextDb, ...args];
973
+ }
974
+ function useFileUpload(...args) {
975
+ const [db, bucketName] = useDbAndArgs("useFileUpload", args);
976
+ const [uploads, setUploads] = useState(0);
977
+ const [error, setError] = useState(null);
978
+ const objectUrls = useRef([]);
979
+ useEffect(() => () => {
980
+ for (const url of objectUrls.current) URL.revokeObjectURL(url);
981
+ objectUrls.current = [];
982
+ }, []);
983
+ const clearError = useCallback(() => setError(null), []);
984
+ const upload = useCallback(async (path, file, options) => {
985
+ setError(null);
986
+ const config = db.getBucketConfig(bucketName);
987
+ if (config?.maxSize !== null && config?.maxSize !== void 0 && file.size > config.maxSize) {
988
+ const maxMB = (config.maxSize / (1024 * 1024)).toFixed(1);
989
+ setError(/* @__PURE__ */ new Error(`File exceeds maximum size of ${maxMB} MB.`));
990
+ return;
991
+ }
992
+ const allowed = config?.allowedExtensions;
993
+ const fileName = file.name;
994
+ if (allowed && allowed.length > 0 && fileName) {
995
+ const ext = fileName.split(".").pop()?.toLowerCase();
996
+ if (!ext || !allowed.includes(ext)) {
997
+ setError(/* @__PURE__ */ new Error(`File type not allowed. Accepted: ${allowed.join(", ")}.`));
998
+ return;
999
+ }
1000
+ }
1001
+ setUploads((n) => n + 1);
1002
+ try {
1003
+ const bytes = await fileToUint8Array(file);
1004
+ return await db.bucket(bucketName).put(path, bytes, options);
1005
+ } catch (e) {
1006
+ setError(toError(e));
1007
+ } finally {
1008
+ setUploads((n) => n - 1);
1009
+ }
1010
+ }, [db, bucketName]);
1011
+ const download = useCallback(async (path) => {
1012
+ setError(null);
1013
+ try {
1014
+ const content = await db.bucket(bucketName).get(path);
1015
+ if (!content) return null;
1016
+ const url = URL.createObjectURL(new Blob([content]));
1017
+ objectUrls.current.push(url);
1018
+ return url;
1019
+ } catch (e) {
1020
+ setError(toError(e));
1021
+ return null;
1022
+ }
1023
+ }, [db, bucketName]);
1024
+ const remove = useCallback(async (path) => {
1025
+ setError(null);
1026
+ try {
1027
+ await db.bucket(bucketName).delete(path);
1028
+ } catch (e) {
1029
+ setError(toError(e));
1030
+ }
1031
+ }, [db, bucketName]);
1032
+ const exists = useCallback(async (path) => {
1033
+ setError(null);
1034
+ try {
1035
+ return await db.bucket(bucketName).exists(path);
1036
+ } catch (e) {
1037
+ setError(toError(e));
1038
+ return false;
1039
+ }
1040
+ }, [db, bucketName]);
1041
+ return {
1042
+ isUploading: uploads > 0,
1043
+ error,
1044
+ clearError,
1045
+ upload,
1046
+ download,
1047
+ remove,
1048
+ exists
1049
+ };
1050
+ }
1051
+ function useDownloadFile(...args) {
1052
+ const [db, bucketName, path, options = {}] = useDbAndArgs("useDownloadFile", args);
1053
+ const useCache = options.cache !== false;
1054
+ const persist = options.persist !== false;
1055
+ const { pin, revalidate } = options;
1056
+ const [tick, setTick] = useState(0);
1057
+ const reloadOnce = useRef(false);
1058
+ const request = path ? `${String(bucketName)}\u0000${path}\u0000${tick}` : null;
1059
+ const [state, setState] = useState({
1060
+ request: null,
1061
+ url: null,
1062
+ isLoading: false,
1063
+ error: null
1064
+ });
1065
+ useEffect(() => {
1066
+ if (!path || !request) return;
1067
+ const reload = reloadOnce.current;
1068
+ reloadOnce.current = false;
1069
+ let cancelled = false;
1070
+ let lease = null;
1071
+ let privateUrl = null;
1072
+ setState((s) => ({
1073
+ request,
1074
+ url: s.url,
1075
+ isLoading: true,
1076
+ error: null
1077
+ }));
1078
+ const bucket = db.bucket(bucketName);
1079
+ (useCache ? bucket.url(path, {
1080
+ persist,
1081
+ pin,
1082
+ revalidate,
1083
+ reload
1084
+ }).then((acquired) => {
1085
+ if (!acquired) return null;
1086
+ if (cancelled) {
1087
+ acquired.release();
1088
+ return null;
1089
+ }
1090
+ lease = acquired;
1091
+ return acquired.url;
1092
+ }) : bucket.read(path, {
1093
+ persist: false,
1094
+ reload: true
1095
+ }).then((blob) => {
1096
+ if (!blob || cancelled) return null;
1097
+ privateUrl = URL.createObjectURL(blob);
1098
+ return privateUrl;
1099
+ })).then((url) => {
1100
+ if (!cancelled) setState({
1101
+ request,
1102
+ url,
1103
+ isLoading: false,
1104
+ error: null
1105
+ });
1106
+ }, (err) => {
1107
+ if (!cancelled) setState({
1108
+ request,
1109
+ url: null,
1110
+ isLoading: false,
1111
+ error: toError(err)
1112
+ });
1113
+ });
1114
+ return () => {
1115
+ cancelled = true;
1116
+ lease?.release();
1117
+ if (privateUrl) URL.revokeObjectURL(privateUrl);
1118
+ };
1119
+ }, [
1120
+ db,
1121
+ request,
1122
+ useCache,
1123
+ persist,
1124
+ pin,
1125
+ revalidate
1126
+ ]);
1127
+ const refetch = useCallback(() => {
1128
+ reloadOnce.current = true;
1129
+ setTick((n) => n + 1);
1130
+ }, []);
1131
+ if (!request) return {
1132
+ url: null,
1133
+ isLoading: false,
1134
+ error: null,
1135
+ refetch
1136
+ };
1137
+ if (state.request !== request) return {
1138
+ url: state.url,
1139
+ isLoading: true,
1140
+ error: null,
1141
+ refetch
1142
+ };
1143
+ return {
1144
+ url: state.url,
1145
+ isLoading: state.isLoading,
1146
+ error: state.error,
1147
+ refetch
1148
+ };
1149
+ }
1150
+ function useBlurhash(...args) {
1151
+ const [db, bucketName, path] = useDbAndArgs("useBlurhash", args);
1152
+ const request = path ? `${String(bucketName)}\u0000${path}` : null;
1153
+ const [state, setState] = useState({
1154
+ request: null,
1155
+ hash: null
1156
+ });
1157
+ useEffect(() => {
1158
+ if (!path || !request) return;
1159
+ let cancelled = false;
1160
+ db.bucket(bucketName).blurhash(path).then((hash) => {
1161
+ if (!cancelled) setState({
1162
+ request,
1163
+ hash
1164
+ });
1165
+ }, () => {
1166
+ if (!cancelled) setState({
1167
+ request,
1168
+ hash: null
1169
+ });
1170
+ });
1171
+ return () => {
1172
+ cancelled = true;
1173
+ };
1174
+ }, [db, request]);
1175
+ if (!request) return {
1176
+ hash: null,
1177
+ isLoading: false
1178
+ };
1179
+ if (state.request !== request) return {
1180
+ hash: null,
1181
+ isLoading: true
1182
+ };
1183
+ return {
1184
+ hash: state.hash,
1185
+ isLoading: false
1186
+ };
1187
+ }
1188
+ function useBucketImage(...args) {
1189
+ const [db, bucketName, path, options = {}] = useDbAndArgs("useBucketImage", args);
1190
+ const { hash } = useBlurhash(db, bucketName, options.blurhash !== false ? path : null);
1191
+ const file = useDownloadFile(db, bucketName, path, options);
1192
+ const [decodedUrl, setDecodedUrl] = useState(null);
1193
+ const url = file.url;
1194
+ const gate = useCallback((img) => {
1195
+ if (!img || !url) return;
1196
+ const done = () => setDecodedUrl(url);
1197
+ if (typeof img.decode === "function") img.decode().then(done, done);
1198
+ else if (img.complete) done();
1199
+ else {
1200
+ img.onload = done;
1201
+ img.onerror = done;
1202
+ }
1203
+ }, [url]);
1204
+ return {
1205
+ ...file,
1206
+ blurhash: hash,
1207
+ ready: url !== null && decodedUrl === url,
1208
+ gate
1209
+ };
1210
+ }
1211
+ /** A blurhash painted onto a canvas, once per hash change. */
1212
+ function Blurhash({ hash, width = 32, height = 32, punch = 1, className, style }) {
1213
+ const canvas = useRef(null);
1214
+ useEffect(() => {
1215
+ const el = canvas.current;
1216
+ if (!el) return;
1217
+ el.width = width;
1218
+ el.height = height;
1219
+ if (!hash) return;
1220
+ try {
1221
+ const pixels = decodeBlurhash(hash, width, height, punch);
1222
+ const ctx = el.getContext("2d");
1223
+ if (!ctx) return;
1224
+ const imageData = ctx.createImageData(width, height);
1225
+ imageData.data.set(pixels);
1226
+ ctx.putImageData(imageData, 0, 0);
1227
+ } catch {}
1228
+ }, [
1229
+ hash,
1230
+ width,
1231
+ height,
1232
+ punch
1233
+ ]);
1234
+ return /* @__PURE__ */ jsx("canvas", {
1235
+ ref: canvas,
1236
+ className,
1237
+ style
1238
+ });
1239
+ }
1240
+ const LAYER = {
1241
+ position: "absolute",
1242
+ inset: 0,
1243
+ width: "100%",
1244
+ height: "100%"
1245
+ };
1246
+ function prefersReducedMotion() {
1247
+ return typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
1248
+ }
1249
+ /**
1250
+ * A bucket image that never pops in. Layers, bottom to top: your `fallback`,
1251
+ * the stored blurhash, and the real image, which stays transparent until its
1252
+ * bitmap is DECODED and then crossfades in. The placeholder layers unmount
1253
+ * once the fade settles. Respects prefers-reduced-motion. The container is
1254
+ * made `position: relative` unless your class positions it already.
1255
+ */
1256
+ function BucketImage(props) {
1257
+ const image = useBucketImage(props.bucket, props.path, {
1258
+ ...props.options,
1259
+ blurhash: props.blurhash !== false
1260
+ });
1261
+ const [reducedMotion] = useState(prefersReducedMotion);
1262
+ const transition = props.transition ?? 300;
1263
+ const root = useRef(null);
1264
+ useIsomorphicLayoutEffect(() => {
1265
+ const el = root.current;
1266
+ if (el && getComputedStyle(el).position === "static") el.style.position = "relative";
1267
+ }, []);
1268
+ const [settledUrl, setSettledUrl] = useState(null);
1269
+ useEffect(() => {
1270
+ if (!image.ready || !image.url) return;
1271
+ const url = image.url;
1272
+ const timer = setTimeout(() => setSettledUrl(url), (reducedMotion ? 0 : transition) + 120);
1273
+ return () => clearTimeout(timer);
1274
+ }, [
1275
+ image.ready,
1276
+ image.url,
1277
+ reducedMotion,
1278
+ transition
1279
+ ]);
1280
+ const settled = image.ready && settledUrl === image.url;
1281
+ return /* @__PURE__ */ jsxs("div", {
1282
+ ref: root,
1283
+ className: props.className,
1284
+ style: props.style,
1285
+ children: [!settled && /* @__PURE__ */ jsxs("div", {
1286
+ style: LAYER,
1287
+ children: [/* @__PURE__ */ jsx("div", {
1288
+ style: LAYER,
1289
+ children: props.fallback
1290
+ }), /* @__PURE__ */ jsx(Blurhash, {
1291
+ hash: image.blurhash,
1292
+ style: LAYER
1293
+ })]
1294
+ }), /* @__PURE__ */ jsx("img", {
1295
+ ref: image.gate,
1296
+ src: image.url ?? void 0,
1297
+ alt: props.alt ?? "",
1298
+ decoding: "async",
1299
+ className: props.imgClassName,
1300
+ style: {
1301
+ ...LAYER,
1302
+ objectFit: props.fit ?? "cover",
1303
+ opacity: image.ready ? 1 : 0,
1304
+ transition: reducedMotion ? "none" : `opacity ${transition}ms ${props.easing ?? "cubic-bezier(0.16, 1, 0.3, 1)"}`
1305
+ }
1306
+ })]
1307
+ });
1308
+ }
1309
+
1310
+ //#endregion
1311
+ export { Blurhash, BucketImage, RecordId, Sp00kyProvider, SyncedDb, Uuid, WebPushError, useAppRelease, useBlurhash, useBucketImage, useChannel, useCrdtField, useDb, useDownloadFile, useFeatureFlag, useFileUpload, useImpersonation, usePendingMutations, usePreload, useQuery, useStorageStatus, useSubmission, useSyncActivity, useSyncStatus };
1312
+ //# sourceMappingURL=index.js.map