@powerhousedao/reactor-browser 6.2.3-dev.9 → 6.2.3-staging.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.
Files changed (85) hide show
  1. package/dist/{attachment-service-D3EhiAJ7.d.ts → attachment-service-But1Xljo.d.ts} +169 -59
  2. package/dist/attachment-service-But1Xljo.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-B4FIzG1w.js → dispatch-qRXS70fh.js} +389 -54
  10. package/dist/dispatch-qRXS70fh.js.map +1 -0
  11. package/dist/document-by-id-B_8DA4yZ.js +16 -0
  12. package/dist/document-by-id-B_8DA4yZ.js.map +1 -0
  13. package/dist/{document-model-modules-bTP87nyr.js → document-model-modules-D6I-UUXq.js} +32 -65
  14. package/dist/document-model-modules-D6I-UUXq.js.map +1 -0
  15. package/dist/{document-operations-WeE6wIDt.js → document-operations-Bt-1-ThH.js} +147 -120
  16. package/dist/document-operations-Bt-1-ThH.js.map +1 -0
  17. package/dist/{global-OuINvEGT.d.ts → global-fql2bmb0.d.ts} +50 -13
  18. package/dist/global-fql2bmb0.d.ts.map +1 -0
  19. package/dist/{index-B33TKEqp.d.ts → index-BABMK8cO.d.ts} +19 -98
  20. package/dist/index-BABMK8cO.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 +379 -364
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +111 -39
  26. package/dist/index.js.map +1 -1
  27. package/dist/{inspector-proxy-6h5VKAwt.d.ts → inspector-proxy-DCowaeeH.d.ts} +11 -4
  28. package/dist/inspector-proxy-DCowaeeH.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-D1RB45sA.js → relational-ChC_AWAK.js} +3 -2
  34. package/dist/{relational-D1RB45sA.js.map → relational-ChC_AWAK.js.map} +1 -1
  35. package/dist/{renown-rqK8sokh.js → renown-C9pYZRqf.js} +7 -8
  36. package/dist/{renown-rqK8sokh.js.map → renown-C9pYZRqf.js.map} +1 -1
  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 +2 -2
  59. package/dist/src/rpc/index.d.ts +52 -32
  60. package/dist/src/rpc/index.d.ts.map +1 -1
  61. package/dist/src/rpc/index.js +58 -9
  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-CaXQ4-5Q.js → switchboard-CFyD_5_e.js} +58 -6
  66. package/dist/switchboard-CFyD_5_e.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-D3EhiAJ7.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-B4FIzG1w.js.map +0 -1
  76. package/dist/document-model-modules-bTP87nyr.js.map +0 -1
  77. package/dist/document-operations-WeE6wIDt.js.map +0 -1
  78. package/dist/global-OuINvEGT.d.ts.map +0 -1
  79. package/dist/index-B33TKEqp.d.ts.map +0 -1
  80. package/dist/index-BIVDXw3K.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/switchboard-CaXQ4-5Q.js.map +0 -1
  84. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  85. 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
