@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.d.mts +273 -15
- package/dist/index.d.ts +273 -15
- package/dist/index.js +459 -8
- package/dist/index.mjs +453 -10
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
'use client';
|
|
1
2
|
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
2
4
|
var __defProp = Object.defineProperty;
|
|
3
5
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
6
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
8
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
9
|
var __export = (target, all) => {
|
|
7
10
|
for (var name in all)
|
|
@@ -15,15 +18,28 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
18
|
}
|
|
16
19
|
return to;
|
|
17
20
|
};
|
|
21
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
22
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
23
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
24
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
25
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
26
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
27
|
+
mod
|
|
28
|
+
));
|
|
18
29
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
30
|
|
|
20
31
|
// src/index.ts
|
|
21
32
|
var index_exports = {};
|
|
22
33
|
__export(index_exports, {
|
|
34
|
+
ReplicationProvider: () => ReplicationProvider,
|
|
23
35
|
TalaDBProvider: () => TalaDBProvider,
|
|
24
36
|
useCollection: () => useCollection,
|
|
25
37
|
useFind: () => useFind,
|
|
26
38
|
useFindOne: () => useFindOne,
|
|
39
|
+
useMutation: () => useMutation,
|
|
40
|
+
useQueries: () => useQueries,
|
|
41
|
+
useQuery: () => useQuery,
|
|
42
|
+
useReplicationConfig: () => useReplicationConfig,
|
|
27
43
|
useTalaDB: () => useTalaDB
|
|
28
44
|
});
|
|
29
45
|
module.exports = __toCommonJS(index_exports);
|
|
@@ -32,13 +48,49 @@ module.exports = __toCommonJS(index_exports);
|
|
|
32
48
|
var import_react = require("react");
|
|
33
49
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
34
50
|
var TalaDBContext = (0, import_react.createContext)(null);
|
|
35
|
-
function TalaDBProvider(
|
|
51
|
+
function TalaDBProvider(props) {
|
|
52
|
+
if ("db" in props && props.db) {
|
|
53
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TalaDBContext.Provider, { value: props.db, children: props.children });
|
|
54
|
+
}
|
|
55
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(NamedProvider, { ...props });
|
|
56
|
+
}
|
|
57
|
+
function NamedProvider({
|
|
58
|
+
name,
|
|
59
|
+
options,
|
|
60
|
+
fallback = null,
|
|
61
|
+
children
|
|
62
|
+
}) {
|
|
63
|
+
const [db, setDb] = (0, import_react.useState)(null);
|
|
64
|
+
const [error, setError] = (0, import_react.useState)(null);
|
|
65
|
+
const optionsKey = JSON.stringify(options ?? null);
|
|
66
|
+
(0, import_react.useEffect)(() => {
|
|
67
|
+
setError(null);
|
|
68
|
+
let cancelled = false;
|
|
69
|
+
let opened = null;
|
|
70
|
+
import("taladb").then(({ openDB }) => openDB(name, options)).then((instance) => {
|
|
71
|
+
if (cancelled) {
|
|
72
|
+
void instance.close();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
opened = instance;
|
|
76
|
+
setDb(instance);
|
|
77
|
+
}).catch((e) => {
|
|
78
|
+
if (!cancelled) setError(e);
|
|
79
|
+
});
|
|
80
|
+
return () => {
|
|
81
|
+
cancelled = true;
|
|
82
|
+
if (opened) void opened.close();
|
|
83
|
+
setDb(null);
|
|
84
|
+
};
|
|
85
|
+
}, [name, optionsKey]);
|
|
86
|
+
if (error !== null) throw error;
|
|
87
|
+
if (db === null) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: fallback });
|
|
36
88
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TalaDBContext.Provider, { value: db, children });
|
|
37
89
|
}
|
|
38
90
|
function useTalaDB() {
|
|
39
91
|
const db = (0, import_react.useContext)(TalaDBContext);
|
|
40
92
|
if (db === null) {
|
|
41
|
-
throw new Error(
|
|
93
|
+
throw new Error('useTalaDB must be used inside <TalaDBProvider db={...}> or <TalaDBProvider name="...">');
|
|
42
94
|
}
|
|
43
95
|
return db;
|
|
44
96
|
}
|
|
@@ -53,13 +105,16 @@ function useCollection(name) {
|
|
|
53
105
|
// src/useFind.ts
|
|
54
106
|
var import_react3 = require("react");
|
|
55
107
|
function useFind(collection, filter) {
|
|
56
|
-
const snapshotRef = (0, import_react3.useRef)({ data: [], loading: true });
|
|
108
|
+
const snapshotRef = (0, import_react3.useRef)({ data: [], loading: true, error: null });
|
|
57
109
|
const filterKey = JSON.stringify(filter ?? null);
|
|
58
110
|
const subscribe = (0, import_react3.useCallback)(
|
|
59
111
|
(notify) => {
|
|
60
|
-
snapshotRef.current = { data: snapshotRef.current.data, loading: true };
|
|
112
|
+
snapshotRef.current = { data: snapshotRef.current.data, loading: true, error: null };
|
|
61
113
|
return collection.subscribe(filter ?? {}, (docs) => {
|
|
62
|
-
snapshotRef.current = { data: docs, loading: false };
|
|
114
|
+
snapshotRef.current = { data: docs, loading: false, error: null };
|
|
115
|
+
notify();
|
|
116
|
+
}, (error) => {
|
|
117
|
+
snapshotRef.current = { ...snapshotRef.current, loading: false, error };
|
|
63
118
|
notify();
|
|
64
119
|
});
|
|
65
120
|
},
|
|
@@ -74,13 +129,16 @@ function useFind(collection, filter) {
|
|
|
74
129
|
// src/useFindOne.ts
|
|
75
130
|
var import_react4 = require("react");
|
|
76
131
|
function useFindOne(collection, filter) {
|
|
77
|
-
const snapshotRef = (0, import_react4.useRef)({ data: null, loading: true });
|
|
132
|
+
const snapshotRef = (0, import_react4.useRef)({ data: null, loading: true, error: null });
|
|
78
133
|
const filterKey = JSON.stringify(filter);
|
|
79
134
|
const subscribe = (0, import_react4.useCallback)(
|
|
80
135
|
(notify) => {
|
|
81
|
-
snapshotRef.current = { data: snapshotRef.current.data, loading: true };
|
|
136
|
+
snapshotRef.current = { data: snapshotRef.current.data, loading: true, error: null };
|
|
82
137
|
return collection.subscribe(filter, (docs) => {
|
|
83
|
-
snapshotRef.current = { data: docs[0] ?? null, loading: false };
|
|
138
|
+
snapshotRef.current = { data: docs[0] ?? null, loading: false, error: null };
|
|
139
|
+
notify();
|
|
140
|
+
}, (error) => {
|
|
141
|
+
snapshotRef.current = { ...snapshotRef.current, loading: false, error };
|
|
84
142
|
notify();
|
|
85
143
|
});
|
|
86
144
|
},
|
|
@@ -90,11 +148,404 @@ function useFindOne(collection, filter) {
|
|
|
90
148
|
const getSnapshot = (0, import_react4.useCallback)(() => snapshotRef.current, []);
|
|
91
149
|
return (0, import_react4.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
|
|
92
150
|
}
|
|
151
|
+
|
|
152
|
+
// src/replication/config.tsx
|
|
153
|
+
var import_react5 = require("react");
|
|
154
|
+
|
|
155
|
+
// src/replication/engine.ts
|
|
156
|
+
var import_taladb = require("taladb");
|
|
157
|
+
function replicationTarget(endpoint, collection) {
|
|
158
|
+
return `${endpoint}::${collection}`;
|
|
159
|
+
}
|
|
160
|
+
async function buildAdapter(config) {
|
|
161
|
+
const headers = config.getAuth ? await config.getAuth() : void 0;
|
|
162
|
+
return new import_taladb.HttpSyncAdapter({
|
|
163
|
+
endpoint: config.endpoint,
|
|
164
|
+
headers,
|
|
165
|
+
fetch: config.fetch,
|
|
166
|
+
paths: config.paths
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
var inflight = /* @__PURE__ */ new Map();
|
|
170
|
+
function inflightKey(endpoint, collection, direction) {
|
|
171
|
+
return `${endpoint}::${collection}::${direction}`;
|
|
172
|
+
}
|
|
173
|
+
function replicate(db, config, collection, direction) {
|
|
174
|
+
const key = inflightKey(config.endpoint, collection, direction);
|
|
175
|
+
const existing = inflight.get(key);
|
|
176
|
+
if (existing) return existing;
|
|
177
|
+
const pass = (async () => {
|
|
178
|
+
const adapter = await buildAdapter(config);
|
|
179
|
+
await db.sync(adapter, {
|
|
180
|
+
collections: [collection],
|
|
181
|
+
direction,
|
|
182
|
+
target: replicationTarget(config.endpoint, collection)
|
|
183
|
+
});
|
|
184
|
+
})().finally(() => {
|
|
185
|
+
inflight.delete(key);
|
|
186
|
+
});
|
|
187
|
+
inflight.set(key, pass);
|
|
188
|
+
return pass;
|
|
189
|
+
}
|
|
190
|
+
var BACKOFFS_MS = [200, 400, 800];
|
|
191
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
192
|
+
async function replicateWithRetry(db, config, collection, direction) {
|
|
193
|
+
let lastError;
|
|
194
|
+
for (let attempt = 0; attempt <= BACKOFFS_MS.length; attempt++) {
|
|
195
|
+
try {
|
|
196
|
+
await replicate(db, config, collection, direction);
|
|
197
|
+
return;
|
|
198
|
+
} catch (error) {
|
|
199
|
+
lastError = error;
|
|
200
|
+
if (attempt < BACKOFFS_MS.length) await sleep(BACKOFFS_MS[attempt]);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
throw lastError;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// src/replication/config.tsx
|
|
207
|
+
var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
208
|
+
var ReplicationContext = (0, import_react5.createContext)(null);
|
|
209
|
+
function ReplicationProvider({ children, ...config }) {
|
|
210
|
+
const key = `${config.endpoint}|${config.pollMs ?? ""}|${JSON.stringify(config.paths ?? null)}|${JSON.stringify(config.prefetch ?? null)}|${config.prefetchMode ?? ""}|${config.prefetchConcurrency ?? ""}`;
|
|
211
|
+
const value = (0, import_react5.useMemo)(
|
|
212
|
+
() => config,
|
|
213
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
214
|
+
[key]
|
|
215
|
+
);
|
|
216
|
+
return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(ReplicationContext.Provider, { value, children: [
|
|
217
|
+
value.prefetch && value.prefetch.length > 0 ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(PrefetchRunner, {}) : null,
|
|
218
|
+
children
|
|
219
|
+
] });
|
|
220
|
+
}
|
|
221
|
+
function resolveReplicationConfig(base, overrides) {
|
|
222
|
+
const endpoint = overrides?.endpoint ?? base?.endpoint;
|
|
223
|
+
const pollMs = overrides?.pollMs ?? base?.pollMs ?? 0;
|
|
224
|
+
if (!endpoint) return { config: null, pollMs };
|
|
225
|
+
return {
|
|
226
|
+
config: {
|
|
227
|
+
endpoint,
|
|
228
|
+
getAuth: overrides?.getAuth ?? base?.getAuth,
|
|
229
|
+
fetch: overrides?.fetch ?? base?.fetch,
|
|
230
|
+
paths: overrides?.paths ?? base?.paths
|
|
231
|
+
},
|
|
232
|
+
pollMs
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
function useReplicationBase() {
|
|
236
|
+
return (0, import_react5.useContext)(ReplicationContext);
|
|
237
|
+
}
|
|
238
|
+
function useReplicationConfig(overrides) {
|
|
239
|
+
return resolveReplicationConfig((0, import_react5.useContext)(ReplicationContext), overrides);
|
|
240
|
+
}
|
|
241
|
+
var CURSOR_COLLECTION = "__taladb_sync";
|
|
242
|
+
function normalizePrefetch(entries) {
|
|
243
|
+
return (entries ?? []).map((e) => typeof e === "string" ? { collection: e } : e);
|
|
244
|
+
}
|
|
245
|
+
var idleScheduler = (fn) => {
|
|
246
|
+
const g = globalThis;
|
|
247
|
+
if (typeof g.requestIdleCallback === "function") {
|
|
248
|
+
const id2 = g.requestIdleCallback(fn, { timeout: 2e3 });
|
|
249
|
+
return () => g.cancelIdleCallback?.(id2);
|
|
250
|
+
}
|
|
251
|
+
const id = setTimeout(fn, 0);
|
|
252
|
+
return () => clearTimeout(id);
|
|
253
|
+
};
|
|
254
|
+
var schedule = idleScheduler;
|
|
255
|
+
async function hasSynced(db, target) {
|
|
256
|
+
try {
|
|
257
|
+
const doc = await db.collection(CURSOR_COLLECTION).findOne({ target });
|
|
258
|
+
return doc != null;
|
|
259
|
+
} catch {
|
|
260
|
+
return false;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function PrefetchRunner() {
|
|
264
|
+
const db = useTalaDB();
|
|
265
|
+
const base = useReplicationBase();
|
|
266
|
+
const slices = normalizePrefetch(base?.prefetch);
|
|
267
|
+
const mode = base?.prefetchMode ?? "once";
|
|
268
|
+
const concurrency = Math.max(1, base?.prefetchConcurrency ?? 2);
|
|
269
|
+
const baseRef = (0, import_react5.useRef)(base);
|
|
270
|
+
baseRef.current = base;
|
|
271
|
+
const sig = JSON.stringify({ slices, mode, concurrency, endpoint: base?.endpoint ?? null });
|
|
272
|
+
(0, import_react5.useEffect)(() => {
|
|
273
|
+
if (slices.length === 0) return void 0;
|
|
274
|
+
let cancelled = false;
|
|
275
|
+
const cancelSchedule = schedule(() => {
|
|
276
|
+
void run();
|
|
277
|
+
});
|
|
278
|
+
async function run() {
|
|
279
|
+
const b = baseRef.current;
|
|
280
|
+
const queue = normalizePrefetch(b?.prefetch);
|
|
281
|
+
const worker = async () => {
|
|
282
|
+
while (!cancelled) {
|
|
283
|
+
const slice = queue.shift();
|
|
284
|
+
if (!slice) return;
|
|
285
|
+
const { config } = resolveReplicationConfig(b, { endpoint: slice.endpoint });
|
|
286
|
+
if (!config) continue;
|
|
287
|
+
const target = replicationTarget(config.endpoint, slice.collection);
|
|
288
|
+
if (mode === "once" && await hasSynced(db, target)) continue;
|
|
289
|
+
if (cancelled) return;
|
|
290
|
+
try {
|
|
291
|
+
await replicate(db, config, slice.collection, "pull");
|
|
292
|
+
} catch {
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
const lanes = Math.min(concurrency, queue.length);
|
|
297
|
+
await Promise.all(Array.from({ length: lanes }, () => worker()));
|
|
298
|
+
}
|
|
299
|
+
return () => {
|
|
300
|
+
cancelled = true;
|
|
301
|
+
cancelSchedule();
|
|
302
|
+
};
|
|
303
|
+
}, [db, sig]);
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// src/useQuery.ts
|
|
308
|
+
var import_react6 = require("react");
|
|
309
|
+
function useQuery(options) {
|
|
310
|
+
const { collection, filter, source = "local-first" } = options;
|
|
311
|
+
const networked = source !== "local-only";
|
|
312
|
+
const db = useTalaDB();
|
|
313
|
+
const col = useCollection(collection);
|
|
314
|
+
const read = useFind(col, filter);
|
|
315
|
+
const { config, pollMs } = useReplicationConfig({
|
|
316
|
+
endpoint: options.endpoint,
|
|
317
|
+
getAuth: options.getAuth,
|
|
318
|
+
fetch: options.fetch,
|
|
319
|
+
paths: options.paths,
|
|
320
|
+
pollMs: options.pollMs
|
|
321
|
+
});
|
|
322
|
+
const configRef = (0, import_react6.useRef)(config);
|
|
323
|
+
configRef.current = config;
|
|
324
|
+
const [syncing, setSyncing] = (0, import_react6.useState)(false);
|
|
325
|
+
const [syncError, setSyncError] = (0, import_react6.useState)(null);
|
|
326
|
+
const [firstSyncDone, setFirstSyncDone] = (0, import_react6.useState)(false);
|
|
327
|
+
const endpoint = config?.endpoint;
|
|
328
|
+
const refetch = (0, import_react6.useCallback)(async () => {
|
|
329
|
+
const cfg = configRef.current;
|
|
330
|
+
if (!networked || !cfg) return;
|
|
331
|
+
setSyncing(true);
|
|
332
|
+
setSyncError(null);
|
|
333
|
+
try {
|
|
334
|
+
await replicate(db, cfg, collection, "pull");
|
|
335
|
+
} catch (e) {
|
|
336
|
+
setSyncError(e);
|
|
337
|
+
} finally {
|
|
338
|
+
setSyncing(false);
|
|
339
|
+
setFirstSyncDone(true);
|
|
340
|
+
}
|
|
341
|
+
}, [db, collection, networked, endpoint]);
|
|
342
|
+
(0, import_react6.useEffect)(() => {
|
|
343
|
+
if (!networked) return;
|
|
344
|
+
void refetch();
|
|
345
|
+
if (pollMs > 0) {
|
|
346
|
+
const id = setInterval(() => void refetch(), pollMs);
|
|
347
|
+
return () => clearInterval(id);
|
|
348
|
+
}
|
|
349
|
+
return void 0;
|
|
350
|
+
}, [refetch, networked, pollMs]);
|
|
351
|
+
if (networked && !config) {
|
|
352
|
+
throw new Error(
|
|
353
|
+
`useQuery({ collection: '${collection}' }) needs an endpoint for source '${source}'. Wrap the tree in <ReplicationProvider endpoint="\u2026">, pass { endpoint }, or use source: "local-only".`
|
|
354
|
+
);
|
|
355
|
+
}
|
|
356
|
+
const loading = source === "remote-first" ? read.loading || !firstSyncDone : read.loading;
|
|
357
|
+
return { data: read.data, loading, error: read.error, syncing, syncError, refetch };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// src/useQueries.ts
|
|
361
|
+
var import_react7 = require("react");
|
|
362
|
+
var NOOP_REFETCH = async () => {
|
|
363
|
+
};
|
|
364
|
+
function emptyResult() {
|
|
365
|
+
return { data: [], loading: true, error: null, syncing: false, syncError: null, refetch: NOOP_REFETCH };
|
|
366
|
+
}
|
|
367
|
+
function useQueries(queries) {
|
|
368
|
+
const db = useTalaDB();
|
|
369
|
+
const base = useReplicationBase();
|
|
370
|
+
for (const q of queries) {
|
|
371
|
+
const networked = (q.source ?? "local-first") !== "local-only";
|
|
372
|
+
if (networked && !(q.endpoint ?? base?.endpoint)) {
|
|
373
|
+
throw new Error(
|
|
374
|
+
`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".`
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
const sig = JSON.stringify(
|
|
379
|
+
queries.map((q) => ({
|
|
380
|
+
collection: q.collection,
|
|
381
|
+
filter: q.filter ?? null,
|
|
382
|
+
source: q.source ?? "local-first",
|
|
383
|
+
endpoint: q.endpoint ?? null,
|
|
384
|
+
pollMs: q.pollMs ?? null
|
|
385
|
+
}))
|
|
386
|
+
);
|
|
387
|
+
const queriesRef = (0, import_react7.useRef)(queries);
|
|
388
|
+
queriesRef.current = queries;
|
|
389
|
+
const baseRef = (0, import_react7.useRef)(base);
|
|
390
|
+
baseRef.current = base;
|
|
391
|
+
const [results, setResults] = (0, import_react7.useState)(
|
|
392
|
+
() => queries.map(() => emptyResult())
|
|
393
|
+
);
|
|
394
|
+
(0, import_react7.useEffect)(() => {
|
|
395
|
+
const qs = queriesRef.current;
|
|
396
|
+
const b = baseRef.current;
|
|
397
|
+
let cancelled = false;
|
|
398
|
+
const setAt = (i, fn) => {
|
|
399
|
+
setResults((prev) => {
|
|
400
|
+
if (i >= prev.length) return prev;
|
|
401
|
+
const copy = prev.slice();
|
|
402
|
+
copy[i] = fn(copy[i]);
|
|
403
|
+
return copy;
|
|
404
|
+
});
|
|
405
|
+
};
|
|
406
|
+
const resolved = qs.map((q, i) => {
|
|
407
|
+
const { config } = resolveReplicationConfig(b, {
|
|
408
|
+
endpoint: q.endpoint,
|
|
409
|
+
getAuth: q.getAuth,
|
|
410
|
+
fetch: q.fetch,
|
|
411
|
+
paths: q.paths,
|
|
412
|
+
pollMs: q.pollMs
|
|
413
|
+
});
|
|
414
|
+
const networked = (q.source ?? "local-first") !== "local-only";
|
|
415
|
+
const pollMs = q.pollMs ?? b?.pollMs ?? 0;
|
|
416
|
+
const refetch = async () => {
|
|
417
|
+
if (!networked || !config) return;
|
|
418
|
+
setAt(i, (r) => ({ ...r, syncing: true, syncError: null }));
|
|
419
|
+
try {
|
|
420
|
+
await replicate(db, config, q.collection, "pull");
|
|
421
|
+
} catch (e) {
|
|
422
|
+
if (!cancelled) setAt(i, (r) => ({ ...r, syncError: e }));
|
|
423
|
+
} finally {
|
|
424
|
+
if (!cancelled) setAt(i, (r) => ({ ...r, syncing: false }));
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
return { config, networked, pollMs, refetch };
|
|
428
|
+
});
|
|
429
|
+
setResults(
|
|
430
|
+
qs.map((_q, i) => ({
|
|
431
|
+
data: [],
|
|
432
|
+
loading: true,
|
|
433
|
+
error: null,
|
|
434
|
+
syncing: false,
|
|
435
|
+
syncError: null,
|
|
436
|
+
refetch: resolved[i].refetch
|
|
437
|
+
}))
|
|
438
|
+
);
|
|
439
|
+
const unsubs = qs.map((q, i) => {
|
|
440
|
+
const col = db.collection(q.collection);
|
|
441
|
+
return col.subscribe(
|
|
442
|
+
q.filter ?? {},
|
|
443
|
+
(docs) => {
|
|
444
|
+
if (!cancelled) setAt(i, (r) => ({ ...r, data: docs, loading: false, error: null }));
|
|
445
|
+
},
|
|
446
|
+
(error) => {
|
|
447
|
+
if (!cancelled) setAt(i, (r) => ({ ...r, loading: false, error }));
|
|
448
|
+
}
|
|
449
|
+
);
|
|
450
|
+
});
|
|
451
|
+
const intervals = [];
|
|
452
|
+
resolved.forEach((res) => {
|
|
453
|
+
if (!res.networked || !res.config) return;
|
|
454
|
+
void res.refetch();
|
|
455
|
+
if (res.pollMs > 0) intervals.push(setInterval(() => void res.refetch(), res.pollMs));
|
|
456
|
+
});
|
|
457
|
+
return () => {
|
|
458
|
+
cancelled = true;
|
|
459
|
+
unsubs.forEach((u) => u());
|
|
460
|
+
intervals.forEach((id) => clearInterval(id));
|
|
461
|
+
};
|
|
462
|
+
}, [db, sig]);
|
|
463
|
+
return queries.map((_q, i) => results[i] ?? emptyResult());
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// src/useMutation.ts
|
|
467
|
+
var import_react8 = require("react");
|
|
468
|
+
function useMutation(options) {
|
|
469
|
+
const { collection, direction = "push", drainOnMount = true } = options;
|
|
470
|
+
const db = useTalaDB();
|
|
471
|
+
const col = useCollection(collection);
|
|
472
|
+
const { config } = useReplicationConfig({
|
|
473
|
+
endpoint: options.endpoint,
|
|
474
|
+
getAuth: options.getAuth,
|
|
475
|
+
fetch: options.fetch,
|
|
476
|
+
paths: options.paths
|
|
477
|
+
});
|
|
478
|
+
const configRef = (0, import_react8.useRef)(config);
|
|
479
|
+
configRef.current = config;
|
|
480
|
+
const [pending, setPending] = (0, import_react8.useState)(false);
|
|
481
|
+
const [error, setError] = (0, import_react8.useState)(null);
|
|
482
|
+
const endpoint = config?.endpoint;
|
|
483
|
+
const applyLocal = (0, import_react8.useCallback)(
|
|
484
|
+
async (op) => {
|
|
485
|
+
switch (op.type) {
|
|
486
|
+
case "insert":
|
|
487
|
+
await col.insert(op.doc);
|
|
488
|
+
return;
|
|
489
|
+
case "update":
|
|
490
|
+
await col.updateOne(op.where, { $set: op.set });
|
|
491
|
+
return;
|
|
492
|
+
case "delete":
|
|
493
|
+
await col.deleteOne(op.where);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
},
|
|
497
|
+
[col]
|
|
498
|
+
);
|
|
499
|
+
const drain = (0, import_react8.useCallback)(async () => {
|
|
500
|
+
const cfg = configRef.current;
|
|
501
|
+
if (!cfg) return;
|
|
502
|
+
await replicateWithRetry(db, cfg, collection, direction);
|
|
503
|
+
}, [db, collection, direction, endpoint]);
|
|
504
|
+
const mutateAsync = (0, import_react8.useCallback)(
|
|
505
|
+
async (op) => {
|
|
506
|
+
setPending(true);
|
|
507
|
+
setError(null);
|
|
508
|
+
try {
|
|
509
|
+
await applyLocal(op);
|
|
510
|
+
await drain();
|
|
511
|
+
} catch (e) {
|
|
512
|
+
setError(e);
|
|
513
|
+
throw e;
|
|
514
|
+
} finally {
|
|
515
|
+
setPending(false);
|
|
516
|
+
}
|
|
517
|
+
},
|
|
518
|
+
[applyLocal, drain]
|
|
519
|
+
);
|
|
520
|
+
const mutate = (0, import_react8.useCallback)(
|
|
521
|
+
(op) => {
|
|
522
|
+
void mutateAsync(op).catch(() => {
|
|
523
|
+
});
|
|
524
|
+
},
|
|
525
|
+
[mutateAsync]
|
|
526
|
+
);
|
|
527
|
+
(0, import_react8.useEffect)(() => {
|
|
528
|
+
if (!drainOnMount || !configRef.current) return;
|
|
529
|
+
void drain().catch(() => {
|
|
530
|
+
});
|
|
531
|
+
}, [drain, drainOnMount]);
|
|
532
|
+
if (!config) {
|
|
533
|
+
throw new Error(
|
|
534
|
+
`useMutation({ collection: '${collection}' }) needs an endpoint. Wrap the tree in <ReplicationProvider endpoint="\u2026"> or pass { endpoint }.`
|
|
535
|
+
);
|
|
536
|
+
}
|
|
537
|
+
return { mutate, mutateAsync, pending, error };
|
|
538
|
+
}
|
|
93
539
|
// Annotate the CommonJS export names for ESM import in node:
|
|
94
540
|
0 && (module.exports = {
|
|
541
|
+
ReplicationProvider,
|
|
95
542
|
TalaDBProvider,
|
|
96
543
|
useCollection,
|
|
97
544
|
useFind,
|
|
98
545
|
useFindOne,
|
|
546
|
+
useMutation,
|
|
547
|
+
useQueries,
|
|
548
|
+
useQuery,
|
|
549
|
+
useReplicationConfig,
|
|
99
550
|
useTalaDB
|
|
100
551
|
});
|