@taladb/react 0.8.4 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,14 +1,52 @@
1
+ 'use client';
2
+
1
3
  // src/context.tsx
2
- import { createContext, useContext } from "react";
3
- import { jsx } from "react/jsx-runtime";
4
+ import { createContext, useContext, useEffect, useState } from "react";
5
+ import { Fragment, jsx } from "react/jsx-runtime";
4
6
  var TalaDBContext = createContext(null);
5
- function TalaDBProvider({ db, children }) {
7
+ function TalaDBProvider(props) {
8
+ if ("db" in props && props.db) {
9
+ return /* @__PURE__ */ jsx(TalaDBContext.Provider, { value: props.db, children: props.children });
10
+ }
11
+ return /* @__PURE__ */ jsx(NamedProvider, { ...props });
12
+ }
13
+ function NamedProvider({
14
+ name,
15
+ options,
16
+ fallback = null,
17
+ children
18
+ }) {
19
+ const [db, setDb] = useState(null);
20
+ const [error, setError] = useState(null);
21
+ const optionsKey = JSON.stringify(options ?? null);
22
+ useEffect(() => {
23
+ setError(null);
24
+ let cancelled = false;
25
+ let opened = null;
26
+ import("taladb").then(({ openDB }) => openDB(name, options)).then((instance) => {
27
+ if (cancelled) {
28
+ void instance.close();
29
+ return;
30
+ }
31
+ opened = instance;
32
+ setDb(instance);
33
+ }).catch((e) => {
34
+ if (!cancelled) setError(e);
35
+ });
36
+ return () => {
37
+ cancelled = true;
38
+ if (opened) void opened.close();
39
+ setDb(null);
40
+ };
41
+ }, [name, optionsKey]);
42
+ if (error !== null) throw error;
43
+ if (db === null) return /* @__PURE__ */ jsx(Fragment, { children: fallback });
6
44
  return /* @__PURE__ */ jsx(TalaDBContext.Provider, { value: db, children });
7
45
  }
8
46
  function useTalaDB() {
9
47
  const db = useContext(TalaDBContext);
10
48
  if (db === null) {
11
- throw new Error("useTalaDB must be used inside <TalaDBProvider db={...}>");
49
+ throw new Error('useTalaDB must be used inside <TalaDBProvider db={...}> or <TalaDBProvider name="...">');
12
50
  }
13
51
  return db;
14
52
  }
@@ -23,13 +61,16 @@ function useCollection(name) {
23
61
  // src/useFind.ts
24
62
  import { useCallback, useRef, useSyncExternalStore } from "react";
25
63
  function useFind(collection, filter) {
26
- const snapshotRef = useRef({ data: [], loading: true });
64
+ const snapshotRef = useRef({ data: [], loading: true, error: null });
27
65
  const filterKey = JSON.stringify(filter ?? null);
28
66
  const subscribe = useCallback(
29
67
  (notify) => {
30
- snapshotRef.current = { data: snapshotRef.current.data, loading: true };
68
+ snapshotRef.current = { data: snapshotRef.current.data, loading: true, error: null };
31
69
  return collection.subscribe(filter ?? {}, (docs) => {
32
- snapshotRef.current = { data: docs, loading: false };
70
+ snapshotRef.current = { data: docs, loading: false, error: null };
71
+ notify();
72
+ }, (error) => {
73
+ snapshotRef.current = { ...snapshotRef.current, loading: false, error };
33
74
  notify();
34
75
  });
35
76
  },
@@ -44,13 +85,16 @@ function useFind(collection, filter) {
44
85
  // src/useFindOne.ts
45
86
  import { useCallback as useCallback2, useRef as useRef2, useSyncExternalStore as useSyncExternalStore2 } from "react";
46
87
  function useFindOne(collection, filter) {
47
- const snapshotRef = useRef2({ data: null, loading: true });
88
+ const snapshotRef = useRef2({ data: null, loading: true, error: null });
48
89
  const filterKey = JSON.stringify(filter);
49
90
  const subscribe = useCallback2(
50
91
  (notify) => {
51
- snapshotRef.current = { data: snapshotRef.current.data, loading: true };
92
+ snapshotRef.current = { data: snapshotRef.current.data, loading: true, error: null };
52
93
  return collection.subscribe(filter, (docs) => {
53
- snapshotRef.current = { data: docs[0] ?? null, loading: false };
94
+ snapshotRef.current = { data: docs[0] ?? null, loading: false, error: null };
95
+ notify();
96
+ }, (error) => {
97
+ snapshotRef.current = { ...snapshotRef.current, loading: false, error };
54
98
  notify();
55
99
  });
56
100
  },
@@ -60,10 +104,409 @@ function useFindOne(collection, filter) {
60
104
  const getSnapshot = useCallback2(() => snapshotRef.current, []);
61
105
  return useSyncExternalStore2(subscribe, getSnapshot, getSnapshot);
62
106
  }
107
+
108
+ // src/replication/config.tsx
109
+ import {
110
+ createContext as createContext2,
111
+ useContext as useContext2,
112
+ useEffect as useEffect2,
113
+ useMemo as useMemo2,
114
+ useRef as useRef3
115
+ } from "react";
116
+
117
+ // src/replication/engine.ts
118
+ import { HttpSyncAdapter } from "taladb";
119
+ function replicationTarget(endpoint, collection) {
120
+ return `${endpoint}::${collection}`;
121
+ }
122
+ async function buildAdapter(config) {
123
+ const headers = config.getAuth ? await config.getAuth() : void 0;
124
+ return new HttpSyncAdapter({
125
+ endpoint: config.endpoint,
126
+ headers,
127
+ fetch: config.fetch,
128
+ paths: config.paths
129
+ });
130
+ }
131
+ var inflight = /* @__PURE__ */ new Map();
132
+ function inflightKey(endpoint, collection, direction) {
133
+ return `${endpoint}::${collection}::${direction}`;
134
+ }
135
+ function replicate(db, config, collection, direction) {
136
+ const key = inflightKey(config.endpoint, collection, direction);
137
+ const existing = inflight.get(key);
138
+ if (existing) return existing;
139
+ const pass = (async () => {
140
+ const adapter = await buildAdapter(config);
141
+ await db.sync(adapter, {
142
+ collections: [collection],
143
+ direction,
144
+ target: replicationTarget(config.endpoint, collection)
145
+ });
146
+ })().finally(() => {
147
+ inflight.delete(key);
148
+ });
149
+ inflight.set(key, pass);
150
+ return pass;
151
+ }
152
+ var BACKOFFS_MS = [200, 400, 800];
153
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
154
+ async function replicateWithRetry(db, config, collection, direction) {
155
+ let lastError;
156
+ for (let attempt = 0; attempt <= BACKOFFS_MS.length; attempt++) {
157
+ try {
158
+ await replicate(db, config, collection, direction);
159
+ return;
160
+ } catch (error) {
161
+ lastError = error;
162
+ if (attempt < BACKOFFS_MS.length) await sleep(BACKOFFS_MS[attempt]);
163
+ }
164
+ }
165
+ throw lastError;
166
+ }
167
+
168
+ // src/replication/config.tsx
169
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
170
+ var ReplicationContext = createContext2(null);
171
+ function ReplicationProvider({ children, ...config }) {
172
+ const key = `${config.endpoint}|${config.pollMs ?? ""}|${JSON.stringify(config.paths ?? null)}|${JSON.stringify(config.prefetch ?? null)}|${config.prefetchMode ?? ""}|${config.prefetchConcurrency ?? ""}`;
173
+ const value = useMemo2(
174
+ () => config,
175
+ // eslint-disable-next-line react-hooks/exhaustive-deps
176
+ [key]
177
+ );
178
+ return /* @__PURE__ */ jsxs(ReplicationContext.Provider, { value, children: [
179
+ value.prefetch && value.prefetch.length > 0 ? /* @__PURE__ */ jsx2(PrefetchRunner, {}) : null,
180
+ children
181
+ ] });
182
+ }
183
+ function resolveReplicationConfig(base, overrides) {
184
+ const endpoint = overrides?.endpoint ?? base?.endpoint;
185
+ const pollMs = overrides?.pollMs ?? base?.pollMs ?? 0;
186
+ if (!endpoint) return { config: null, pollMs };
187
+ return {
188
+ config: {
189
+ endpoint,
190
+ getAuth: overrides?.getAuth ?? base?.getAuth,
191
+ fetch: overrides?.fetch ?? base?.fetch,
192
+ paths: overrides?.paths ?? base?.paths
193
+ },
194
+ pollMs
195
+ };
196
+ }
197
+ function useReplicationBase() {
198
+ return useContext2(ReplicationContext);
199
+ }
200
+ function useReplicationConfig(overrides) {
201
+ return resolveReplicationConfig(useContext2(ReplicationContext), overrides);
202
+ }
203
+ var CURSOR_COLLECTION = "__taladb_sync";
204
+ function normalizePrefetch(entries) {
205
+ return (entries ?? []).map((e) => typeof e === "string" ? { collection: e } : e);
206
+ }
207
+ var idleScheduler = (fn) => {
208
+ const g = globalThis;
209
+ if (typeof g.requestIdleCallback === "function") {
210
+ const id2 = g.requestIdleCallback(fn, { timeout: 2e3 });
211
+ return () => g.cancelIdleCallback?.(id2);
212
+ }
213
+ const id = setTimeout(fn, 0);
214
+ return () => clearTimeout(id);
215
+ };
216
+ var schedule = idleScheduler;
217
+ async function hasSynced(db, target) {
218
+ try {
219
+ const doc = await db.collection(CURSOR_COLLECTION).findOne({ target });
220
+ return doc != null;
221
+ } catch {
222
+ return false;
223
+ }
224
+ }
225
+ function PrefetchRunner() {
226
+ const db = useTalaDB();
227
+ const base = useReplicationBase();
228
+ const slices = normalizePrefetch(base?.prefetch);
229
+ const mode = base?.prefetchMode ?? "once";
230
+ const concurrency = Math.max(1, base?.prefetchConcurrency ?? 2);
231
+ const baseRef = useRef3(base);
232
+ baseRef.current = base;
233
+ const sig = JSON.stringify({ slices, mode, concurrency, endpoint: base?.endpoint ?? null });
234
+ useEffect2(() => {
235
+ if (slices.length === 0) return void 0;
236
+ let cancelled = false;
237
+ const cancelSchedule = schedule(() => {
238
+ void run();
239
+ });
240
+ async function run() {
241
+ const b = baseRef.current;
242
+ const queue = normalizePrefetch(b?.prefetch);
243
+ const worker = async () => {
244
+ while (!cancelled) {
245
+ const slice = queue.shift();
246
+ if (!slice) return;
247
+ const { config } = resolveReplicationConfig(b, { endpoint: slice.endpoint });
248
+ if (!config) continue;
249
+ const target = replicationTarget(config.endpoint, slice.collection);
250
+ if (mode === "once" && await hasSynced(db, target)) continue;
251
+ if (cancelled) return;
252
+ try {
253
+ await replicate(db, config, slice.collection, "pull");
254
+ } catch {
255
+ }
256
+ }
257
+ };
258
+ const lanes = Math.min(concurrency, queue.length);
259
+ await Promise.all(Array.from({ length: lanes }, () => worker()));
260
+ }
261
+ return () => {
262
+ cancelled = true;
263
+ cancelSchedule();
264
+ };
265
+ }, [db, sig]);
266
+ return null;
267
+ }
268
+
269
+ // src/useQuery.ts
270
+ import { useCallback as useCallback3, useEffect as useEffect3, useRef as useRef4, useState as useState2 } from "react";
271
+ function useQuery(options) {
272
+ const { collection, filter, source = "local-first" } = options;
273
+ const networked = source !== "local-only";
274
+ const db = useTalaDB();
275
+ const col = useCollection(collection);
276
+ const read = useFind(col, filter);
277
+ const { config, pollMs } = useReplicationConfig({
278
+ endpoint: options.endpoint,
279
+ getAuth: options.getAuth,
280
+ fetch: options.fetch,
281
+ paths: options.paths,
282
+ pollMs: options.pollMs
283
+ });
284
+ const configRef = useRef4(config);
285
+ configRef.current = config;
286
+ const [syncing, setSyncing] = useState2(false);
287
+ const [syncError, setSyncError] = useState2(null);
288
+ const [firstSyncDone, setFirstSyncDone] = useState2(false);
289
+ const endpoint = config?.endpoint;
290
+ const refetch = useCallback3(async () => {
291
+ const cfg = configRef.current;
292
+ if (!networked || !cfg) return;
293
+ setSyncing(true);
294
+ setSyncError(null);
295
+ try {
296
+ await replicate(db, cfg, collection, "pull");
297
+ } catch (e) {
298
+ setSyncError(e);
299
+ } finally {
300
+ setSyncing(false);
301
+ setFirstSyncDone(true);
302
+ }
303
+ }, [db, collection, networked, endpoint]);
304
+ useEffect3(() => {
305
+ if (!networked) return;
306
+ void refetch();
307
+ if (pollMs > 0) {
308
+ const id = setInterval(() => void refetch(), pollMs);
309
+ return () => clearInterval(id);
310
+ }
311
+ return void 0;
312
+ }, [refetch, networked, pollMs]);
313
+ if (networked && !config) {
314
+ throw new Error(
315
+ `useQuery({ collection: '${collection}' }) needs an endpoint for source '${source}'. Wrap the tree in <ReplicationProvider endpoint="\u2026">, pass { endpoint }, or use source: "local-only".`
316
+ );
317
+ }
318
+ const loading = source === "remote-first" ? read.loading || !firstSyncDone : read.loading;
319
+ return { data: read.data, loading, error: read.error, syncing, syncError, refetch };
320
+ }
321
+
322
+ // src/useQueries.ts
323
+ import { useEffect as useEffect4, useRef as useRef5, useState as useState3 } from "react";
324
+ var NOOP_REFETCH = async () => {
325
+ };
326
+ function emptyResult() {
327
+ return { data: [], loading: true, error: null, syncing: false, syncError: null, refetch: NOOP_REFETCH };
328
+ }
329
+ function useQueries(queries) {
330
+ const db = useTalaDB();
331
+ const base = useReplicationBase();
332
+ for (const q of queries) {
333
+ const networked = (q.source ?? "local-first") !== "local-only";
334
+ if (networked && !(q.endpoint ?? base?.endpoint)) {
335
+ throw new Error(
336
+ `useQueries: the query for '${q.collection}' needs an endpoint for source '${q.source ?? "local-first"}'. Provide <ReplicationProvider endpoint="\u2026">, pass { endpoint }, or use source: "local-only".`
337
+ );
338
+ }
339
+ }
340
+ const sig = JSON.stringify(
341
+ queries.map((q) => ({
342
+ collection: q.collection,
343
+ filter: q.filter ?? null,
344
+ source: q.source ?? "local-first",
345
+ endpoint: q.endpoint ?? null,
346
+ pollMs: q.pollMs ?? null
347
+ }))
348
+ );
349
+ const queriesRef = useRef5(queries);
350
+ queriesRef.current = queries;
351
+ const baseRef = useRef5(base);
352
+ baseRef.current = base;
353
+ const [results, setResults] = useState3(
354
+ () => queries.map(() => emptyResult())
355
+ );
356
+ useEffect4(() => {
357
+ const qs = queriesRef.current;
358
+ const b = baseRef.current;
359
+ let cancelled = false;
360
+ const setAt = (i, fn) => {
361
+ setResults((prev) => {
362
+ if (i >= prev.length) return prev;
363
+ const copy = prev.slice();
364
+ copy[i] = fn(copy[i]);
365
+ return copy;
366
+ });
367
+ };
368
+ const resolved = qs.map((q, i) => {
369
+ const { config } = resolveReplicationConfig(b, {
370
+ endpoint: q.endpoint,
371
+ getAuth: q.getAuth,
372
+ fetch: q.fetch,
373
+ paths: q.paths,
374
+ pollMs: q.pollMs
375
+ });
376
+ const networked = (q.source ?? "local-first") !== "local-only";
377
+ const pollMs = q.pollMs ?? b?.pollMs ?? 0;
378
+ const refetch = async () => {
379
+ if (!networked || !config) return;
380
+ setAt(i, (r) => ({ ...r, syncing: true, syncError: null }));
381
+ try {
382
+ await replicate(db, config, q.collection, "pull");
383
+ } catch (e) {
384
+ if (!cancelled) setAt(i, (r) => ({ ...r, syncError: e }));
385
+ } finally {
386
+ if (!cancelled) setAt(i, (r) => ({ ...r, syncing: false }));
387
+ }
388
+ };
389
+ return { config, networked, pollMs, refetch };
390
+ });
391
+ setResults(
392
+ qs.map((_q, i) => ({
393
+ data: [],
394
+ loading: true,
395
+ error: null,
396
+ syncing: false,
397
+ syncError: null,
398
+ refetch: resolved[i].refetch
399
+ }))
400
+ );
401
+ const unsubs = qs.map((q, i) => {
402
+ const col = db.collection(q.collection);
403
+ return col.subscribe(
404
+ q.filter ?? {},
405
+ (docs) => {
406
+ if (!cancelled) setAt(i, (r) => ({ ...r, data: docs, loading: false, error: null }));
407
+ },
408
+ (error) => {
409
+ if (!cancelled) setAt(i, (r) => ({ ...r, loading: false, error }));
410
+ }
411
+ );
412
+ });
413
+ const intervals = [];
414
+ resolved.forEach((res) => {
415
+ if (!res.networked || !res.config) return;
416
+ void res.refetch();
417
+ if (res.pollMs > 0) intervals.push(setInterval(() => void res.refetch(), res.pollMs));
418
+ });
419
+ return () => {
420
+ cancelled = true;
421
+ unsubs.forEach((u) => u());
422
+ intervals.forEach((id) => clearInterval(id));
423
+ };
424
+ }, [db, sig]);
425
+ return queries.map((_q, i) => results[i] ?? emptyResult());
426
+ }
427
+
428
+ // src/useMutation.ts
429
+ import { useCallback as useCallback4, useEffect as useEffect5, useRef as useRef6, useState as useState4 } from "react";
430
+ function useMutation(options) {
431
+ const { collection, direction = "push", drainOnMount = true } = options;
432
+ const db = useTalaDB();
433
+ const col = useCollection(collection);
434
+ const { config } = useReplicationConfig({
435
+ endpoint: options.endpoint,
436
+ getAuth: options.getAuth,
437
+ fetch: options.fetch,
438
+ paths: options.paths
439
+ });
440
+ const configRef = useRef6(config);
441
+ configRef.current = config;
442
+ const [pending, setPending] = useState4(false);
443
+ const [error, setError] = useState4(null);
444
+ const endpoint = config?.endpoint;
445
+ const applyLocal = useCallback4(
446
+ async (op) => {
447
+ switch (op.type) {
448
+ case "insert":
449
+ await col.insert(op.doc);
450
+ return;
451
+ case "update":
452
+ await col.updateOne(op.where, { $set: op.set });
453
+ return;
454
+ case "delete":
455
+ await col.deleteOne(op.where);
456
+ return;
457
+ }
458
+ },
459
+ [col]
460
+ );
461
+ const drain = useCallback4(async () => {
462
+ const cfg = configRef.current;
463
+ if (!cfg) return;
464
+ await replicateWithRetry(db, cfg, collection, direction);
465
+ }, [db, collection, direction, endpoint]);
466
+ const mutateAsync = useCallback4(
467
+ async (op) => {
468
+ setPending(true);
469
+ setError(null);
470
+ try {
471
+ await applyLocal(op);
472
+ await drain();
473
+ } catch (e) {
474
+ setError(e);
475
+ throw e;
476
+ } finally {
477
+ setPending(false);
478
+ }
479
+ },
480
+ [applyLocal, drain]
481
+ );
482
+ const mutate = useCallback4(
483
+ (op) => {
484
+ void mutateAsync(op).catch(() => {
485
+ });
486
+ },
487
+ [mutateAsync]
488
+ );
489
+ useEffect5(() => {
490
+ if (!drainOnMount || !configRef.current) return;
491
+ void drain().catch(() => {
492
+ });
493
+ }, [drain, drainOnMount]);
494
+ if (!config) {
495
+ throw new Error(
496
+ `useMutation({ collection: '${collection}' }) needs an endpoint. Wrap the tree in <ReplicationProvider endpoint="\u2026"> or pass { endpoint }.`
497
+ );
498
+ }
499
+ return { mutate, mutateAsync, pending, error };
500
+ }
63
501
  export {
502
+ ReplicationProvider,
64
503
  TalaDBProvider,
65
504
  useCollection,
66
505
  useFind,
67
506
  useFindOne,
507
+ useMutation,
508
+ useQueries,
509
+ useQuery,
510
+ useReplicationConfig,
68
511
  useTalaDB
69
512
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@taladb/react",
3
- "version": "0.8.4",
3
+ "version": "0.9.1",
4
4
  "description": "React hooks for TalaDB — useFind, useFindOne, and useCollection for React and React Native",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "peerDependencies": {
43
43
  "react": ">=18.0.0",
44
- "taladb": "^0.8.4"
44
+ "taladb": "^0.9.1"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@testing-library/react": "^16.0.0",
@@ -53,7 +53,7 @@
53
53
  "tsup": "^8.0.0",
54
54
  "typescript": "^5.9.3",
55
55
  "vitest": "^3.2.0",
56
- "taladb": "0.8.4"
56
+ "taladb": "0.9.1"
57
57
  },
58
58
  "scripts": {
59
59
  "build": "tsup",