@@ -119,12 +107,16 @@ function getActionErrors(result, actions) {
119
107
  async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {
120
108
  const document = typeof documentOrDocumentId === "string" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;
121
109
  if (!document) {
122
- logger.error(`Document with id ${JSON.stringify(documentOrDocumentId)} not found`);
110
+ const message = `Document with id ${JSON.stringify(documentOrDocumentId)} not found`;
111
+ logger.error(message);
112
+ onErrors?.([new Error(message)]);
123
113
  return;
124
114
  }
125
- const signedActionsWithContext = await makeSignedActionsWithContext(actionOrActions, document);
115
+ const signedActionsWithContext = makeSignedActionsWithContext(actionOrActions, document);
126
116
  if (!signedActionsWithContext) {
127
- logger.error("No signed actions with context found");
117
+ const message = "No signed actions with context found";
118
+ logger.error(message);
119
+ onErrors?.([/* @__PURE__ */ new Error(message)]);
128
120
  return;
129
121
  }
130
122
  const result = await queueActions(document, signedActionsWithContext);
@@ -135,6 +127,119 @@ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors,
135
127
  if (onSuccess && result) onSuccess(result);
136
128
  return result;
137
129
  }
130
+ //#endregion
131
+ //#region src/document-refetcher.ts
132
+ /** The refetch snapshot of a document with nothing in flight and no kept failure. */
133
+ const IDLE_REFETCH_STATE = Object.freeze({
134
+ isRefetching: false,
135
+ error: void 0
136
+ });
137
+ function fulfilledPromise(value) {
138
+ const promise = Promise.resolve(value);
139
+ promise.status = "fulfilled";
140
+ promise.value = value;
141
+ return promise;
142
+ }
143
+ function rejectedPromise(reason) {
144
+ const promise = Promise.reject(reason);
145
+ promise.status = "rejected";
146
+ promise.reason = reason;
147
+ promise.catch(() => void 0);
148
+ return promise;
149
+ }
150
+ const MISSING_DOCUMENT_ERRORS = ["DocumentNotFoundError", "DocumentDeletedError"];
151
+ function isMissingDocumentError(error) {
152
+ if (!(error instanceof Error)) return false;
153
+ return MISSING_DOCUMENT_ERRORS.includes(error.name) || error.message.startsWith("Document not found");
154
+ }
155
+ const noop = () => void 0;
156
+ /** Background refetch of loaded documents: readers keep the loaded promise until it settles. */
157
+ var DocumentRefetcher = class {
158
+ host;
159
+ refetches = /* @__PURE__ */ new Map();
160
+ states = /* @__PURE__ */ new Map();
161
+ constructor(host) {
162
+ this.host = host;
163
+ }
164
+ getState(id) {
165
+ return this.states.get(id) ?? IDLE_REFETCH_STATE;
166
+ }
167
+ /** Serializes refetches per key: one runs, later requests share one queued run. */
168
+ refetch(id) {
169
+ let entry = this.refetches.get(id);
170
+ if (!entry) {
171
+ entry = {
172
+ running: void 0,
173
+ queued: void 0
174
+ };
175
+ this.refetches.set(id, entry);
176
+ const current = this.host.documents.get(id);
177
+ if (current?.status !== "pending") return this.start(id, entry);
178
+ entry.running = current;
179
+ }
180
+ const inFlight = entry;
181
+ inFlight.queued ??= (inFlight.running ?? Promise.resolve()).then(noop, noop).then(() => this.start(id, inFlight));
182
+ return inFlight.queued;
183
+ }
184
+ /** Stops any refetch of `id` from writing back, e.g. on deletion. */
185
+ forget(id) {
186
+ this.refetches.delete(id);
187
+ this.states.delete(id);
188
+ }
189
+ clear() {
190
+ this.refetches.clear();
191
+ this.states.clear();
192
+ }
193
+ start(id, entry) {
194
+ entry.queued = void 0;
195
+ entry.running = this.run(id, entry);
196
+ return entry.running;
197
+ }
198
+ async run(id, entry) {
199
+ const isCurrent = () => this.refetches.get(id) === entry;
200
+ if (!isCurrent()) return this.host.fetch(id);
201
+ if (this.setState(id, {
202
+ isRefetching: true,
203
+ error: this.getState(id).error
204
+ })) this.host.notify(id);
205
+ try {
206
+ const document = await this.host.fetch(id);
207
+ if (isCurrent()) {
208
+ this.host.onFetched?.(id, document);
209
+ this.host.documents.set(id, fulfilledPromise(document));
210
+ this.finish(id, entry, void 0);
211
+ }
212
+ return document;
213
+ } catch (error) {
214
+ if (isCurrent()) {
215
+ if (isMissingDocumentError(error)) {
216
+ this.host.documents.set(id, rejectedPromise(error));
217
+ this.finish(id, entry, void 0);
218
+ } else {
219
+ console.warn("[DocumentCache] Refetch failed; keeping the loaded document:", error);
220
+ this.finish(id, entry, error);
221
+ }
222
+ }
223
+ throw error;
224
+ }
225
+ }
226
+ finish(id, entry, error) {
227
+ if (!entry.queued) this.refetches.delete(id);
228
+ this.setState(id, {
229
+ isRefetching: entry.queued !== void 0,
230
+ error
231
+ });
232
+ this.host.notify(id);
233
+ }
234
+ /** Returns whether the snapshot changed; the caller notifies. */
235
+ setState(id, state) {
236
+ const current = this.getState(id);
237
+ if (current.isRefetching === state.isRefetching && current.error === state.error) return false;
238
+ if (!state.isRefetching && state.error === void 0) this.states.delete(id);
239
+ else this.states.set(id, Object.freeze({ ...state }));
240
+ return true;
241
+ }
242
+ };
138
243
  /**
139
244
  * The reactor's `DocumentChangeType` members, typed as the enum so they can be
140
245
  * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
@@ -195,16 +300,55 @@ function fulfilledOnly(promises) {
195
300
  return documents;
196
301
  });
197
302
  }
303
+ /** The snapshot every uncached document scope reads as. One frozen object, so `useSyncExternalStore` sees a stable value. */
304
+ const IDLE_OPERATIONS_ENTRY = Object.freeze({
305
+ status: "idle",
306
+ operations: Object.freeze([]),
307
+ error: void 0,
308
+ hasNextPage: false
309
+ });
310
+ /** Whether a document cache also serves operation history. `GraphQLClientDocumentCache` does not. */
311
+ function isOperationCache(cache) {
312
+ if (typeof cache !== "object" || cache === null) return false;
313
+ const candidate = cache;
314
+ return typeof candidate.getOperationsState === "function" && typeof candidate.loadOperations === "function" && typeof candidate.loadMoreOperations === "function" && typeof candidate.invalidateOperations === "function" && typeof candidate.subscribeOperations === "function";
315
+ }
316
+ /**
317
+ * Page size used to refresh a scope whose request record has gone missing.
318
+ * A loaded scope always has one, so this is a floor rather than a default.
319
+ */
320
+ const FALLBACK_REFRESH_LIMIT = 100;
321
+ /**
322
+ * The highest revision among the operations loaded so far, or -1 for none.
323
+ * Pages arrive oldest first, so this is normally the last entry; it is
324
+ * computed rather than assumed because nothing in the cache enforces that.
325
+ */
326
+ function highestOperationIndex(operations) {
327
+ let highest = -1;
328
+ for (const operation of operations) if (operation.index > highest) highest = operation.index;
329
+ return highest;
330
+ }
198
331
  /**
199
332
  * Document cache implementation that uses the new ReactorClient API.
200
333
  *
201
334
  * This cache subscribes to document change events via IReactorBrowserClient.subscribe()
202
335
  * and automatically updates the cache when documents are created, updated, or deleted.
336
+ * It also holds paginated operation history per document scope (see `IOperationCache`),
337
+ * which is dropped for a document whenever a change event for it arrives.
203
338
  */
204
339
  var DocumentCache = class {
340
+ client;
205
341
  documents = /* @__PURE__ */ new Map();
206
342
  batchPromises = /* @__PURE__ */ new Map();
207
343
  listeners = /* @__PURE__ */ new Map();
344
+ refetcher = new DocumentRefetcher({
345
+ documents: this.documents,
346
+ fetch: (id) => this.client.get(id),
347
+ notify: (id) => this.notifyListeners(id),
348
+ onFetched: (id, document) => {
349
+ if (document.header.id !== id) this.recordAlias(document.header.id, id);
350
+ }
351
+ });
208
352
  /**
209
353
  * Cache keys that fetched a document under a name other than its id --
210
354
  * slugs, which `client.get` resolves. Change events dispatch by `header.id`,
@@ -213,6 +357,11 @@ var DocumentCache = class {
213
357
  * the same document is cached under.
214
358
  */
215
359
  aliasKeys = /* @__PURE__ */ new Map();
360
+ /** Operations by document id, then scope. Entries are replaced, never mutated. */
361
+ operationEntries = /* @__PURE__ */ new Map();
362
+ /** In-flight controllers and the next page's cursor/limit, by document id then scope. */
363
+ operationRequests = /* @__PURE__ */ new Map();
364
+ operationListeners = /* @__PURE__ */ new Map();
216
365
  unsubscribe = null;
217
366
  constructor(client) {
218
367
  this.client = client;
@@ -223,13 +372,22 @@ var DocumentCache = class {
223
372
  handleDocumentChange(event) {
224
373
  if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {
225
374
  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);
375
+ if (documentId) {
376
+ const keys = this.cacheKeysFor(documentId);
377
+ this.handleDocumentDeleted(documentId);
378
+ for (const key of keys) this.invalidateOperations(key);
379
+ }
380
+ } else if (event.type === DOCUMENT_CHANGE_TYPE.Updated) for (const doc of event.documents) {
381
+ const keys = this.cacheKeysFor(doc.header.id);
382
+ this.handleDocumentUpdated(doc.header.id).catch(console.warn);
383
+ for (const key of keys) this.refreshOperations(key);
384
+ }
228
385
  }
229
386
  handleDocumentDeleted(documentId) {
230
387
  for (const key of this.cacheKeysFor(documentId)) {
231
388
  const listeners = this.listeners.get(key);
232
389
  this.documents.delete(key);
390
+ this.refetcher.forget(key);
233
391
  this.invalidateBatchesContaining(key);
234
392
  if (listeners) listeners.forEach((listener) => listener());
235
393
  this.listeners.delete(key);
@@ -237,12 +395,11 @@ var DocumentCache = class {
237
395
  this.aliasKeys.delete(documentId);
238
396
  }
239
397
  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
- }
398
+ const refetches = this.cacheKeysFor(documentId).filter((key) => this.documents.has(key)).map((key) => this.get(key, true));
399
+ await Promise.all(refetches);
400
+ }
401
+ notifyListeners(key) {
402
+ for (const listener of this.listeners.get(key) ?? []) listener();
246
403
  }
247
404
  /** The id an event dispatches by, plus every alias the document is cached under. */
248
405
  cacheKeysFor(documentId) {
@@ -259,10 +416,9 @@ var DocumentCache = class {
259
416
  }
260
417
  get(id, refetch) {
261
418
  const currentData = this.documents.get(id);
262
- if (currentData) {
263
- if (currentData.status === "pending") return currentData;
264
- if (!refetch) return currentData;
265
- }
419
+ if (currentData && !refetch) return currentData;
420
+ if (currentData && currentData.status !== "rejected") return this.refetcher.refetch(id);
421
+ this.refetcher.forget(id);
266
422
  const documentPromise = this.client.get(id);
267
423
  documentPromise.then((doc) => {
268
424
  if (doc.header.id !== id) this.recordAlias(doc.header.id, id);
@@ -270,6 +426,9 @@ var DocumentCache = class {
270
426
  this.documents.set(id, addPromiseState(documentPromise));
271
427
  return documentPromise;
272
428
  }
429
+ getRefetchState(id) {
430
+ return this.refetcher.getState(id);
431
+ }
273
432
  getBatch(ids) {
274
433
  const key = ids.join(",");
275
434
  const cached = this.batchPromises.get(key);
@@ -319,6 +478,161 @@ var DocumentCache = class {
319
478
  }
320
479
  };
321
480
  }
481
+ getOperationsState(documentId, scope) {
482
+ return this.operationEntries.get(documentId)?.get(scope) ?? IDLE_OPERATIONS_ENTRY;
483
+ }
484
+ loadOperations(documentId, scope, limit) {
485
+ const current = this.getOperationsState(documentId, scope);
486
+ if (current.status !== "idle") return;
487
+ const controller = new AbortController();
488
+ this.setOperationsRequest(documentId, scope, {
489
+ controller,
490
+ nextCursor: void 0,
491
+ limit
492
+ });
493
+ this.setOperationsEntry(documentId, scope, {
494
+ ...current,
495
+ status: "pending"
496
+ });
497
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, void 0, {
498
+ cursor: "",
499
+ limit
500
+ }, controller.signal), controller, limit);
501
+ }
502
+ loadMoreOperations(documentId, scope) {
503
+ const current = this.getOperationsState(documentId, scope);
504
+ const request = this.operationRequests.get(documentId)?.get(scope);
505
+ if (current.status !== "success" || !current.hasNextPage || !request?.nextCursor) return;
506
+ const controller = new AbortController();
507
+ const { nextCursor, limit } = request;
508
+ this.setOperationsRequest(documentId, scope, {
509
+ controller,
510
+ nextCursor,
511
+ limit
512
+ });
513
+ this.setOperationsEntry(documentId, scope, {
514
+ ...current,
515
+ status: "pending"
516
+ });
517
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, void 0, {
518
+ cursor: nextCursor,
519
+ limit
520
+ }, controller.signal), controller, limit);
521
+ }
522
+ /**
523
+ * Bring a document's cached scopes up to date after it changed, without
524
+ * throwing away what is already loaded.
525
+ *
526
+ * The operation stream is append-only: an update adds operations at higher
527
+ * revisions and never rewrites the ones below, so history already paged in
528
+ * is still correct. Dropping it meant a panel showing a fully loaded
529
+ * document re-walked every page on each edit -- the cost of which grows
530
+ * with the document, exactly where it hurts most. Each scope instead asks
531
+ * only for what comes after the newest revision it holds, using the
532
+ * `sinceRevision` filter, and appends the answer.
533
+ *
534
+ * A scope that has not finished paging is dropped as before: it has no
535
+ * meaningful "newest revision" to resume from, since asking for everything
536
+ * past the newest row it happens to hold would skip the pages between that
537
+ * row and the end of the stream.
538
+ */
539
+ refreshOperations(documentId) {
540
+ const scopes = this.operationEntries.get(documentId);
541
+ if (!scopes) return;
542
+ for (const [scope, entry] of [...scopes.entries()]) {
543
+ if (entry.status !== "success" || entry.hasNextPage) {
544
+ this.invalidateOperationsScope(documentId, scope);
545
+ continue;
546
+ }
547
+ const previous = this.operationRequests.get(documentId)?.get(scope);
548
+ const limit = previous?.limit ?? FALLBACK_REFRESH_LIMIT;
549
+ previous?.controller.abort();
550
+ const controller = new AbortController();
551
+ this.setOperationsRequest(documentId, scope, {
552
+ controller,
553
+ nextCursor: void 0,
554
+ limit
555
+ });
556
+ this.setOperationsEntry(documentId, scope, {
557
+ ...entry,
558
+ status: "pending"
559
+ });
560
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, { sinceRevision: highestOperationIndex(entry.operations) + 1 }, {
561
+ cursor: "",
562
+ limit
563
+ }, controller.signal), controller, limit);
564
+ }
565
+ }
566
+ /** Drops one scope of a document, aborting its request if one is in flight. */
567
+ invalidateOperationsScope(documentId, scope) {
568
+ const requests = this.operationRequests.get(documentId);
569
+ const request = requests?.get(scope);
570
+ if (request && requests) {
571
+ request.controller.abort();
572
+ requests.delete(scope);
573
+ if (requests.size === 0) this.operationRequests.delete(documentId);
574
+ }
575
+ const scopes = this.operationEntries.get(documentId);
576
+ if (scopes?.delete(scope)) {
577
+ if (scopes.size === 0) this.operationEntries.delete(documentId);
578
+ this.notifyOperationListeners(documentId);
579
+ }
580
+ }
581
+ invalidateOperations(documentId) {
582
+ const requests = this.operationRequests.get(documentId);
583
+ if (requests) {
584
+ for (const request of requests.values()) request.controller.abort();
585
+ this.operationRequests.delete(documentId);
586
+ }
587
+ if (this.operationEntries.delete(documentId)) this.notifyOperationListeners(documentId);
588
+ }
589
+ subscribeOperations(documentId, callback) {
590
+ const listeners = this.operationListeners.get(documentId) ?? [];
591
+ this.operationListeners.set(documentId, [...listeners, callback]);
592
+ return () => {
593
+ const current = this.operationListeners.get(documentId) ?? [];
594
+ this.operationListeners.set(documentId, current.filter((listener) => listener !== callback));
595
+ };
596
+ }
597
+ settleOperationsPage(documentId, scope, page, controller, limit) {
598
+ page.then((result) => {
599
+ if (controller.signal.aborted) return;
600
+ const current = this.getOperationsState(documentId, scope);
601
+ this.setOperationsRequest(documentId, scope, {
602
+ controller,
603
+ nextCursor: result.nextCursor,
604
+ limit
605
+ });
606
+ this.setOperationsEntry(documentId, scope, {
607
+ status: "success",
608
+ operations: [...current.operations, ...result.results],
609
+ error: void 0,
610
+ hasNextPage: !!result.nextCursor
611
+ });
612
+ }, (reason) => {
613
+ if (controller.signal.aborted) return;
614
+ const current = this.getOperationsState(documentId, scope);
615
+ this.setOperationsEntry(documentId, scope, {
616
+ ...current,
617
+ status: "error",
618
+ error: reason
619
+ });
620
+ });
621
+ }
622
+ setOperationsEntry(documentId, scope, entry) {
623
+ const scopes = this.operationEntries.get(documentId) ?? /* @__PURE__ */ new Map();
624
+ scopes.set(scope, entry);
625
+ this.operationEntries.set(documentId, scopes);
626
+ this.notifyOperationListeners(documentId);
627
+ }
628
+ setOperationsRequest(documentId, scope, request) {
629
+ const scopes = this.operationRequests.get(documentId) ?? /* @__PURE__ */ new Map();
630
+ scopes.set(scope, request);
631
+ this.operationRequests.set(documentId, scopes);
632
+ }
633
+ notifyOperationListeners(documentId) {
634
+ for (const listener of this.operationListeners.get(documentId) ?? []) listener();
635
+ }
322
636
  /**
323
637
  * Disposes of the cache and unsubscribes from document change events.
324
638
  */
