@rpcbase/client 0.384.0 → 0.386.0

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,5 +1,6 @@
1
1
  import { createContext, useContext, useId, useMemo, useState, useRef, useEffect } from "react";
2
2
  import { jsx } from "react/jsx-runtime";
3
+ import { c } from "react/compiler-runtime";
3
4
  const STATIC_RPCBASE_RTS_HYDRATION_DATA_KEY = "__staticRpcbaseRtsHydrationData";
4
5
  const RtsSsrRuntimeContext = createContext(null);
5
6
  const hydrationDataStore = /* @__PURE__ */ new Map();
@@ -19,8 +20,12 @@ const normalizePageInfo$2 = (value) => {
19
20
  return {
20
21
  hasNextPage: raw.hasNextPage,
21
22
  hasPrevPage: raw.hasPrevPage,
22
- ...nextCursor ? { nextCursor } : {},
23
- ...prevCursor ? { prevCursor } : {}
23
+ ...nextCursor ? {
24
+ nextCursor
25
+ } : {},
26
+ ...prevCursor ? {
27
+ prevCursor
28
+ } : {}
24
29
  };
25
30
  };
26
31
  const parseHydrationData = (value) => {
@@ -41,7 +46,9 @@ const parseHydrationData = (value) => {
41
46
  modelName,
42
47
  queryKey,
43
48
  data: query.data,
44
- ...pageInfo ? { pageInfo } : {}
49
+ ...pageInfo ? {
50
+ pageInfo
51
+ } : {}
45
52
  });
46
53
  }
