@powerhousedao/reactor-browser 6.2.3-dev.3 → 6.2.3-dev.30

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.
Files changed (86) hide show
  1. package/dist/{attachment-service-CdwHrbDH.d.ts → attachment-service-CF8LWxyM.d.ts} +209 -64
  2. package/dist/attachment-service-CF8LWxyM.d.ts.map +1 -0
  3. package/dist/{client-DjK30EQ-.js → client-BiJAJ9dW.js} +1 -1
  4. package/dist/{client-DjK30EQ-.js.map → client-BiJAJ9dW.js.map} +1 -1
  5. package/dist/{client-BIHN_UyR.d.ts → client-CngU4mtn.d.ts} +3 -3
  6. package/dist/client-CngU4mtn.d.ts.map +1 -0
  7. package/dist/{client-D66jVnot.js → client-VV9M73s_.js} +126 -18
  8. package/dist/client-VV9M73s_.js.map +1 -0
  9. package/dist/{document-by-id-BSZqTN66.js → dispatch-BOQgTK9B.js} +375 -51
  10. package/dist/dispatch-BOQgTK9B.js.map +1 -0
  11. package/dist/document-by-id-Kuxk62l1.js +16 -0
  12. package/dist/document-by-id-Kuxk62l1.js.map +1 -0
  13. package/dist/{document-model-modules-DfQBNGc-.js → document-model-modules-Cv9KSduJ.js} +64 -97
  14. package/dist/document-model-modules-Cv9KSduJ.js.map +1 -0
  15. package/dist/{document-operations-Bgo6A6W2.js → document-operations-D16LsXDs.js} +202 -124
  16. package/dist/document-operations-D16LsXDs.js.map +1 -0
  17. package/dist/{global-BggszP4X.d.ts → global-yMvtFjK6.d.ts} +51 -14
  18. package/dist/global-yMvtFjK6.d.ts.map +1 -0
  19. package/dist/{index-CkJNhsQo.d.ts → index-UsPtg1Z3.d.ts} +21 -99
  20. package/dist/index-UsPtg1Z3.d.ts.map +1 -0
  21. package/dist/{index-BIVDXw3K.d.ts → index-rtDmzViP.d.ts} +3 -3
  22. package/dist/index-rtDmzViP.d.ts.map +1 -0
  23. package/dist/index.d.ts +413 -362
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +138 -43
  26. package/dist/index.js.map +1 -1
  27. package/dist/{inspector-proxy-6h5VKAwt.d.ts → inspector-proxy-B2qjCMEv.d.ts} +9 -4
  28. package/dist/inspector-proxy-B2qjCMEv.d.ts.map +1 -0
  29. package/dist/{make-ph-event-functions-DBq3iWYn.js → make-ph-event-functions-FzpvQtj6.js} +1 -1
  30. package/dist/{make-ph-event-functions-DBq3iWYn.js.map → make-ph-event-functions-FzpvQtj6.js.map} +1 -1
  31. package/dist/{pglite-CntadC_p-9NDG14dS.d.ts → pglite-CntadC_p-DTkdF8sr.d.ts} +11 -33
  32. package/dist/pglite-CntadC_p-DTkdF8sr.d.ts.map +1 -0
  33. package/dist/{relational-D4sxGPz7.js → relational-ChC_AWAK.js} +4 -3
  34. package/dist/{relational-D4sxGPz7.js.map → relational-ChC_AWAK.js.map} +1 -1
  35. package/dist/{renown-BIEv6bSI.js → renown-C9pYZRqf.js} +26 -12
  36. package/dist/renown-C9pYZRqf.js.map +1 -0
  37. package/dist/{renown-BHxwP7xU.js → renown-Def5iO8k.js} +2 -2
  38. package/dist/{renown-BHxwP7xU.js.map → renown-Def5iO8k.js.map} +1 -1
  39. package/dist/src/ai/index.d.ts +51 -62
  40. package/dist/src/ai/index.d.ts.map +1 -1
  41. package/dist/src/ai/index.js +5 -8
  42. package/dist/src/ai/index.js.map +1 -1
  43. package/dist/src/analytics/index.d.ts +36 -44
  44. package/dist/src/analytics/index.d.ts.map +1 -1
  45. package/dist/src/analytics/index.js +2 -2
  46. package/dist/src/analytics/index.js.map +1 -1
  47. package/dist/src/document-model.d.ts +3 -4
  48. package/dist/src/document-model.d.ts.map +1 -1
  49. package/dist/src/document-model.js.map +1 -1
  50. package/dist/src/graphql/client.d.ts +4 -3
  51. package/dist/src/graphql/client.js +1 -1
  52. package/dist/src/graphql-client/entry.d.ts +5 -4
  53. package/dist/src/graphql-client/entry.js +4 -4
  54. package/dist/src/relational/index.d.ts +8 -9
  55. package/dist/src/relational/index.d.ts.map +1 -1
  56. package/dist/src/relational/index.js +1 -1
  57. package/dist/src/renown/index.d.ts +3 -2
  58. package/dist/src/renown/index.js +3 -3
  59. package/dist/src/rpc/index.d.ts +40 -31
  60. package/dist/src/rpc/index.d.ts.map +1 -1
  61. package/dist/src/rpc/index.js +20 -5
  62. package/dist/src/rpc/index.js.map +1 -1
  63. package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
  64. package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
  65. package/dist/{switchboard-D4-_jwk-.js → switchboard-Nyr7CXcr.js} +59 -7
  66. package/dist/switchboard-Nyr7CXcr.js.map +1 -0
  67. package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
  68. package/dist/types-520nWrB3.d.ts.map +1 -0
  69. package/dist/{types-Dcv1ZLoW.d.ts → types-B7-_l_wE.d.ts} +86 -16
  70. package/dist/types-B7-_l_wE.d.ts.map +1 -0
  71. package/package.json +15 -16
  72. package/dist/attachment-service-CdwHrbDH.d.ts.map +0 -1
  73. package/dist/client-BIHN_UyR.d.ts.map +0 -1
  74. package/dist/client-D66jVnot.js.map +0 -1
  75. package/dist/document-by-id-BSZqTN66.js.map +0 -1
  76. package/dist/document-model-modules-DfQBNGc-.js.map +0 -1
  77. package/dist/document-operations-Bgo6A6W2.js.map +0 -1
  78. package/dist/global-BggszP4X.d.ts.map +0 -1
  79. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  80. package/dist/index-CkJNhsQo.d.ts.map +0 -1
  81. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  82. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  83. package/dist/renown-BIEv6bSI.js.map +0 -1
  84. package/dist/switchboard-D4-_jwk-.js.map +0 -1
  85. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  86. package/dist/types-Dcv1ZLoW.d.ts.map +0 -1