@@ -327,6 +641,11 @@ var DocumentCache = class {
327
641
  this.unsubscribe();
328
642
  this.unsubscribe = null;
329
643
  }
644
+ for (const requests of this.operationRequests.values()) for (const request of requests.values()) request.controller.abort();
645
+ this.operationRequests.clear();
646
+ this.operationEntries.clear();
647
+ this.refetcher.clear();
648
+ this.operationListeners.clear();
330
649
  }
331
650
  };
332
651
  //#endregion
@@ -393,10 +712,14 @@ function useDocument(id) {
393
712
  * - isPending: Whether the document is currently loading
394
713
  * - error: Any error that occurred during loading (e.g., document not found)
395
714
  * - reload: Function to force a refetch, or undefined when no id is supplied
715
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
716
+ * - refetchError: The last refetch failure that kept the loaded document
396
717
  */
397
718
  function useDocumentSafe(id) {
398
719
  const documentCache = useDocumentCache();
399
- const promise = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, () => id ? documentCache?.get(id) : void 0);
720
+ const subscribe = (cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {};
721
+ const promise = useSyncExternalStore(subscribe, () => id ? documentCache?.get(id) : void 0);
722
+ const refetch = useSyncExternalStore(subscribe, () => readRefetchState(documentCache, id));
400
723
  const [, bumpOnSettle] = useReducer((count) => count + 1, 0);
401
724
  const pendingPromise = promise && readPromiseState(promise).status === "pending" ? promise : null;
402
725
  useEffect(() => {
@@ -415,13 +738,20 @@ function useDocumentSafe(id) {
415
738
  isPending: false,
416
739
  error: void 0,
417
740
  data: void 0,
418
- reload: void 0
741
+ reload: void 0,
742
+ isRefetching: false,
743
+ refetchError: void 0
419
744
  };
420
745
  return {
421
746
  ...getDocumentQueryState(promise),
422
- reload: () => documentCache.get(id, true)
747
+ reload: () => documentCache.get(id, true),
748
+ isRefetching: refetch.isRefetching,
749
+ refetchError: refetch.error
423
750
  };
424
751
  }
752
+ function readRefetchState(documentCache, id) {
753
+ return id && documentCache?.getRefetchState?.(id) || IDLE_REFETCH_STATE;
754
+ }
425
755
  /**
426
756
  * Retrieves multiple documents from the reactor using React Suspense.
427
757
  * This hook will suspend rendering while any of the documents are loading.
@@ -471,6 +801,8 @@ function useGetDocuments() {
471
801
  * - isPending: Boolean indicating if the document is currently loading
472
802
  * - error: Any error that occurred during loading
473
803
  * - reload: Function to force reload the document from cache
804
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
805
+ * - refetchError: The last refetch failure that kept the loaded document
474
806
  */
475
807
  function useGetDocumentAsync(id) {
476
808
  const documentCache = useDocumentCache();
@@ -479,11 +811,17 @@ function useGetDocumentAsync(id) {
479
811
  data: void 0,
480
812
  isPending: false,
481
813
  error: void 0,
482
- reload: void 0
814
+ reload: void 0,
815
+ isRefetching: false,
816
+ refetchError: void 0
483
817
  };
818
+ const state = getDocumentQueryState(documentCache.get(id));
819
+ const refetch = readRefetchState(documentCache, id);
484
820
  return {
485
- ...getDocumentQueryState(documentCache.get(id)),
486
- reload: () => documentCache.get(id, true)
821
+ ...state,
822
+ reload: () => documentCache.get(id, true),
823
+ isRefetching: refetch.isRefetching,
824
+ refetchError: refetch.error
487
825
  };
488
826
  }
489
827
  //#endregion
@@ -492,28 +830,25 @@ function useDispatch(document) {
492
830
  /**
493
831
  * Dispatches actions to the document.
494
832
  * @param actionOrActions - The action or actions to dispatch.
495
- * @param onErrors - Callback invoked with any errors that occurred during action execution.
833
+ * @param onErrors - Callback invoked with any errors that occurred during action execution,
834
+ * or with the failure when the dispatch itself did not complete.
496
835
  */
497
836
  function dispatch(actionOrActions, onErrors, onSuccess) {
498
- dispatchActions(actionOrActions, document, onErrors, onSuccess).catch((error) => {
837
+ let answered = false;
838
+ dispatchActions(actionOrActions, document, onErrors && ((errors) => {
839
+ answered = true;
840
+ onErrors(errors);
841
+ }), onSuccess && ((result) => {
842
+ answered = true;
843
+ onSuccess(result);
844
+ })).catch((error) => {
499
845
  logger.error("Failed to dispatch actions: @error", error);
846
+ if (!answered) onErrors?.([error instanceof Error ? error : new Error(String(error))]);
500
847
  });
501
848
  }
502
849
  return [document, dispatch];
503
850
  }
504
851
  //#endregion
505
- //#region src/hooks/document-by-id.ts
506
- /** Returns a document by id. */
507
- function useDocumentById(id) {
508
- const document = useDocument(id);
509
- const [, dispatch] = useDispatch(document);
510
- return [document, dispatch];
511
- }
512
- /** Returns documents by ids. */
513
- function useDocumentsByIds(ids) {
514
- return useDocuments(ids);
515
- }
516
- //#endregion
517
- 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 };
852
+ 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 };
518
853
 
519
- //# sourceMappingURL=document-by-id-B4FIzG1w.js.map
854
+ //# sourceMappingURL=dispatch-qRXS70fh.js.map