47
54
  return {
@@ -80,11 +87,22 @@ const clearHydratedRtsQueryData = () => {
80
87
  hydrationDataStore.clear();
81
88
  hydrationPageInfoStore.clear();
82
89
  };
83
- const RtsSsrRuntimeProvider = ({
84
- value,
85
- children
86
- }) => {
87
- return /* @__PURE__ */ jsx(RtsSsrRuntimeContext.Provider, { value, children });
90
+ const RtsSsrRuntimeProvider = (t0) => {
91
+ const $ = c(3);
92
+ const {
93
+ value,
94
+ children
95
+ } = t0;
96
+ let t1;
97
+ if ($[0] !== children || $[1] !== value) {
98
+ t1 = /* @__PURE__ */ jsx(RtsSsrRuntimeContext.Provider, { value, children });
99
+ $[0] = children;
100
+ $[1] = value;
101
+ $[2] = t1;
102
+ } else {
103
+ t1 = $[2];
104
+ }
105
+ return t1;
88
106
  };
89
107
  const useRtsSsrRuntime = () => {
90
108
  return useContext(RtsSsrRuntimeContext);
@@ -106,17 +124,29 @@ const ensureBrowser$1 = () => {
106
124
  throw new Error("RTS PouchDB store can only be used in the browser");
107
125
  }
108
126
  };
109
- const computeBasePrefix = ({ tenantId, appName }) => {
127
+ const computeBasePrefix = ({
128
+ tenantId,
129
+ appName
130
+ }) => {
110
131
  let prefix = "rb/";
111
132
  if (appName) prefix += `${appName}/`;
112
133
  prefix += `${tenantId}/`;
113
134
  return prefix;
114
135
  };
115
136
  const getDbNamesKey = (prefix) => `rb:rts:pouchDbs:${prefix}`;
116
- const getPrefixOverrideKey = ({ tenantId, appName }) => `rb:rts:pouchPrefix:${appName ?? ""}:${tenantId}`;
117
- const readPrefixOverride = ({ tenantId, appName }) => {
137
+ const getPrefixOverrideKey = ({
138
+ tenantId,
139
+ appName
140
+ }) => `rb:rts:pouchPrefix:${appName ?? ""}:${tenantId}`;
141
+ const readPrefixOverride = ({
142
+ tenantId,
143
+ appName
144
+ }) => {
118
145
  try {
119
- const value = window.localStorage.getItem(getPrefixOverrideKey({ tenantId, appName }));
146
+ const value = window.localStorage.getItem(getPrefixOverrideKey({
147
+ tenantId,
148
+ appName
149
+ }));
120
150
  if (!value) return null;
121
151
  if (!value.endsWith("/")) return `${value}/`;
122
152
  return value;
@@ -129,8 +159,14 @@ const getPrefix = () => {
129
159
  throw new Error("RTS PouchDB store is not configured");
130
160
  }
131
161
  if (storeConfig.prefix) return storeConfig.prefix;
132
- const basePrefix = computeBasePrefix({ tenantId: storeConfig.tenantId, appName: storeConfig.appName });
133
- const override = readPrefixOverride({ tenantId: storeConfig.tenantId, appName: storeConfig.appName });
162
+ const basePrefix = computeBasePrefix({
163
+ tenantId: storeConfig.tenantId,
164
+ appName: storeConfig.appName
165
+ });
166
+ const override = readPrefixOverride({
167
+ tenantId: storeConfig.tenantId,
168
+ appName: storeConfig.appName
169
+ });
134
170
  return override ?? basePrefix;
135
171
  };
136
172
  const loadDbNames = (prefix) => {
@@ -183,11 +219,7 @@ const getPouchDb = async () => {
183
219
  ensureBrowser$1();
184
220
  if (!pouchDbPromise) {
185
221
  pouchDbPromise = (async () => {
186
- const [core, indexedDbAdapter, findPlugin] = await Promise.all([
187
- import("pouchdb-core"),
188
- import("pouchdb-adapter-indexeddb"),
189
- import("pouchdb-find")
190
- ]);
222
+ const [core, indexedDbAdapter, findPlugin] = await Promise.all([import("pouchdb-core"), import("pouchdb-adapter-indexeddb"), import("pouchdb-find")]);
191
223
  const PouchDB = unwrapDefault(core);
192
224
  PouchDB.plugin(unwrapDefault(indexedDbAdapter));
193
225
  PouchDB.plugin(unwrapDefault(findPlugin));
@@ -216,7 +248,10 @@ const getCollection = async (modelName, options) => {
216
248
  const existing = collections.get(dbKey);
217
249
  if (existing) return existing;
218
250
  registerDbName(prefix, dbName);
219
- const db = new PouchDB(dbName, { adapter: "indexeddb", revs_limit: 1 });
251
+ const db = new PouchDB(dbName, {
252
+ adapter: "indexeddb",
253
+ revs_limit: 1
254
+ });
220
255
  collections.set(dbKey, db);
221
256
  return db;
222
257
  };
@@ -276,17 +311,21 @@ const runQuery = async ({
276
311
  query = {},
277
312
  options
278
313
  }) => {
279
- const collection = await getCollection(modelName, { uid: options.uid });
280
- const replacedQuery = replaceQueryKeys(
281
- query,
282
- (key) => key.startsWith("_") && key !== "_id" ? `${UNDERSCORE_PREFIX}${key}` : key
283
- );
314
+ const collection = await getCollection(modelName, {
315
+ uid: options.uid
316
+ });
317
+ const replacedQuery = replaceQueryKeys(query, (key) => key.startsWith("_") && key !== "_id" ? `${UNDERSCORE_PREFIX}${key}` : key);
284
318
  const limit = typeof options.limit === "number" ? Math.abs(options.limit) : DEFAULT_FIND_LIMIT;
285
- const { docs } = await collection.find({
319
+ const {
320
+ docs
321
+ } = await collection.find({
286
322
  selector: replacedQuery,
287
323
  limit
288
324
  });
289
- let mappedDocs = docs.map(({ _rev: _revIgnored, ...rest }) => remapDocFromStorage(rest));
325
+ let mappedDocs = docs.map(({
326
+ _rev: _revIgnored,
327
+ ...rest
328
+ }) => remapDocFromStorage(rest));
290
329
  if (options.projection) {
291
330
  mappedDocs = mappedDocs.filter((doc) => satisfiesProjection(doc, options.projection));
292
331
  }
@@ -311,14 +350,27 @@ const runQuery = async ({
311
350
  return 0;
312
351
  });
313
352
  }
314
- return { data: mappedDocs, context: { source: "cache" } };
353
+ return {
354
+ data: mappedDocs,
355
+ context: {
356
+ source: "cache"
357
+ }
358
+ };
315
359
  };
316
360
  const updateDocs = async (modelName, data, uid) => {
317
- const collection = await getCollection(modelName, { uid });
361
+ const collection = await getCollection(modelName, {
362
+ uid
363
+ });
318
364
  const allIds = data.map((doc) => doc._id).filter(Boolean);
319
365
  if (!allIds.length) return;
320
- const { docs: currentDocs } = await collection.find({
321
- selector: { _id: { $in: allIds } },
366
+ const {
367
+ docs: currentDocs
368
+ } = await collection.find({
369
+ selector: {
370
+ _id: {
371
+ $in: allIds
372
+ }
373
+ },
322
374
  fields: ["_id", "_rev"],
323
375
  limit: allIds.length
324
376
  });
@@ -328,12 +380,16 @@ const updateDocs = async (modelName, data, uid) => {
328
380
  return acc;
329
381
  }, {});
330
382
  const newDocs = data.map((mongoDoc) => {
331
- const currentDoc = currentDocsById[mongoDoc._id] ?? { _id: mongoDoc._id };
383
+ const currentDoc = currentDocsById[mongoDoc._id] ?? {
384
+ _id: mongoDoc._id
385
+ };
332
386
  const nextDoc = Object.entries(mongoDoc).reduce((acc, [key, value]) => {
333
387
  const newKey = key !== "_id" && key.startsWith("_") ? `${UNDERSCORE_PREFIX}${key}` : key;
334
388
  acc[newKey] = value;
335
389
  return acc;
336
- }, { ...currentDoc });
390
+ }, {
391
+ ...currentDoc
392
+ });
337
393
  const rev = currentDoc._rev;
338
394
  if (typeof rev === "string" && rev) {
339
395
  nextDoc._rev = rev;
@@ -345,11 +401,19 @@ const updateDocs = async (modelName, data, uid) => {
345
401
  await collection.bulkDocs(newDocs);
346
402
  };
347
403
  const deleteDocs = async (modelName, ids, uid) => {
348
- const collection = await getCollection(modelName, { uid });
404
+ const collection = await getCollection(modelName, {
405
+ uid
406
+ });
349
407
  const allIds = ids.map((id) => String(id ?? "")).filter(Boolean);
350
408
  if (!allIds.length) return;
351
- const { docs: currentDocs } = await collection.find({
352
- selector: { _id: { $in: allIds } },
409
+ const {
410
+ docs: currentDocs
411
+ } = await collection.find({
412
+ selector: {
413
+ _id: {
414
+ $in: allIds
415
+ }
416
+ },
353
417
  fields: ["_id", "_rev"],
354
418
  limit: allIds.length
355
419
  });
@@ -362,17 +426,28 @@ const deleteDocs = async (modelName, ids, uid) => {
362
426
  await collection.bulkDocs(deletions);
363
427
  };
364
428
  const destroyCollection = async (modelName, uid) => {
365
- const collection = await getCollection(modelName, { uid });
429
+ const collection = await getCollection(modelName, {
430
+ uid
431
+ });
366
432
  const prefix = getPrefix();
367
433
  const dbName = `${uid}/${modelName}`;
368
434
  collections.delete(`${prefix}${dbName}`);
369
435
  unregisterDbName(prefix, dbName);
370
436
  await collection.destroy();
371
437
  };
372
- const resetRtsPouchStore = ({ tenantId, appName }) => {
438
+ const resetRtsPouchStore = ({
439
+ tenantId,
440
+ appName
441
+ }) => {
373
442
  ensureBrowser$1();
374
- const basePrefix = computeBasePrefix({ tenantId, appName });
375
- const oldPrefix = readPrefixOverride({ tenantId, appName }) ?? basePrefix;
443
+ const basePrefix = computeBasePrefix({
444
+ tenantId,
445
+ appName
446
+ });
447
+ const oldPrefix = readPrefixOverride({
448
+ tenantId,
449
+ appName
450
+ }) ?? basePrefix;
376
451
  const dbNames = Array.from(loadDbNames(oldPrefix));
377
452
  const openDbs = Array.from(collections.entries()).filter(([key]) => key.startsWith(oldPrefix)).map(([, db]) => db);
378
453
  void (async () => {
@@ -384,7 +459,10 @@ const resetRtsPouchStore = ({ tenantId, appName }) => {
384
459
  const PouchDBForPrefix = PouchDB.defaults?.({}) ?? PouchDB;
385
460
  PouchDBForPrefix.prefix = oldPrefix;
386
461
  await Promise.all(Array.from(remaining).map(async (name) => {
387
- const db = new PouchDBForPrefix(name, { adapter: "indexeddb", revs_limit: 1 });
462
+ const db = new PouchDBForPrefix(name, {
463
+ adapter: "indexeddb",
464
+ revs_limit: 1
465
+ });
388
466
  await db.destroy().then(() => {
389
467
  remaining.delete(name);
390
468
  }).catch(() => {
@@ -399,7 +477,10 @@ const resetRtsPouchStore = ({ tenantId, appName }) => {
399
477
  })();
400
478
  const newPrefix = `${basePrefix}reset-${Date.now().toString(16)}/`;
401
479
  try {
402
- window.localStorage.setItem(getPrefixOverrideKey({ tenantId, appName }), newPrefix);
480
+ window.localStorage.setItem(getPrefixOverrideKey({
481
+ tenantId,
482
+ appName
483
+ }), newPrefix);
403
484
  } catch {
404
485
  return newPrefix;
405
486
  }
@@ -466,7 +547,9 @@ const sendToServer = (message) => {
466
547
  if (socket.readyState !== WebSocket.OPEN) return;
467
548
  socket.send(JSON.stringify(message));
468
549
  };
469
- const resubscribeAll = ({ forceInitialQuery }) => {
550
+ const resubscribeAll = ({
551
+ forceInitialQuery
552
+ }) => {
470
553
  for (const sub of subscriptions.values()) {
471
554
  const runInitialQuery = forceInitialQuery || sub.runInitialNetworkQuery;
472
555
  sendToServer({
@@ -506,7 +589,9 @@ const scheduleReconnect = () => {
506
589
  }
507
590
  reconnectAttempts += 1;
508
591
  reconnectTimer = window.setTimeout(() => {
509
- void connectInternal(currentTenantId, currentUid, connectOptions, { resetReconnectAttempts: false });
592
+ void connectInternal(currentTenantId, currentUid, connectOptions, {
593
+ resetReconnectAttempts: false
594
+ });
510
595
  }, delay);
511
596
  };
512
597
  const isDocWithId = (doc) => {
@@ -523,12 +608,22 @@ const normalizePageInfo$1 = (value) => {
523
608
  return {
524
609
  hasNextPage: raw.hasNextPage,
525
610
  hasPrevPage: raw.hasPrevPage,
526
- ...nextCursor ? { nextCursor } : {},
527
- ...prevCursor ? { prevCursor } : {}
611
+ ...nextCursor ? {
612
+ nextCursor
613
+ } : {},
614
+ ...prevCursor ? {
615
+ prevCursor
616
+ } : {}
528
617
  };
529
618
  };
530
619
  const handleQueryPayload = (payload) => {
531
- const { modelName, queryKey, data, error, txnId } = payload;
620
+ const {
621
+ modelName,
622
+ queryKey,
623
+ data,
624
+ error,
625
+ txnId
626
+ } = payload;
532
627
  const cbKey = `${modelName}.${queryKey}`;
533
628
  const callbacks = queryCallbacks.get(cbKey);
534
629
  if (!callbacks || !callbacks.size) return;
@@ -537,7 +632,14 @@ const handleQueryPayload = (payload) => {
537
632
  const hasPopulate = Boolean(subscription?.options?.populate);
538
633
  const hasPagination = Boolean(subscription?.options?.pagination || pageInfo);
539
634
  const isLocal = !!(txnId && localTxnBuf.includes(txnId));
540
- const context = { source: "network", isLocal, txnId, ...pageInfo ? { pageInfo } : {} };
635
+ const context = {
636
+ source: "network",
637
+ isLocal,
638
+ txnId,
639
+ ...pageInfo ? {
640
+ pageInfo
641
+ } : {}
642
+ };
541
643
  if (error) {
542
644
  for (const cb of callbacks) cb(error, void 0, context);
543
645
  return;
@@ -580,7 +682,11 @@ const addLocalTxn = (txnId) => {
580
682
  localTxnBuf.shift();
581
683
  }
582
684
  };
583
- const getSyncStorageKey = ({ tenantId, uid, appName }) => `rb:rts:changesSeq:${appName ?? ""}:${tenantId}:${uid}`;
685
+ const getSyncStorageKey = ({
686
+ tenantId,
687
+ uid,
688
+ appName
689
+ }) => `rb:rts:changesSeq:${appName ?? ""}:${tenantId}:${uid}`;
584
690
  const readStoredSeq = (key) => {
585
691
  try {
586
692
  const raw = window.localStorage.getItem(key);
@@ -628,15 +734,24 @@ const applyChangeBatch = async (changes, uid) => {
628
734
  const syncRtsChanges = async (tenantId, uid, options = {}) => {
629
735
  ensureBrowser();
630
736
  if (!tenantId || !uid) return;
631
- const storageKey = getSyncStorageKey({ tenantId, uid, appName: options.appName });
737
+ const storageKey = getSyncStorageKey({
738
+ tenantId,
739
+ uid,
740
+ appName: options.appName
741
+ });
632
742
  let sinceSeq = readStoredSeq(storageKey);
633
743
  for (let i = 0; i < 32; i += 1) {
634
744
  const url = `${RTS_CHANGES_ROUTE}?${TENANT_ID_QUERY_PARAM}=${encodeURIComponent(tenantId)}`;
635
745
  const response = await fetch(url, {
636
746
  method: "POST",
637
747
  credentials: "include",
638
- headers: { "Content-Type": "application/json" },
639
- body: JSON.stringify({ sinceSeq, limit: 2e3 })
748
+ headers: {
749
+ "Content-Type": "application/json"
750
+ },
751
+ body: JSON.stringify({
752
+ sinceSeq,
753
+ limit: 2e3
754
+ })
640
755
  });
641
756
  if (!response.ok) return;
642
757
  const payload = await response.json().catch(() => null);
@@ -647,29 +762,37 @@ const syncRtsChanges = async (tenantId, uid, options = {}) => {
647
762
  const latestSeq = Number(payloadObj.latestSeq ?? 0);
648
763
  const needsFullResync = Boolean(payloadObj.needsFullResync);
649
764
  if (needsFullResync) {
650
- resetRtsPouchStore({ tenantId, appName: options.appName });
765
+ resetRtsPouchStore({
766
+ tenantId,
767
+ appName: options.appName
768
+ });
651
769
  writeStoredSeq(storageKey, latestSeq);
652
770
  return;
653
771
  }
654
772
  const changesRaw = payloadObj.changes;
655
773
  const changes = Array.isArray(changesRaw) ? changesRaw : [];
656
- const normalized = changes.map((c) => {
657
- if (!c || typeof c !== "object") return null;
658
- const obj = c;
774
+ const normalized = changes.map((c2) => {
775
+ if (!c2 || typeof c2 !== "object") return null;
776
+ const obj = c2;
659
777
  const seq = Number(obj.seq ?? 0);
660
778
  const modelName = typeof obj.modelName === "string" ? obj.modelName : String(obj.modelName ?? "");
661
779
  const op = obj.op === "reset_model" ? "reset_model" : "delete";
662
780
  const docId = typeof obj.docId === "string" && obj.docId ? obj.docId : obj.docId ? String(obj.docId) : void 0;
663
- return { seq, modelName, op, ...docId ? { docId } : {} };
664
- }).filter((c) => c !== null).filter(
665
- (c) => Number.isFinite(c.seq) && c.seq > 0 && c.modelName && (c.op === "reset_model" || !!c.docId)
666
- );
781
+ return {
782
+ seq,
783
+ modelName,
784
+ op,
785
+ ...docId ? {
786
+ docId
787
+ } : {}
788
+ };
789
+ }).filter((c2) => c2 !== null).filter((c2) => Number.isFinite(c2.seq) && c2.seq > 0 && c2.modelName && (c2.op === "reset_model" || !!c2.docId));
667
790
  if (!normalized.length) {
668
791
  writeStoredSeq(storageKey, latestSeq);
669
792
  return;
670
793
  }
671
794
  await applyChangeBatch(normalized, uid);
672
- const lastSeq = normalized.reduce((max, c) => c.seq > max ? c.seq : max, sinceSeq);
795
+ const lastSeq = normalized.reduce((max, c2) => c2.seq > max ? c2.seq : max, sinceSeq);
673
796
  sinceSeq = lastSeq;
674
797
  writeStoredSeq(storageKey, sinceSeq);
675
798
  if (latestSeq > 0 && sinceSeq >= latestSeq) {
@@ -682,14 +805,18 @@ const ensureSynced = (tenantId, uid, options) => {
682
805
  const key = `${options.appName ?? ""}:${tenantId}:${uid}`;
683
806
  if (syncPromise && syncKey === key) return;
684
807
  syncKey = key;
685
- syncPromise = syncRtsChanges(tenantId, uid, { appName: options.appName }).catch(() => {
808
+ syncPromise = syncRtsChanges(tenantId, uid, {
809
+ appName: options.appName
810
+ }).catch(() => {
686
811
  }).finally(() => {
687
812
  if (syncKey === key) {
688
813
  syncPromise = null;
689
814
  }
690
815
  });
691
816
  };
692
- const connectInternal = (tenantId, uid, options, { resetReconnectAttempts }) => {
817
+ const connectInternal = (tenantId, uid, options, {
818
+ resetReconnectAttempts
819
+ }) => {
693
820
  ensureBrowser();
694
821
  if (!tenantId) return Promise.resolve();
695
822
  if (!uid) throw new Error("Missing uid");
@@ -697,7 +824,10 @@ const connectInternal = (tenantId, uid, options, { resetReconnectAttempts }) =>
697
824
  currentUid = uid;
698
825
  connectOptions = options;
699
826
  if (options.configureStore !== false) {
700
- configureRtsPouchStore({ tenantId, appName: options.appName });
827
+ configureRtsPouchStore({
828
+ tenantId,
829
+ appName: options.appName
830
+ });
701
831
  }
702
832
  ensureSynced(tenantId, uid, options);
703
833
  if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) {
@@ -717,7 +847,9 @@ const connectInternal = (tenantId, uid, options, { resetReconnectAttempts }) =>
717
847
  reconnectAttempts = 0;
718
848
  pendingServerReconnectJitter = false;
719
849
  const forceInitialQuery = hasEstablishedConnection;
720
- resubscribeAll({ forceInitialQuery });
850
+ resubscribeAll({
851
+ forceInitialQuery
852
+ });
721
853
  hasEstablishedConnection = true;
722
854
  resolve();
723
855
  });
@@ -743,7 +875,9 @@ const connectInternal = (tenantId, uid, options, { resetReconnectAttempts }) =>
743
875
  return connectPromise;
744
876
  };
745
877
  const connect = (tenantId, uid, options = {}) => {
746
- return connectInternal(tenantId, uid, options, { resetReconnectAttempts: true });
878
+ return connectInternal(tenantId, uid, options, {
879
+ resetReconnectAttempts: true
880
+ });
747
881
  };
748
882
  const disconnect = () => {
749
883
  explicitDisconnect = true;
@@ -796,7 +930,13 @@ const registerQuery = (modelName, query, optionsOrCallback, callbackMaybe, behav
796
930
  const set = queryCallbacks.get(cbKey) ?? /* @__PURE__ */ new Set();
797
931
  set.add(callback);
798
932
  queryCallbacks.set(cbKey, set);
799
- subscriptions.set(cbKey, { modelName, query, options, queryKey, runInitialNetworkQuery });
933
+ subscriptions.set(cbKey, {
934
+ modelName,
935
+ query,
936
+ options,
937
+ queryKey,
938
+ runInitialNetworkQuery
939
+ });
800
940
  if (currentUid && runInitialLocalQuery && !hasPopulate && !hasPagination) {
801
941
  void runQuery({
802
942
  modelName,
@@ -807,14 +947,28 @@ const registerQuery = (modelName, query, optionsOrCallback, callbackMaybe, behav
807
947
  sort: options.sort,
808
948
  limit: options.limit
809
949
  }
810
- }).then(({ data, context }) => {
950
+ }).then(({
951
+ data,
952
+ context
953
+ }) => {
811
954
  callback?.(null, data, context);
812
955
  }).catch(() => {
813
956
  });
814
957
  }
815
- sendToServer({ type: "register-query", modelName, queryKey, query, options, runInitialQuery: runInitialNetworkQuery });
958
+ sendToServer({
959
+ type: "register-query",
960
+ modelName,
961
+ queryKey,
962
+ query,
963
+ options,
964
+ runInitialQuery: runInitialNetworkQuery
965
+ });
816
966
  return () => {
817
- sendToServer({ type: "remove-query", modelName, queryKey });
967
+ sendToServer({
968
+ type: "remove-query",
969
+ modelName,
970
+ queryKey
971
+ });
818
972
  const callbacks = queryCallbacks.get(cbKey);
819
973
  callbacks?.delete(callback);
820
974
  if (callbacks && callbacks.size === 0) {
@@ -836,7 +990,10 @@ const runNetworkQuery = async ({
836
990
  if (!socket || socket.readyState !== WebSocket.OPEN) {
837
991
  throw new Error("runNetworkQuery: RTS socket is not connected");
838
992
  }
839
- const resolvedOptions = options.key ? options : { ...options, key: makeRunQueryKey() };
993
+ const resolvedOptions = options.key ? options : {
994
+ ...options,
995
+ key: makeRunQueryKey()
996
+ };
840
997
  const queryKey = computeRtsQueryKey(query, resolvedOptions);
841
998
  const cbKey = `${modelName}.${queryKey}`;
842
999
  return await new Promise((resolve, reject) => {
@@ -861,7 +1018,10 @@ const runNetworkQuery = async ({
861
1018
  settle(() => reject(error));
862
1019
  return;
863
1020
  }
864
- settle(() => resolve({ data, context }));
1021
+ settle(() => resolve({
1022
+ data,
1023
+ context
1024
+ }));
865
1025
  };
866
1026
  const callbacks = queryCallbacks.get(cbKey) ?? /* @__PURE__ */ new Set();
867
1027
  callbacks.add(callback);
@@ -871,11 +1031,21 @@ const runNetworkQuery = async ({
871
1031
  settle(() => reject(new Error("runNetworkQuery: request timed out")));
872
1032
  }, timeoutMs);
873
1033
  }
874
- sendToServer({ type: "run-query", modelName, queryKey, query, options: resolvedOptions });
1034
+ sendToServer({
1035
+ type: "run-query",
1036
+ modelName,
1037
+ queryKey,
1038
+ query,
1039
+ options: resolvedOptions
1040
+ });
875
1041
  });
876
1042
  };
877
1043
  const sendMessage = (event, payload) => {
878
- sendToServer({ type: "event", event, payload });
1044
+ sendToServer({
1045
+ type: "event",
1046
+ event,
1047
+ payload
1048
+ });
879
1049
  };
880
1050
  const onMessage = (event, callback) => {
881
1051
  const set = messageCallbacks.get(event) ?? /* @__PURE__ */ new Set();
@@ -897,8 +1067,12 @@ const normalizePageInfo = (value) => {
897
1067
  return {
898
1068
  hasNextPage: raw.hasNextPage,
899
1069
  hasPrevPage: raw.hasPrevPage,
900
- ...nextCursor ? { nextCursor } : {},
901
- ...prevCursor ? { prevCursor } : {}
1070
+ ...nextCursor ? {
1071
+ nextCursor
1072
+ } : {},
1073
+ ...prevCursor ? {
1074
+ prevCursor
1075
+ } : {}
902
1076
  };
903
1077
  };
904
1078
  const getDocId = (doc) => {
@@ -965,14 +1139,8 @@ const useQuery = (modelName, query = {}, options = {}) => {
965
1139
  queryKey
966
1140
  });
967
1141
  }
968
- const seedDataRaw = useMemo(
969
- () => enabled && ssrEnabled ? ssrRuntime ? ssrRuntime.getQueryData(modelName, queryKey) : peekHydratedRtsQueryData(modelName, queryKey) : void 0,
970
- [enabled, ssrEnabled, ssrRuntime, modelName, queryKey]
971
- );
972
- const seedPageInfoRaw = useMemo(
973
- () => enabled && ssrEnabled ? ssrRuntime ? ssrRuntime.getQueryPageInfo(modelName, queryKey) : peekHydratedRtsQueryPageInfo(modelName, queryKey) : void 0,
974
- [enabled, ssrEnabled, ssrRuntime, modelName, queryKey]
975
- );
1142
+ const seedDataRaw = useMemo(() => enabled && ssrEnabled ? ssrRuntime ? ssrRuntime.getQueryData(modelName, queryKey) : peekHydratedRtsQueryData(modelName, queryKey) : void 0, [enabled, ssrEnabled, ssrRuntime, modelName, queryKey]);
1143
+ const seedPageInfoRaw = useMemo(() => enabled && ssrEnabled ? ssrRuntime ? ssrRuntime.getQueryPageInfo(modelName, queryKey) : peekHydratedRtsQueryPageInfo(modelName, queryKey) : void 0, [enabled, ssrEnabled, ssrRuntime, modelName, queryKey]);
976
1144
  const hasSeedData = Array.isArray(seedDataRaw);
977
1145
  const seedData = hasSeedData ? seedDataRaw : void 0;
978
1146
  const seedPageInfo = normalizePageInfo(seedPageInfoRaw);
@@ -984,8 +1152,21 @@ const useQuery = (modelName, query = {}, options = {}) => {
984
1152
  return "";
985
1153
  }
986
1154
  })();
1155
+ const seedPageInfoJson = (() => {
1156
+ if (!seedPageInfo) return "";
1157
+ try {
1158
+ return JSON.stringify(seedPageInfo);
1159
+ } catch {
1160
+ return "";
1161
+ }
1162
+ })();
987
1163
  const [data, setData] = useState(() => isPaginated ? void 0 : seedData);
988
- const [headPage, setHeadPage] = useState(() => isPaginated && seedData ? { nodes: seedData, ...seedPageInfo ? { pageInfo: seedPageInfo } : {} } : null);
1164
+ const [headPage, setHeadPage] = useState(() => isPaginated && seedData ? {
1165
+ nodes: seedData,
1166
+ ...seedPageInfo ? {
1167
+ pageInfo: seedPageInfo
1168
+ } : {}
1169
+ } : null);
989
1170
  const [previousPages, setPreviousPages] = useState([]);
990
1171
  const [nextPages, setNextPages] = useState([]);
991
1172
  const [source, setSource] = useState(() => hasSeedData ? "cache" : void 0);
@@ -1035,7 +1216,9 @@ const useQuery = (modelName, query = {}, options = {}) => {
1035
1216
  if (isPaginated) {
1036
1217
  setHeadPage({
1037
1218
  nodes: nextSeedData,
1038
- ...seedPageInfo ? { pageInfo: seedPageInfo } : {}
1219
+ ...seedPageInfo ? {
1220
+ pageInfo: seedPageInfo
1221
+ } : {}
1039
1222
  });
1040
1223
  setData(void 0);
1041
1224
  } else {
@@ -1047,83 +1230,69 @@ const useQuery = (modelName, query = {}, options = {}) => {
1047
1230
  setData(void 0);
1048
1231
  setHeadPage(null);
1049
1232
  setLoading(true);
1050
- }, [enabled, ssrEnabled, ssrRuntime, modelName, queryKey, hasSeedData, seedData, seedJson, isPaginated, seedPageInfo]);
1233
+ }, [enabled, ssrEnabled, ssrRuntime, modelName, queryKey, hasSeedData, seedJson, seedPageInfoJson, isPaginated]);
1051
1234
  useEffect(() => {
1052
1235
  if (!enabled) return;
1053
1236
  const runInitialNetworkQuery = refreshOnMount || !hasSeedData;
1054
1237
  const runInitialLocalQuery = !hasSeedData && !hasPopulate && !isPaginated;
1055
- const unsubscribe = registerQuery(
1056
- modelName,
1057
- query,
1058
- {
1059
- key,
1060
- projection: options.projection,
1061
- sort: options.sort,
1062
- limit: options.limit,
1063
- populate: options.populate,
1064
- pagination: options.pagination
1065
- },
1066
- (err, result, context) => {
1067
- if (context.source === "cache" && hasNetworkReply.current) return;
1068
- if (context.source === "network") {
1069
- hasNetworkReply.current = true;
1070
- }
1071
- setLoading(false);
1072
- if (err) {
1073
- setError(err);
1074
- return;
1075
- }
1076
- if (!Array.isArray(result)) return;
1077
- if (context.source === "network" && context.isLocal && options.skipLocal && hasFirstReply.current) {
1078
- return;
1079
- }
1080
- hasFirstReply.current = true;
1081
- const networkPageInfo = context.source === "network" ? context.pageInfo : void 0;
1082
- const payloadForHash = isPaginated ? { result, pageInfo: networkPageInfo } : result;
1083
- let nextJson = "";
1084
- try {
1085
- nextJson = JSON.stringify(payloadForHash);
1086
- } catch {
1087
- nextJson = "";
1088
- }
1089
- if (nextJson && nextJson === lastDataJsonRef.current) {
1090
- setSource(context.source);
1091
- return;
1092
- }
1093
- lastDataJsonRef.current = nextJson;
1238
+ const unsubscribe = registerQuery(modelName, query, {
1239
+ key,
1240
+ projection: options.projection,
1241
+ sort: options.sort,
1242
+ limit: options.limit,
1243
+ populate: options.populate,
1244
+ pagination: options.pagination
1245
+ }, (err, result, context) => {
1246
+ if (context.source === "cache" && hasNetworkReply.current) return;
1247
+ if (context.source === "network") {
1248
+ hasNetworkReply.current = true;
1249
+ }
1250
+ setLoading(false);
1251
+ if (err) {
1252
+ setError(err);
1253
+ return;
1254
+ }
1255
+ if (!Array.isArray(result)) return;
1256
+ if (context.source === "network" && context.isLocal && options.skipLocal && hasFirstReply.current) {
1257
+ return;
1258
+ }
1259
+ hasFirstReply.current = true;
1260
+ const networkPageInfo = context.source === "network" ? context.pageInfo : void 0;
1261
+ const payloadForHash = isPaginated ? {
1262
+ result,
1263
+ pageInfo: networkPageInfo
1264
+ } : result;
1265
+ let nextJson = "";
1266
+ try {
1267
+ nextJson = JSON.stringify(payloadForHash);
1268
+ } catch {
1269
+ nextJson = "";
1270
+ }
1271
+ if (nextJson && nextJson === lastDataJsonRef.current) {
1094
1272
  setSource(context.source);
1095
- setError(void 0);
1096
- if (isPaginated) {
1097
- setHeadPage({
1098
- nodes: result,
1099
- ...networkPageInfo ? { pageInfo: networkPageInfo } : {}
1100
- });
1101
- return;
1102
- }
1103
- setData(result);
1104
- },
1105
- {
1106
- runInitialNetworkQuery,
1107
- runInitialLocalQuery
1273
+ return;
1108
1274
  }
1109
- );
1275
+ lastDataJsonRef.current = nextJson;
1276
+ setSource(context.source);
1277
+ setError(void 0);
1278
+ if (isPaginated) {
1279
+ setHeadPage({
1280
+ nodes: result,
1281
+ ...networkPageInfo ? {
1282
+ pageInfo: networkPageInfo
1283
+ } : {}
1284
+ });
1285
+ return;
1286
+ }
1287
+ setData(result);
1288
+ }, {
1289
+ runInitialNetworkQuery,
1290
+ runInitialLocalQuery
1291
+ });
1110
1292
  return () => {
1111
1293
  unsubscribe?.();
1112
1294
  };
1113
- }, [
1114
- enabled,
1115
- modelName,
1116
- queryKey,
1117
- queryJson,
1118
- projectionJson,
1119
- sortJson,
1120
- limitStr,
1121
- populateJson,
1122
- paginationJson,
1123
- hasSeedData,
1124
- refreshOnMount,
1125
- isPaginated
1126
- ]);
1295
+ }, [enabled, modelName, queryKey, queryJson, projectionJson, sortJson, limitStr, populateJson, paginationJson, hasSeedData, refreshOnMount, isPaginated]);
1127
1296
  const effectivePageInfo = useMemo(() => {
1128
1297
  if (!isPaginated) return void 0;
1129
1298
  const firstPageInfo = previousPages.length > 0 ? previousPages[0]?.pageInfo : headPage?.pageInfo;
@@ -1136,8 +1305,12 @@ const useQuery = (modelName, query = {}, options = {}) => {
1136
1305
  return {
1137
1306
  hasPrevPage,
1138
1307
  hasNextPage,
1139
- ...prevCursor ? { prevCursor } : {},
1140
- ...nextCursor ? { nextCursor } : {}
1308
+ ...prevCursor ? {
1309
+ prevCursor
1310
+ } : {},
1311
+ ...nextCursor ? {
1312
+ nextCursor
1313
+ } : {}
1141
1314
  };
1142
1315
  }, [headPage, isPaginated, nextPages, previousPages]);
1143
1316
  const mergedPaginatedData = useMemo(() => {
@@ -1151,8 +1324,8 @@ const useQuery = (modelName, query = {}, options = {}) => {
1151
1324
  const currentHead = headPageRef.current;
1152
1325
  const currentNextPages = nextPagesRef.current;
1153
1326
  const cursor = currentNextPages.length > 0 ? currentNextPages[currentNextPages.length - 1]?.pageInfo?.nextCursor : currentHead?.pageInfo?.nextCursor;
1154
- const hasNextPage = currentNextPages.length > 0 ? Boolean(currentNextPages[currentNextPages.length - 1]?.pageInfo?.hasNextPage) : Boolean(currentHead?.pageInfo?.hasNextPage);
1155
- if (!cursor || !hasNextPage) return false;
1327
+ const hasNextPage_0 = currentNextPages.length > 0 ? Boolean(currentNextPages[currentNextPages.length - 1]?.pageInfo?.hasNextPage) : Boolean(currentHead?.pageInfo?.hasNextPage);
1328
+ if (!cursor || !hasNextPage_0) return false;
1156
1329
  setPagingDirection("next");
1157
1330
  setLoading(true);
1158
1331
  setError(void 0);
@@ -1176,13 +1349,15 @@ const useQuery = (modelName, query = {}, options = {}) => {
1176
1349
  if (!Array.isArray(response.data)) return false;
1177
1350
  const page = {
1178
1351
  nodes: response.data,
1179
- ...response.context.source === "network" && response.context.pageInfo ? { pageInfo: response.context.pageInfo } : {}
1352
+ ...response.context.source === "network" && response.context.pageInfo ? {
1353
+ pageInfo: response.context.pageInfo
1354
+ } : {}
1180
1355
  };
1181
1356
  setSource("network");
1182
1357
  setNextPages((current) => [...current, page]);
1183
1358
  return true;
1184
- } catch (err) {
1185
- setError(err);
1359
+ } catch (err_0) {
1360
+ setError(err_0);
1186
1361
  return false;
1187
1362
  } finally {
1188
1363
  setPagingDirection(null);
@@ -1192,16 +1367,16 @@ const useQuery = (modelName, query = {}, options = {}) => {
1192
1367
  const fetchPrevious = async () => {
1193
1368
  if (!enabled || !isPaginated || !options.pagination) return false;
1194
1369
  if (pagingDirectionRef.current) return false;
1195
- const currentHead = headPageRef.current;
1370
+ const currentHead_0 = headPageRef.current;
1196
1371
  const currentPreviousPages = previousPagesRef.current;
1197
- const cursor = currentPreviousPages.length > 0 ? currentPreviousPages[0]?.pageInfo?.prevCursor : currentHead?.pageInfo?.prevCursor;
1198
- const hasPrevPage = currentPreviousPages.length > 0 ? Boolean(currentPreviousPages[0]?.pageInfo?.hasPrevPage) : Boolean(currentHead?.pageInfo?.hasPrevPage);
1199
- if (!cursor || !hasPrevPage) return false;
1372
+ const cursor_0 = currentPreviousPages.length > 0 ? currentPreviousPages[0]?.pageInfo?.prevCursor : currentHead_0?.pageInfo?.prevCursor;
1373
+ const hasPrevPage_0 = currentPreviousPages.length > 0 ? Boolean(currentPreviousPages[0]?.pageInfo?.hasPrevPage) : Boolean(currentHead_0?.pageInfo?.hasPrevPage);
1374
+ if (!cursor_0 || !hasPrevPage_0) return false;
1200
1375
  setPagingDirection("prev");
1201
1376
  setLoading(true);
1202
1377
  setError(void 0);
1203
1378
  try {
1204
- const response = await runNetworkQuery({
1379
+ const response_0 = await runNetworkQuery({
1205
1380
  modelName,
1206
1381
  query,
1207
1382
  options: {
@@ -1213,20 +1388,22 @@ const useQuery = (modelName, query = {}, options = {}) => {
1213
1388
  pagination: {
1214
1389
  ...options.pagination,
1215
1390
  direction: "prev",
1216
- cursor
1391
+ cursor: cursor_0
1217
1392
  }
1218
1393
  }
1219
1394
  });
1220
- if (!Array.isArray(response.data)) return false;
1221
- const page = {
1222
- nodes: response.data,
1223
- ...response.context.source === "network" && response.context.pageInfo ? { pageInfo: response.context.pageInfo } : {}
1395
+ if (!Array.isArray(response_0.data)) return false;
1396
+ const page_0 = {
1397
+ nodes: response_0.data,
1398
+ ...response_0.context.source === "network" && response_0.context.pageInfo ? {
1399
+ pageInfo: response_0.context.pageInfo
1400
+ } : {}
1224
1401
  };
1225
1402
  setSource("network");
1226
- setPreviousPages((current) => [page, ...current]);
1403
+ setPreviousPages((current_0) => [page_0, ...current_0]);
1227
1404
  return true;
1228
- } catch (err) {
1229
- setError(err);
1405
+ } catch (err_1) {
1406
+ setError(err_1);
1230
1407
  return false;
1231
1408
  } finally {
1232
1409
  setPagingDirection(null);
@@ -1238,29 +1415,16 @@ const useQuery = (modelName, query = {}, options = {}) => {
1238
1415
  setPreviousPages([]);
1239
1416
  setNextPages([]);
1240
1417
  };
1241
- return useMemo(
1242
- () => ({
1243
- data: isPaginated ? mergedPaginatedData : data,
1244
- pageInfo: effectivePageInfo,
1245
- source,
1246
- error,
1247
- loading,
1248
- fetchNext,
1249
- fetchPrevious,
1250
- resetPagination
1251
- }),
1252
- [
1253
- data,
1254
- effectivePageInfo,
1255
- error,
1256
- fetchNext,
1257
- fetchPrevious,
1258
- isPaginated,
1259
- loading,
1260
- mergedPaginatedData,
1261
- source
1262
- ]
1263
- );
1418
+ return useMemo(() => ({
1419
+ data: isPaginated ? mergedPaginatedData : data,
1420
+ pageInfo: effectivePageInfo,
1421
+ source,
1422
+ error,
1423
+ loading,
1424
+ fetchNext,
1425
+ fetchPrevious,
1426
+ resetPagination
1427
+ }), [data, effectivePageInfo, error, fetchNext, fetchPrevious, isPaginated, loading, mergedPaginatedData, source]);
1264
1428
  };
1265
1429
  export {
1266
1430
  RtsSsrRuntimeProvider as R,
@@ -1288,4 +1452,4 @@ export {
1288
1452
  updateDocs as u,
1289
1453
  useQuery as v
1290
1454
  };
1291
- //# sourceMappingURL=useQuery-Ce_EmI2F.js.map
1455
+ //# sourceMappingURL=useQuery-DImVXkBa.js.map