@@ -1,6 +1,5 @@
1
- import { t as makePHEventFunctions } from "./make-ph-event-functions-DBq3iWYn.js";
1
+ import { t as makePHEventFunctions } from "./make-ph-event-functions-FzpvQtj6.js";
2
2
  import { logger } from "document-model";
3
- import { buildSignedAction } from "@powerhousedao/shared/document-model";
4
3
  import { use, useCallback, useEffect, useReducer, useSyncExternalStore } from "react";
5
4
  //#region src/actions/queue.ts
6
5
  async function queueActions(document, actionOrActions) {
@@ -49,16 +48,6 @@ async function uploadOperations(documentId, allOperations, pushOperations, optio
49
48
  }
50
49
  //#endregion
51
50
  //#region src/actions/sign.ts
52
- async function signAction(action, document) {
53
- const renown = window.ph?.renown;
54
- if (!renown?.user) return action;
55
- if (!action.context?.signer) return action;
56
- const reactorClient = window.ph?.reactorClientModule?.client;
57
- if (!reactorClient) return action;
58
- const reducer = (await reactorClient.getDocumentModelModuleForDocument(document)).reducer;
59
- const actionSigner = action.context.signer;
60
- return await buildSignedAction(action, reducer, document, actionSigner, renown.crypto.sign);
61
- }
62
51
  function addActionContext(action) {
63
52
  const renown = window.ph?.renown;
64
53
  if (!renown?.user) return action;
@@ -78,7 +67,7 @@ function addActionContext(action) {
78
67
  ...action
79
68
  };
80
69
  }
81
- async function makeSignedActionWithContext(action, document) {
70
+ function makeSignedActionWithContext(action, document) {
82
71
  if (!action) {
83
72
  logger.error("No action found");
84
73
  return;
@@ -87,15 +76,14 @@ async function makeSignedActionWithContext(action, document) {
87
76
  logger.error("No document found");
88
77
  return;
89
78
  }
90
- return addActionContext(await signAction(action, document));
79
+ return addActionContext(action);
91
80
  }
92
- async function makeSignedActionsWithContext(actionOrActions, document) {
81
+ function makeSignedActionsWithContext(actionOrActions, document) {
93
82
  if (!actionOrActions) {
94
83
  logger.error("No actions found");
95
84
  return;
96
85
  }
97
- const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
98
- return (await Promise.all(actions.map((action) => makeSignedActionWithContext(action, document)))).filter((a) => a !== void 0);
86
+ return (Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]).map((action) => makeSignedActionWithContext(action, document)).filter((a) => a !== void 0);
99
87
  }
100
88
  //#endregion
101
89
  //#region src/actions/dispatch.ts
@@ -122,7 +110,7 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
122
110
  logger.error(`Document with id ${JSON.stringify(documentOrDocumentId)} not found`);
123
111
  return;
124
112
  }
125
- const signedActionsWithContext = await makeSignedActionsWithContext(actionOrActions, document);
113
+ const signedActionsWithContext = makeSignedActionsWithContext(actionOrActions, document);
126
114
  if (!signedActionsWithContext) {
127
115
  logger.error("No signed actions with context found");
128
116
  return;
@@ -135,6 +123,119 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
135
123
  if (onSuccess && result) onSuccess(result);
136
124
  return result;
137
125
  }
126
+ //#endregion
127
+ //#region src/document-refetcher.ts
128
+ /** The refetch snapshot of a document with nothing in flight and no kept failure. */
129
+ const IDLE_REFETCH_STATE = Object.freeze({
130
+ isRefetching: false,
131
+ error: void 0
132
+ });
133
+ function fulfilledPromise(value) {
134
+ const promise = Promise.resolve(value);
135
+ promise.status = "fulfilled";
136
+ promise.value = value;
137
+ return promise;
138
+ }
139
+ function rejectedPromise(reason) {
140
+ const promise = Promise.reject(reason);
141
+ promise.status = "rejected";
142
+ promise.reason = reason;
143
+ promise.catch(() => void 0);
144
+ return promise;
145
+ }
146
+ const MISSING_DOCUMENT_ERRORS = ["DocumentNotFoundError", "DocumentDeletedError"];
147
+ function isMissingDocumentError(error) {
148
+ if (!(error instanceof Error)) return false;
149
+ return MISSING_DOCUMENT_ERRORS.includes(error.name) || error.message.startsWith("Document not found");
150
+ }
151
+ const noop = () => void 0;
152
+ /** Background refetch of loaded documents: readers keep the loaded promise until it settles. */
153
+ var DocumentRefetcher = class {
154
+ host;
155
+ refetches = /* @__PURE__ */ new Map();
156
+ states = /* @__PURE__ */ new Map();
157
+ constructor(host) {
158
+ this.host = host;
159
+ }
160
+ getState(id) {
161
+ return this.states.get(id) ?? IDLE_REFETCH_STATE;
162
+ }
163
+ /** Serializes refetches per key: one runs, later requests share one queued run. */
164
+ refetch(id) {
165
+ let entry = this.refetches.get(id);
166
+ if (!entry) {
167
+ entry = {
168
+ running: void 0,
169
+ queued: void 0
170
+ };
171
+ this.refetches.set(id, entry);
172
+ const current = this.host.documents.get(id);
173
+ if (current?.status !== "pending") return this.start(id, entry);
174
+ entry.running = current;
175
+ }
176
+ const inFlight = entry;
177
+ inFlight.queued ??= (inFlight.running ?? Promise.resolve()).then(noop, noop).then(() => this.start(id, inFlight));
178
+ return inFlight.queued;
179
+ }
180
+ /** Stops any refetch of `id` from writing back, e.g. on deletion. */
181
+ forget(id) {
182
+ this.refetches.delete(id);
183
+ this.states.delete(id);
184
+ }
185
+ clear() {
186
+ this.refetches.clear();
187
+ this.states.clear();
188
+ }
189
+ start(id, entry) {
190
+ entry.queued = void 0;
191
+ entry.running = this.run(id, entry);
192
+ return entry.running;
193
+ }
194
+ async run(id, entry) {
195
+ const isCurrent = () => this.refetches.get(id) === entry;
196
+ if (!isCurrent()) return this.host.fetch(id);
197
+ if (this.setState(id, {
198
+ isRefetching: true,
199
+ error: this.getState(id).error
200
+ })) this.host.notify(id);
201
+ try {
202
+ const document = await this.host.fetch(id);
203
+ if (isCurrent()) {
204
+ this.host.onFetched?.(id, document);
205
+ this.host.documents.set(id, fulfilledPromise(document));
206
+ this.finish(id, entry, void 0);
207
+ }
208
+ return document;
209
+ } catch (error) {
210
+ if (isCurrent()) {
211
+ if (isMissingDocumentError(error)) {
212
+ this.host.documents.set(id, rejectedPromise(error));
213
+ this.finish(id, entry, void 0);
214
+ } else {
215
+ console.warn("[DocumentCache] Refetch failed; keeping the loaded document:", error);
216
+ this.finish(id, entry, error);
217
+ }
218
+ }
219
+ throw error;
220
+ }
221
+ }
222
+ finish(id, entry, error) {
223
+ if (!entry.queued) this.refetches.delete(id);
224
+ this.setState(id, {
225
+ isRefetching: entry.queued !== void 0,
226
+ error
227
+ });
228
+ this.host.notify(id);
229
+ }
230
+ /** Returns whether the snapshot changed; the caller notifies. */
231
+ setState(id, state) {
232
+ const current = this.getState(id);
233
+ if (current.isRefetching === state.isRefetching && current.error === state.error) return false;
234
+ if (!state.isRefetching && state.error === void 0) this.states.delete(id);
235
+ else this.states.set(id, Object.freeze({ ...state }));
236
+ return true;
237
+ }
238
+ };
138
239
  /**
139
240
  * The reactor's `DocumentChangeType` members, typed as the enum so they can be
140
241
  * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
@@ -195,16 +296,55 @@ function fulfilledOnly(promises) {
195
296
  return documents;
196
297
  });
197
298
  }
299
+ /** The snapshot every uncached document scope reads as. One frozen object, so `useSyncExternalStore` sees a stable value. */
300
+ const IDLE_OPERATIONS_ENTRY = Object.freeze({
301
+ status: "idle",
302
+ operations: Object.freeze([]),
303
+ error: void 0,
304
+ hasNextPage: false
305
+ });
306
+ /** Whether a document cache also serves operation history. `GraphQLClientDocumentCache` does not. */
307
+ function isOperationCache(cache) {
308
+ if (typeof cache !== "object" || cache === null) return false;
309
+ const candidate = cache;
310
+ return typeof candidate.getOperationsState === "function" && typeof candidate.loadOperations === "function" && typeof candidate.loadMoreOperations === "function" && typeof candidate.invalidateOperations === "function" && typeof candidate.subscribeOperations === "function";
311
+ }
312
+ /**
313
+ * Page size used to refresh a scope whose request record has gone missing.
314
+ * A loaded scope always has one, so this is a floor rather than a default.
315
+ */
316
+ const FALLBACK_REFRESH_LIMIT = 100;
317
+ /**
318
+ * The highest revision among the operations loaded so far, or -1 for none.
319
+ * Pages arrive oldest first, so this is normally the last entry; it is
320
+ * computed rather than assumed because nothing in the cache enforces that.
321
+ */
322
+ function highestOperationIndex(operations) {
323
+ let highest = -1;
324
+ for (const operation of operations) if (operation.index > highest) highest = operation.index;
325
+ return highest;
326
+ }
198
327
  /**
199
328
  * Document cache implementation that uses the new ReactorClient API.
200
329
  *
201
330
  * This cache subscribes to document change events via IReactorBrowserClient.subscribe()
202
331
  * and automatically updates the cache when documents are created, updated, or deleted.
332
+ * It also holds paginated operation history per document scope (see `IOperationCache`),
333
+ * which is dropped for a document whenever a change event for it arrives.
203
334
  */
204
335
  var DocumentCache = class {
336
+ client;
205
337
  documents = /* @__PURE__ */ new Map();
206
338
  batchPromises = /* @__PURE__ */ new Map();
207
339
  listeners = /* @__PURE__ */ new Map();
340
+ refetcher = new DocumentRefetcher({
341
+ documents: this.documents,
342
+ fetch: (id) => this.client.get(id),
343
+ notify: (id) => this.notifyListeners(id),
344
+ onFetched: (id, document) => {
345
+ if (document.header.id !== id) this.recordAlias(document.header.id, id);
346
+ }
347
+ });
208
348
  /**
209
349
  * Cache keys that fetched a document under a name other than its id --
210
350
  * slugs, which `client.get` resolves. Change events dispatch by `header.id`,
@@ -213,6 +353,11 @@ var DocumentCache = class {
213
353
  * the same document is cached under.
214
354
  */
215
355
  aliasKeys = /* @__PURE__ */ new Map();
356
+ /** Operations by document id, then scope. Entries are replaced, never mutated. */
357
+ operationEntries = /* @__PURE__ */ new Map();
358
+ /** In-flight controllers and the next page's cursor/limit, by document id then scope. */
359
+ operationRequests = /* @__PURE__ */ new Map();
360
+ operationListeners = /* @__PURE__ */ new Map();
216
361
  unsubscribe = null;
217
362
  constructor(client) {
218
363
  this.client = client;
@@ -223,13 +368,22 @@ var DocumentCache = class {
223
368
  handleDocumentChange(event) {
224
369
  if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {
225
370
  const documentId = event.context?.childId;
226
- if (documentId) this.handleDocumentDeleted(documentId);
227
- } else if (event.type === DOCUMENT_CHANGE_TYPE.Updated) for (const doc of event.documents) this.handleDocumentUpdated(doc.header.id).catch(console.warn);
371
+ if (documentId) {
372
+ const keys = this.cacheKeysFor(documentId);
373
+ this.handleDocumentDeleted(documentId);
374
+ for (const key of keys) this.invalidateOperations(key);
375
+ }
376
+ } else if (event.type === DOCUMENT_CHANGE_TYPE.Updated) for (const doc of event.documents) {
377
+ const keys = this.cacheKeysFor(doc.header.id);
378
+ this.handleDocumentUpdated(doc.header.id).catch(console.warn);
379
+ for (const key of keys) this.refreshOperations(key);
380
+ }
228
381
  }
229
382
  handleDocumentDeleted(documentId) {
230
383
  for (const key of this.cacheKeysFor(documentId)) {
231
384
  const listeners = this.listeners.get(key);
232
385
  this.documents.delete(key);
386
+ this.refetcher.forget(key);
233
387
  this.invalidateBatchesContaining(key);
234
388
  if (listeners) listeners.forEach((listener) => listener());
235
389
  this.listeners.delete(key);
@@ -237,12 +391,11 @@ var DocumentCache = class {
237
391
  this.aliasKeys.delete(documentId);
238
392
  }
239
393
  async handleDocumentUpdated(documentId) {
240
- for (const key of this.cacheKeysFor(documentId)) {
241
- if (!this.documents.has(key)) continue;
242
- await this.get(key, true);
243
- const listeners = this.listeners.get(key);
244
- if (listeners) listeners.forEach((listener) => listener());
245
- }
394
+ const refetches = this.cacheKeysFor(documentId).filter((key) => this.documents.has(key)).map((key) => this.get(key, true));
395
+ await Promise.all(refetches);
396
+ }
397
+ notifyListeners(key) {
398
+ for (const listener of this.listeners.get(key) ?? []) listener();
246
399
  }
247
400
  /** The id an event dispatches by, plus every alias the document is cached under. */
248
401
  cacheKeysFor(documentId) {
@@ -259,10 +412,9 @@ var DocumentCache = class {
259
412
  }
260
413
  get(id, refetch) {
261
414
  const currentData = this.documents.get(id);
262
- if (currentData) {
263
- if (currentData.status === "pending") return currentData;
264
- if (!refetch) return currentData;
265
- }
415
+ if (currentData && !refetch) return currentData;
416
+ if (currentData && currentData.status !== "rejected") return this.refetcher.refetch(id);
417
+ this.refetcher.forget(id);
266
418
  const documentPromise = this.client.get(id);
267
419
  documentPromise.then((doc) => {
268
420
  if (doc.header.id !== id) this.recordAlias(doc.header.id, id);
@@ -270,6 +422,9 @@ var DocumentCache = class {
270
422
  this.documents.set(id, addPromiseState(documentPromise));
271
423
  return documentPromise;
272
424
  }
425
+ getRefetchState(id) {
426
+ return this.refetcher.getState(id);
427
+ }
273
428
  getBatch(ids) {
274
429
  const key = ids.join(",");
275
430
  const cached = this.batchPromises.get(key);
@@ -319,6 +474,161 @@ var DocumentCache = class {
319
474
  }
320
475
  };
321
476
  }
477
+ getOperationsState(documentId, scope) {
478
+ return this.operationEntries.get(documentId)?.get(scope) ?? IDLE_OPERATIONS_ENTRY;
479
+ }
480
+ loadOperations(documentId, scope, limit) {
481
+ const current = this.getOperationsState(documentId, scope);
482
+ if (current.status !== "idle") return;
483
+ const controller = new AbortController();
484
+ this.setOperationsRequest(documentId, scope, {
485
+ controller,
486
+ nextCursor: void 0,
487
+ limit
488
+ });
489
+ this.setOperationsEntry(documentId, scope, {
490
+ ...current,
491
+ status: "pending"
492
+ });
493
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, void 0, {
494
+ cursor: "",
495
+ limit
496
+ }, controller.signal), controller, limit);
497
+ }
498
+ loadMoreOperations(documentId, scope) {
499
+ const current = this.getOperationsState(documentId, scope);
500
+ const request = this.operationRequests.get(documentId)?.get(scope);
501
+ if (current.status !== "success" || !current.hasNextPage || !request?.nextCursor) return;
502
+ const controller = new AbortController();
503
+ const { nextCursor, limit } = request;
504
+ this.setOperationsRequest(documentId, scope, {
505
+ controller,
506
+ nextCursor,
507
+ limit
508
+ });
509
+ this.setOperationsEntry(documentId, scope, {
510
+ ...current,
511
+ status: "pending"
512
+ });
513
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, void 0, {
514
+ cursor: nextCursor,
515
+ limit
516
+ }, controller.signal), controller, limit);
517
+ }
518
+ /**
519
+ * Bring a document's cached scopes up to date after it changed, without
520
+ * throwing away what is already loaded.
521
+ *
522
+ * The operation stream is append-only: an update adds operations at higher
523
+ * revisions and never rewrites the ones below, so history already paged in
524
+ * is still correct. Dropping it meant a panel showing a fully loaded
525
+ * document re-walked every page on each edit -- the cost of which grows
526
+ * with the document, exactly where it hurts most. Each scope instead asks
527
+ * only for what comes after the newest revision it holds, using the
528
+ * `sinceRevision` filter, and appends the answer.
529
+ *
530
+ * A scope that has not finished paging is dropped as before: it has no
531
+ * meaningful "newest revision" to resume from, since asking for everything
532
+ * past the newest row it happens to hold would skip the pages between that
533
+ * row and the end of the stream.
534
+ */
535
+ refreshOperations(documentId) {
536
+ const scopes = this.operationEntries.get(documentId);
537
+ if (!scopes) return;
538
+ for (const [scope, entry] of [...scopes.entries()]) {
539
+ if (entry.status !== "success" || entry.hasNextPage) {
540
+ this.invalidateOperationsScope(documentId, scope);
541
+ continue;
542
+ }
543
+ const previous = this.operationRequests.get(documentId)?.get(scope);
544
+ const limit = previous?.limit ?? FALLBACK_REFRESH_LIMIT;
545
+ previous?.controller.abort();
546
+ const controller = new AbortController();
547
+ this.setOperationsRequest(documentId, scope, {
548
+ controller,
549
+ nextCursor: void 0,
550
+ limit
551
+ });
552
+ this.setOperationsEntry(documentId, scope, {
553
+ ...entry,
554
+ status: "pending"
555
+ });
556
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, { sinceRevision: highestOperationIndex(entry.operations) + 1 }, {
557
+ cursor: "",
558
+ limit
559
+ }, controller.signal), controller, limit);
560
+ }
561
+ }
562
+ /** Drops one scope of a document, aborting its request if one is in flight. */
563
+ invalidateOperationsScope(documentId, scope) {
564
+ const requests = this.operationRequests.get(documentId);
565
+ const request = requests?.get(scope);
566
+ if (request && requests) {
567
+ request.controller.abort();
568
+ requests.delete(scope);
569
+ if (requests.size === 0) this.operationRequests.delete(documentId);
570
+ }
571
+ const scopes = this.operationEntries.get(documentId);
572
+ if (scopes?.delete(scope)) {
573
+ if (scopes.size === 0) this.operationEntries.delete(documentId);
574
+ this.notifyOperationListeners(documentId);
575
+ }
576
+ }
577
+ invalidateOperations(documentId) {
578
+ const requests = this.operationRequests.get(documentId);
579
+ if (requests) {
580
+ for (const request of requests.values()) request.controller.abort();
581
+ this.operationRequests.delete(documentId);
582
+ }
583
+ if (this.operationEntries.delete(documentId)) this.notifyOperationListeners(documentId);
584
+ }
585
+ subscribeOperations(documentId, callback) {
586
+ const listeners = this.operationListeners.get(documentId) ?? [];
587
+ this.operationListeners.set(documentId, [...listeners, callback]);
588
+ return () => {
589
+ const current = this.operationListeners.get(documentId) ?? [];
590
+ this.operationListeners.set(documentId, current.filter((listener) => listener !== callback));
591
+ };
592
+ }
593
+ settleOperationsPage(documentId, scope, page, controller, limit) {
594
+ page.then((result) => {
595
+ if (controller.signal.aborted) return;
596
+ const current = this.getOperationsState(documentId, scope);
597
+ this.setOperationsRequest(documentId, scope, {
598
+ controller,
599
+ nextCursor: result.nextCursor,
600
+ limit
601
+ });
602
+ this.setOperationsEntry(documentId, scope, {
603
+ status: "success",
604
+ operations: [...current.operations, ...result.results],
605
+ error: void 0,
606
+ hasNextPage: !!result.nextCursor
607
+ });
608
+ }, (reason) => {
609
+ if (controller.signal.aborted) return;
610
+ const current = this.getOperationsState(documentId, scope);
611
+ this.setOperationsEntry(documentId, scope, {
612
+ ...current,
613
+ status: "error",
614
+ error: reason
615
+ });
616
+ });
617
+ }
618
+ setOperationsEntry(documentId, scope, entry) {
619
+ const scopes = this.operationEntries.get(documentId) ?? /* @__PURE__ */ new Map();
620
+ scopes.set(scope, entry);
621
+ this.operationEntries.set(documentId, scopes);
622
+ this.notifyOperationListeners(documentId);
623
+ }
624
+ setOperationsRequest(documentId, scope, request) {
625
+ const scopes = this.operationRequests.get(documentId) ?? /* @__PURE__ */ new Map();
626
+ scopes.set(scope, request);
627
+ this.operationRequests.set(documentId, scopes);
628
+ }
629
+ notifyOperationListeners(documentId) {
630
+ for (const listener of this.operationListeners.get(documentId) ?? []) listener();
631
+ }
322
632
  /**
323
633
  * Disposes of the cache and unsubscribes from document change events.
324
634
  */
@@ -327,6 +637,11 @@ var DocumentCache = class {
327
637
  this.unsubscribe();
328
638
  this.unsubscribe = null;
329
639
  }
640
+ for (const requests of this.operationRequests.values()) for (const request of requests.values()) request.controller.abort();
641
+ this.operationRequests.clear();
642
+ this.operationEntries.clear();
643
+ this.refetcher.clear();
644
+ this.operationListeners.clear();
330
645
  }
331
646
  };
332
647
  //#endregion
@@ -393,10 +708,14 @@ function useDocument(id) {
393
708
  * - isPending: Whether the document is currently loading
394
709
  * - error: Any error that occurred during loading (e.g., document not found)
395
710
  * - reload: Function to force a refetch, or undefined when no id is supplied
711
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
712
+ * - refetchError: The last refetch failure that kept the loaded document
396
713
  */
397
714
  function useDocumentSafe(id) {
398
715
  const documentCache = useDocumentCache();
399
- const promise = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);
716
+ const subscribe = (cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {};
717
+ const promise = useSyncExternalStore(subscribe, () => id ? documentCache?.get(id) : void 0);
718
+ const refetch = useSyncExternalStore(subscribe, () => readRefetchState(documentCache, id));
400
719
  const [, bumpOnSettle] = useReducer((count) => count + 1, 0);
401
720
  const pendingPromise = promise && readPromiseState(promise).status === "pending" ? promise : null;
402
721
  useEffect(() => {
@@ -415,13 +734,20 @@ function useDocumentSafe(id) {
415
734
  isPending: false,
416
735
  error: void 0,
417
736
  data: void 0,
418
- reload: void 0
737
+ reload: void 0,
738
+ isRefetching: false,
739
+ refetchError: void 0
419
740
  };
420
741
  return {
421
742
  ...getDocumentQueryState(promise),
422
- reload: () => documentCache.get(id, true)
743
+ reload: () => documentCache.get(id, true),
744
+ isRefetching: refetch.isRefetching,
745
+ refetchError: refetch.error
423
746
  };
424
747
  }
748
+ function readRefetchState(documentCache, id) {
749
+ return id && documentCache?.getRefetchState?.(id) || IDLE_REFETCH_STATE;
750
+ }
425
751
  /**
426
752
  * Retrieves multiple documents from the reactor using React Suspense.
427
753
  * This hook will suspend rendering while any of the documents are loading.
@@ -471,6 +797,8 @@ function useGetDocuments() {
471
797
  * - isPending: Boolean indicating if the document is currently loading
472
798
  * - error: Any error that occurred during loading
473
799
  * - reload: Function to force reload the document from cache
800
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
801
+ * - refetchError: The last refetch failure that kept the loaded document
474
802
  */
475
803
  function useGetDocumentAsync(id) {
476
804
  const documentCache = useDocumentCache();
@@ -479,11 +807,17 @@ function useGetDocumentAsync(id) {
479
807
  data: void 0,
480
808
  isPending: false,
481
809
  error: void 0,
482
- reload: void 0
810
+ reload: void 0,
811
+ isRefetching: false,
812
+ refetchError: void 0
483
813
  };
814
+ const state = getDocumentQueryState(documentCache.get(id));
815
+ const refetch = readRefetchState(documentCache, id);
484
816
  return {
485
- ...getDocumentQueryState(documentCache.get(id)),
486
- reload: () => documentCache.get(id, true)
817
+ ...state,
818
+ reload: () => documentCache.get(id, true),
819
+ isRefetching: refetch.isRefetching,
820
+ refetchError: refetch.error
487
821
  };
488
822
  }
489
823
  //#endregion
@@ -495,23 +829,13 @@ function useDispatch(document) {
495
829
  * @param onErrors - Callback invoked with any errors that occurred during action execution.
496
830
  */
497
831
  function dispatch(actionOrActions, onErrors, onSuccess) {
498
- dispatchActions(actionOrActions, document, onErrors, onSuccess).catch(logger.error);
832
+ dispatchActions(actionOrActions, document, onErrors, onSuccess).catch((error) => {
833
+ logger.error("Failed to dispatch actions: @error", error);
834
+ });
499
835
  }
500
836
  return [document, dispatch];
501
837
  }
502
838
  //#endregion
503
- //#region src/hooks/document-by-id.ts
504
- /** Returns a document by id. */
505
- function useDocumentById(id) {
506
- const document = useDocument(id);
507
- const [, dispatch] = useDispatch(document);
508
- return [document, dispatch];
509
- }
510
- /** Returns documents by ids. */
511
- function useDocumentsByIds(ids) {
512
- return useDocuments(ids);
513
- }
514
- //#endregion
515
- export { uploadOperations as S, isDuplicateManifestError as _, setDocumentCache as a, queueActions as b, useDocumentSafe as c, useGetDocumentAsync as d, useGetDocuments as f, DOCUMENT_CHANGE_TYPE as g, readPromiseState as h, addDocumentCacheEventHandler as i, useDocuments as l, addPromiseState as m, useDocumentsByIds as n, useDocument as o, DocumentCache as p, useDispatch as r, useDocumentCache as s, useDocumentById as t, useGetDocument as u, isDuplicateModuleError as v, queueOperations as x, dispatchActions as y };
839
+ export { queueOperations as C, queueActions as S, isDuplicateManifestError as _, useDocumentCache as a, IDLE_REFETCH_STATE as b, useGetDocument as c, DocumentCache as d, IDLE_OPERATIONS_ENTRY as f, DOCUMENT_CHANGE_TYPE as g, readPromiseState as h, useDocument as i, useGetDocumentAsync as l, isOperationCache as m, addDocumentCacheEventHandler as n, useDocumentSafe as o, addPromiseState as p, setDocumentCache as r, useDocuments as s, useDispatch as t, useGetDocuments as u, isDuplicateModuleError as v, uploadOperations as w, dispatchActions as x, DocumentRefetcher as y };
516
840
 
517
- //# sourceMappingURL=document-by-id-BSZqTN66.js.map
841
+ //# sourceMappingURL=dispatch-BOQgTK9B.js.map