@powerhousedao/reactor-browser 6.2.3-dev.8 → 6.2.3-dev.81

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 (95) hide show
  1. package/dist/{attachment-service-D3EhiAJ7.d.ts → attachment-service-DPWkKp3y.d.ts} +636 -83
  2. package/dist/attachment-service-DPWkKp3y.d.ts.map +1 -0
  3. package/dist/{client-DjK30EQ-.js → client-BFnMV-EO.js} +39 -22
  4. package/dist/client-BFnMV-EO.js.map +1 -0
  5. package/dist/{client-D66jVnot.js → client-BUpynoY6.js} +345 -33
  6. package/dist/client-BUpynoY6.js.map +1 -0
  7. package/dist/{client-BIHN_UyR.d.ts → client-XPGQrO4a.d.ts} +3 -3
  8. package/dist/client-XPGQrO4a.d.ts.map +1 -0
  9. package/dist/dispatch-C8J9jQ-o.js +1171 -0
  10. package/dist/dispatch-C8J9jQ-o.js.map +1 -0
  11. package/dist/document-by-id-Dpp76ZNE.js +16 -0
  12. package/dist/document-by-id-Dpp76ZNE.js.map +1 -0
  13. package/dist/document-model-modules-XrYfGXt8.js +644 -0
  14. package/dist/document-model-modules-XrYfGXt8.js.map +1 -0
  15. package/dist/{document-operations-WeE6wIDt.js → document-operations-CdfiLNQN.js} +1919 -278
  16. package/dist/document-operations-CdfiLNQN.js.map +1 -0
  17. package/dist/global-BSyOOTvL.d.ts +647 -0
  18. package/dist/global-BSyOOTvL.d.ts.map +1 -0
  19. package/dist/{index-B33TKEqp.d.ts → index-Bjm0bSzf.d.ts} +19 -98
  20. package/dist/index-Bjm0bSzf.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 +813 -410
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +771 -119
  26. package/dist/index.js.map +1 -1
  27. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  28. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  29. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  30. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  31. package/dist/navigation-BqphkrOB.js +302 -0
  32. package/dist/navigation-BqphkrOB.js.map +1 -0
  33. package/dist/{pglite-CntadC_p-9NDG14dS.d.ts → pglite-CntadC_p-DTkdF8sr.d.ts} +11 -33
  34. package/dist/pglite-CntadC_p-DTkdF8sr.d.ts.map +1 -0
  35. package/dist/{relational-D1RB45sA.js → relational-DZuyKp2y.js} +66 -5
  36. package/dist/relational-DZuyKp2y.js.map +1 -0
  37. package/dist/{renown-rqK8sokh.js → renown-BtjgHBjH.js} +33 -28
  38. package/dist/{renown-rqK8sokh.js.map → renown-BtjgHBjH.js.map} +1 -1
  39. package/dist/{renown-BHxwP7xU.js → renown-BxkZYzbQ.js} +2 -2
  40. package/dist/{renown-BHxwP7xU.js.map → renown-BxkZYzbQ.js.map} +1 -1
  41. package/dist/src/ai/index.d.ts +53 -70
  42. package/dist/src/ai/index.d.ts.map +1 -1
  43. package/dist/src/ai/index.js +12 -28
  44. package/dist/src/ai/index.js.map +1 -1
  45. package/dist/src/analytics/index.d.ts +36 -44
  46. package/dist/src/analytics/index.d.ts.map +1 -1
  47. package/dist/src/analytics/index.js +4 -4
  48. package/dist/src/analytics/index.js.map +1 -1
  49. package/dist/src/document-model.d.ts +3 -4
  50. package/dist/src/document-model.d.ts.map +1 -1
  51. package/dist/src/document-model.js.map +1 -1
  52. package/dist/src/graphql/client.d.ts +4 -3
  53. package/dist/src/graphql/client.js +1 -1
  54. package/dist/src/graphql-client/entry.d.ts +5 -4
  55. package/dist/src/graphql-client/entry.js +4 -4
  56. package/dist/src/relational/index.d.ts +15 -9
  57. package/dist/src/relational/index.d.ts.map +1 -1
  58. package/dist/src/relational/index.js +1 -1
  59. package/dist/src/renown/index.d.ts +3 -2
  60. package/dist/src/renown/index.js +2 -2
  61. package/dist/src/rpc/index.d.ts +214 -140
  62. package/dist/src/rpc/index.d.ts.map +1 -1
  63. package/dist/src/rpc/index.js +587 -622
  64. package/dist/src/rpc/index.js.map +1 -1
  65. package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
  66. package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
  67. package/dist/{switchboard-CaXQ4-5Q.js → switchboard-CYTCYt4Z.js} +61 -11
  68. package/dist/switchboard-CYTCYt4Z.js.map +1 -0
  69. package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
  70. package/dist/types-520nWrB3.d.ts.map +1 -0
  71. package/dist/{types-Dcv1ZLoW.d.ts → types-BNVqRNli.d.ts} +320 -18
  72. package/dist/types-BNVqRNli.d.ts.map +1 -0
  73. package/package.json +23 -23
  74. package/dist/attachment-service-D3EhiAJ7.d.ts.map +0 -1
  75. package/dist/client-BIHN_UyR.d.ts.map +0 -1
  76. package/dist/client-D66jVnot.js.map +0 -1
  77. package/dist/client-DjK30EQ-.js.map +0 -1
  78. package/dist/document-by-id-B4FIzG1w.js +0 -519
  79. package/dist/document-by-id-B4FIzG1w.js.map +0 -1
  80. package/dist/document-model-modules-bTP87nyr.js +0 -419
  81. package/dist/document-model-modules-bTP87nyr.js.map +0 -1
  82. package/dist/document-operations-WeE6wIDt.js.map +0 -1
  83. package/dist/global-OuINvEGT.d.ts +0 -401
  84. package/dist/global-OuINvEGT.d.ts.map +0 -1
  85. package/dist/index-B33TKEqp.d.ts.map +0 -1
  86. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  87. package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
  88. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  89. package/dist/make-ph-event-functions-DBq3iWYn.js +0 -53
  90. package/dist/make-ph-event-functions-DBq3iWYn.js.map +0 -1
  91. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  92. package/dist/relational-D1RB45sA.js.map +0 -1
  93. package/dist/switchboard-CaXQ4-5Q.js.map +0 -1
  94. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  95. package/dist/types-Dcv1ZLoW.d.ts.map +0 -1
@@ -0,0 +1,1171 @@
1
+ import { c as getPHStore, t as makePHEventFunctions } from "./make-ph-event-functions-B5GU5xcR.js";
2
+ import { use, useCallback, useEffect, useMemo, useReducer, useRef, useSyncExternalStore } from "react";
3
+ import { logger } from "document-model";
4
+ import { operationOutcome } from "@powerhousedao/shared/document-model";
5
+ //#region src/errors.ts
6
+ var UnsupportedDocumentTypeError = class extends Error {
7
+ constructor(documentType) {
8
+ super(`Document type ${documentType} is not supported`);
9
+ this.name = "UnsupportedDocumentTypeError";
10
+ }
11
+ static isError(error) {
12
+ return Error.isError(error) && error.name === "UnsupportedDocumentTypeError";
13
+ }
14
+ };
15
+ var DocumentModelNotFoundError = class extends Error {
16
+ documentType;
17
+ name = "DocumentModelNotFoundError";
18
+ constructor(documentType) {
19
+ super(`Document model module for type ${documentType} not found`);
20
+ this.documentType = documentType;
21
+ }
22
+ static isError(error) {
23
+ return Error.isError(error) && error.name === "DocumentModelNotFoundError";
24
+ }
25
+ };
26
+ var DocumentTypeMismatchError = class extends Error {
27
+ constructor(documentId, expectedType, actualType) {
28
+ super(`Document ${documentId} is not of type ${expectedType}. Actual type: ${actualType}`);
29
+ }
30
+ };
31
+ var NoSelectedDocumentError = class extends Error {
32
+ constructor() {
33
+ super("There is no selected document. Did you mean to call 'useSelectedDocumentSafe' instead?");
34
+ }
35
+ };
36
+ /** A dispatched action the document did not apply: its operation is stored at `index`, state
37
+ * unchanged, because the reducer threw (`reducer-error`) or the write was denied (`denied`). */
38
+ var OperationRejectedError = class OperationRejectedError extends Error {
39
+ documentId;
40
+ scope;
41
+ name = "OperationRejectedError";
42
+ actionId;
43
+ actionType;
44
+ index;
45
+ kind;
46
+ constructor(documentId, scope, operation, outcome) {
47
+ super(outcome.kind === "denied" ? outcome.reason : outcome.message);
48
+ this.documentId = documentId;
49
+ this.scope = scope;
50
+ this.actionId = operation.action.id;
51
+ this.actionType = operation.action.type;
52
+ this.index = operation.index;
53
+ this.kind = outcome.kind;
54
+ }
55
+ /** The rejection `operation` records, or undefined when it applied. */
56
+ static fromOperation(documentId, scope, operation) {
57
+ const outcome = operationOutcome(operation);
58
+ return outcome.kind === "applied" ? void 0 : new OperationRejectedError(documentId, scope, operation, outcome);
59
+ }
60
+ static isError(error) {
61
+ return Error.isError(error) && error.name === "OperationRejectedError";
62
+ }
63
+ };
64
+ //#endregion
65
+ //#region src/actions/queue.ts
66
+ async function queueActions(document, actionOrActions) {
67
+ if (!document) throw new Error("No document provided");
68
+ if (!actionOrActions) throw new Error("No actions provided");
69
+ const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
70
+ if (actions.length === 0) throw new Error("No actions provided");
71
+ const reactorClient = getPHStore()?.reactorClient;
72
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
73
+ return await (await reactorClient.write.execute(document.header.id, "main", actions)).document();
74
+ }
75
+ async function queueOperations(documentId, operationOrOperations) {
76
+ if (!documentId) throw new Error("No documentId provided");
77
+ if (!operationOrOperations) throw new Error("No operations provided");
78
+ const operations = Array.isArray(operationOrOperations) ? operationOrOperations : [operationOrOperations];
79
+ if (operations.length === 0) throw new Error("No operations provided");
80
+ const reactorClient = getPHStore()?.reactorClient;
81
+ if (!reactorClient) throw new Error("ReactorClient not initialized");
82
+ const actions = operations.map((op) => op.action);
83
+ return await (await reactorClient.write.execute(documentId, "main", actions)).document();
84
+ }
85
+ async function uploadOperations(documentId, allOperations, pushOperations, options) {
86
+ const operationsLimit = options?.operationsLimit || 50;
87
+ const onProgress = options?.onProgress;
88
+ logger.verbose(`uploadDocumentOperations(documentId:${documentId}, ops: ${Object.keys(allOperations).join(",")}, limit:${operationsLimit})`);
89
+ const allOperationsArray = Object.values(allOperations).filter((ops) => ops !== void 0);
90
+ const totalOperations = allOperationsArray.reduce((total, operations) => total + operations.length, 0);
91
+ let uploadedOperations = 0;
92
+ for (const operations of allOperationsArray) for (let i = 0; i < operations.length; i += operationsLimit) {
93
+ logger.verbose(`uploadDocumentOperations:for(i:${i}, ops:${operations.length}, limit:${operationsLimit}): START`);
94
+ const chunk = operations.slice(i, i + operationsLimit);
95
+ const operation = chunk.at(-1);
96
+ if (!operation) break;
97
+ const scope = operation.action.scope;
98
+ await pushOperations(documentId, chunk);
99
+ uploadedOperations += chunk.length;
100
+ if (onProgress) onProgress({
101
+ stage: "uploading",
102
+ progress: Math.round(uploadedOperations / totalOperations * 100),
103
+ totalOperations,
104
+ uploadedOperations
105
+ });
106
+ logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}:${scope} rev ${operation.index}): NEXT`);
107
+ }
108
+ logger.verbose(`uploadDocumentOperations:for:waitForUpdate(${documentId}): END`);
109
+ }
110
+ //#endregion
111
+ //#region src/actions/sign.ts
112
+ function addActionContext(action) {
113
+ const renown = getPHStore()?.renown;
114
+ if (!renown?.user) return action;
115
+ return {
116
+ context: { signer: {
117
+ app: {
118
+ name: "Connect",
119
+ key: renown.did
120
+ },
121
+ user: {
122
+ address: renown.user.address,
123
+ networkId: renown.user.networkId,
124
+ chainId: renown.user.chainId
125
+ },
126
+ signatures: []
127
+ } },
128
+ ...action
129
+ };
130
+ }
131
+ function makeSignedActionWithContext(action, document) {
132
+ if (!action) {
133
+ logger.error("No action found");
134
+ return;
135
+ }
136
+ if (!document) {
137
+ logger.error("No document found");
138
+ return;
139
+ }
140
+ return addActionContext(action);
141
+ }
142
+ function makeSignedActionsWithContext(actionOrActions, document) {
143
+ if (!actionOrActions) {
144
+ logger.error("No actions found");
145
+ return;
146
+ }
147
+ return (Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]).map((action) => makeSignedActionWithContext(action, document)).filter((a) => a !== void 0);
148
+ }
149
+ //#endregion
150
+ //#region src/actions/dispatch.ts
151
+ async function getDocument(documentId) {
152
+ try {
153
+ return await getPHStore()?.reactorClient?.get(documentId);
154
+ } catch (error) {
155
+ logger.debug(`Failed to get document with id ${documentId}:`, error);
156
+ return;
157
+ }
158
+ }
159
+ async function getOperationsSince(documentId, scope, sinceRevision) {
160
+ const reactorClient = getPHStore()?.reactorClient;
161
+ if (!reactorClient) return [];
162
+ const operations = [];
163
+ let paging;
164
+ do {
165
+ const page = await reactorClient.getOperations(documentId, {
166
+ branch: "main",
167
+ scopes: [scope]
168
+ }, { sinceRevision }, paging);
169
+ operations.push(...page.results);
170
+ paging = page.nextCursor && page.results.length ? {
171
+ cursor: page.nextCursor,
172
+ limit: page.options.limit
173
+ } : void 0;
174
+ } while (paging);
175
+ return operations;
176
+ }
177
+ /** The operations the dispatch produced in `scope`: a remote client returns them on the
178
+ * document, the local clients do not, so they are read from the revision before it. */
179
+ async function getDispatchedOperations(before, result, scope, actionIds) {
180
+ const returned = result.operations?.[scope];
181
+ if (returned?.some((op) => actionIds.has(op.action.id))) return returned;
182
+ return getOperationsSince(result.header.id, scope, before.header.revision[scope] ?? 0);
183
+ }
184
+ async function getActionErrors(before, result, actions) {
185
+ const actionIds = new Set(actions.map((action) => action.id));
186
+ const errors = [];
187
+ for (const scope of new Set(actions.map((action) => action.scope))) {
188
+ let operations;
189
+ try {
190
+ operations = await getDispatchedOperations(before, result, scope, actionIds);
191
+ } catch (error) {
192
+ logger.warn("Could not read the dispatched operations of @scope: @error", scope, error);
193
+ continue;
194
+ }
195
+ for (const action of actions) {
196
+ if (action.scope !== scope) continue;
197
+ const operation = operations.findLast((op) => op.action.id === action.id);
198
+ const error = operation && OperationRejectedError.fromOperation(result.header.id, scope, operation);
199
+ if (error) errors.push(error);
200
+ }
201
+ }
202
+ return errors;
203
+ }
204
+ async function dispatchActions(actionOrActions, documentOrDocumentId, onErrors, onSuccess) {
205
+ const document = typeof documentOrDocumentId === "string" ? await getDocument(documentOrDocumentId) : documentOrDocumentId;
206
+ if (!document) {
207
+ const message = `Document with id ${JSON.stringify(documentOrDocumentId)} not found`;
208
+ logger.error(message);
209
+ onErrors?.([new Error(message)]);
210
+ return;
211
+ }
212
+ const signedActionsWithContext = makeSignedActionsWithContext(actionOrActions, document);
213
+ if (!signedActionsWithContext) {
214
+ const message = "No signed actions with context found";
215
+ logger.error(message);
216
+ onErrors?.([/* @__PURE__ */ new Error(message)]);
217
+ return;
218
+ }
219
+ const result = await queueActions(document, signedActionsWithContext);
220
+ const rejected = onErrors || onSuccess ? await getActionErrors(document, result, signedActionsWithContext) : [];
221
+ if (onErrors && rejected.length) onErrors(rejected);
222
+ onSuccess?.(result, { rejected });
223
+ return result;
224
+ }
225
+ //#endregion
226
+ //#region src/document-refetcher.ts
227
+ /** The refetch snapshot of a document with nothing in flight and no kept failure. */
228
+ const IDLE_REFETCH_STATE = Object.freeze({
229
+ isRefetching: false,
230
+ error: void 0
231
+ });
232
+ function fulfilledPromise$1(value) {
233
+ const promise = Promise.resolve(value);
234
+ promise.status = "fulfilled";
235
+ promise.value = value;
236
+ return promise;
237
+ }
238
+ function rejectedPromise(reason) {
239
+ const promise = Promise.reject(reason);
240
+ promise.status = "rejected";
241
+ promise.reason = reason;
242
+ promise.catch(() => void 0);
243
+ return promise;
244
+ }
245
+ const MISSING_DOCUMENT_ERRORS = [
246
+ "DocumentNotFoundError",
247
+ "DocumentPurgedError",
248
+ "DocumentDeletedError"
249
+ ];
250
+ function isMissingDocumentError(error) {
251
+ if (!(error instanceof Error)) return false;
252
+ return MISSING_DOCUMENT_ERRORS.includes(error.name) || error.message.startsWith("Document not found");
253
+ }
254
+ const noop = () => void 0;
255
+ /** Background refetch of loaded documents: readers keep the loaded promise until it settles. */
256
+ var DocumentRefetcher = class {
257
+ host;
258
+ refetches = /* @__PURE__ */ new Map();
259
+ states = /* @__PURE__ */ new Map();
260
+ constructor(host) {
261
+ this.host = host;
262
+ }
263
+ getState(id) {
264
+ return this.states.get(id) ?? IDLE_REFETCH_STATE;
265
+ }
266
+ /** Serializes refetches per key: one runs, later requests share one queued run. */
267
+ refetch(id) {
268
+ let entry = this.refetches.get(id);
269
+ if (!entry) {
270
+ entry = {
271
+ running: void 0,
272
+ queued: void 0
273
+ };
274
+ this.refetches.set(id, entry);
275
+ const current = this.host.documents.get(id);
276
+ if (current?.status !== "pending") return this.start(id, entry);
277
+ entry.running = current;
278
+ }
279
+ const inFlight = entry;
280
+ inFlight.queued ??= (inFlight.running ?? Promise.resolve()).then(noop, noop).then(() => this.start(id, inFlight));
281
+ return inFlight.queued;
282
+ }
283
+ /** Stops any refetch of `id` from writing back, e.g. on deletion. */
284
+ forget(id) {
285
+ this.refetches.delete(id);
286
+ this.states.delete(id);
287
+ }
288
+ clear() {
289
+ this.refetches.clear();
290
+ this.states.clear();
291
+ }
292
+ start(id, entry) {
293
+ entry.queued = void 0;
294
+ entry.running = this.run(id, entry);
295
+ return entry.running;
296
+ }
297
+ async run(id, entry) {
298
+ const isCurrent = () => this.refetches.get(id) === entry;
299
+ if (!isCurrent()) return this.host.fetch(id);
300
+ if (this.setState(id, {
301
+ isRefetching: true,
302
+ error: this.getState(id).error
303
+ })) this.host.notify(id);
304
+ try {
305
+ const document = await this.host.fetch(id);
306
+ if (isCurrent()) {
307
+ this.host.onFetched?.(id, document);
308
+ this.host.documents.set(id, fulfilledPromise$1(document));
309
+ this.finish(id, entry, void 0);
310
+ }
311
+ return document;
312
+ } catch (error) {
313
+ if (isCurrent()) {
314
+ if (isMissingDocumentError(error)) {
315
+ this.host.documents.set(id, rejectedPromise(error));
316
+ this.finish(id, entry, void 0);
317
+ } else {
318
+ console.warn("[DocumentCache] Refetch failed; keeping the loaded document:", error);
319
+ this.finish(id, entry, error);
320
+ }
321
+ }
322
+ throw error;
323
+ }
324
+ }
325
+ finish(id, entry, error) {
326
+ if (!entry.queued) this.refetches.delete(id);
327
+ this.setState(id, {
328
+ isRefetching: entry.queued !== void 0,
329
+ error
330
+ });
331
+ this.host.notify(id);
332
+ }
333
+ /** Returns whether the snapshot changed; the caller notifies. */
334
+ setState(id, state) {
335
+ const current = this.getState(id);
336
+ if (current.isRefetching === state.isRefetching && current.error === state.error) return false;
337
+ if (!state.isRefetching && state.error === void 0) this.states.delete(id);
338
+ else this.states.set(id, Object.freeze({ ...state }));
339
+ return true;
340
+ }
341
+ };
342
+ /**
343
+ * The reactor's `DocumentChangeType` members, typed as the enum so they can be
344
+ * assigned to `DocumentChangeEvent.type`. The assertion is unavoidable - a
345
+ * TypeScript string enum is nominal, so no string literal is assignable to it
346
+ * without one - and the two checks above are what make it safe.
347
+ */
348
+ const DOCUMENT_CHANGE_TYPE = {
349
+ Created: "created",
350
+ Deleted: "deleted",
351
+ Updated: "updated",
352
+ ParentAdded: "parent_added",
353
+ ParentRemoved: "parent_removed",
354
+ ChildAdded: "child_added",
355
+ ChildRemoved: "child_removed"
356
+ };
357
+ /**
358
+ * Structural equivalents of the reactor error classes' own static `isError`
359
+ * guards. Those guards match on `error.name` rather than the prototype chain
360
+ * (`packages/reactor/src/registry/errors.ts`), so re-implementing them here is
361
+ * behaviour-preserving and does not need the class at runtime.
362
+ */
363
+ function isDuplicateModuleError(error) {
364
+ return Error.isError(error) && error.name === "DuplicateModuleError";
365
+ }
366
+ function isDuplicateManifestError(error) {
367
+ return Error.isError(error) && error.name === "DuplicateManifestError";
368
+ }
369
+ //#endregion
370
+ //#region src/document-cache.ts
371
+ /** The most ids one `getMany` call is asked for. */
372
+ const GET_MANY_CHUNK_SIZE = 100;
373
+ function addPromiseState(promise) {
374
+ if ("status" in promise) return promise;
375
+ const promiseWithState = promise;
376
+ promiseWithState.status = "pending";
377
+ promiseWithState.then((value) => {
378
+ promiseWithState.status = "fulfilled";
379
+ promiseWithState.value = value;
380
+ }, (reason) => {
381
+ promiseWithState.status = "rejected";
382
+ promiseWithState.reason = reason;
383
+ throw reason;
384
+ });
385
+ return promiseWithState;
386
+ }
387
+ function readPromiseState(promise) {
388
+ return "status" in promise ? promise : { status: "pending" };
389
+ }
390
+ /**
391
+ * Resolves an array of document promises using `Promise.allSettled`,
392
+ * returning only the fulfilled values. A single missing/rejected
393
+ * document does not poison the whole batch. Rejected entries are
394
+ * logged at warn level so developers can see dangling references.
395
+ */
396
+ function fulfilledOnly(promises) {
397
+ return Promise.allSettled(promises).then((results) => {
398
+ const documents = [];
399
+ for (const result of results) if (result.status === "fulfilled") documents.push(result.value);
400
+ else console.warn("[DocumentCache] Skipped unavailable document:", result.reason);
401
+ return documents;
402
+ });
403
+ }
404
+ /** The snapshot every uncached document scope reads as. One frozen object, so `useSyncExternalStore` sees a stable value. */
405
+ const IDLE_OPERATIONS_ENTRY = Object.freeze({
406
+ status: "idle",
407
+ operations: Object.freeze([]),
408
+ error: void 0,
409
+ hasNextPage: false
410
+ });
411
+ /** Whether a document cache also serves operation history. `GraphQLClientDocumentCache` does not. */
412
+ function isOperationCache(cache) {
413
+ if (typeof cache !== "object" || cache === null) return false;
414
+ const candidate = cache;
415
+ return typeof candidate.getOperationsState === "function" && typeof candidate.loadOperations === "function" && typeof candidate.loadMoreOperations === "function" && typeof candidate.invalidateOperations === "function" && typeof candidate.subscribeOperations === "function";
416
+ }
417
+ /** The snapshot every unloaded type reads as, frozen so `useSyncExternalStore` sees one value. */
418
+ const IDLE_DOCUMENTS_OF_TYPE_ENTRY = Object.freeze({
419
+ status: "idle",
420
+ ids: Object.freeze([]),
421
+ error: void 0,
422
+ hasNextPage: false
423
+ });
424
+ /** Whether a document cache also lists documents by type. */
425
+ function isDocumentTypeCache(cache) {
426
+ if (typeof cache !== "object" || cache === null) return false;
427
+ const candidate = cache;
428
+ return typeof candidate.getDocumentsOfTypeState === "function" && typeof candidate.loadDocumentsOfType === "function" && typeof candidate.loadMoreDocumentsOfType === "function" && typeof candidate.subscribeDocumentsOfType === "function";
429
+ }
430
+ function createDeferred() {
431
+ let resolve;
432
+ let reject;
433
+ return {
434
+ promise: new Promise((res, rej) => {
435
+ resolve = res;
436
+ reject = rej;
437
+ }),
438
+ resolve,
439
+ reject
440
+ };
441
+ }
442
+ /** A promise already settled with `value`, readable without awaiting. */
443
+ function fulfilledPromise(value) {
444
+ const promise = Promise.resolve(value);
445
+ promise.status = "fulfilled";
446
+ promise.value = value;
447
+ return promise;
448
+ }
449
+ const typeKey = (type, limit) => `${limit}:${type}`;
450
+ /**
451
+ * Page size used to refresh a scope whose request record has gone missing.
452
+ * A loaded scope always has one, so this is a floor rather than a default.
453
+ */
454
+ const FALLBACK_REFRESH_LIMIT = 100;
455
+ /**
456
+ * The highest revision among the operations loaded so far, or -1 for none.
457
+ * Pages arrive oldest first, so this is normally the last entry; it is
458
+ * computed rather than assumed because nothing in the cache enforces that.
459
+ */
460
+ function highestOperationIndex(operations) {
461
+ let highest = -1;
462
+ for (const operation of operations) if (operation.index > highest) highest = operation.index;
463
+ return highest;
464
+ }
465
+ /**
466
+ * Document cache implementation that uses the new ReactorClient API.
467
+ *
468
+ * This cache subscribes to document change events through the client's read half
469
+ * and automatically updates the cache when documents are created, updated, or deleted.
470
+ * It is built over a browser client, whose `read` half it uses, or over a read
471
+ * half directly.
472
+ * It also holds paginated operation history per document scope (see `IOperationCache`),
473
+ * which is dropped for a document whenever a change event for it arrives.
474
+ */
475
+ var DocumentCache = class {
476
+ documents = /* @__PURE__ */ new Map();
477
+ batchPromises = /* @__PURE__ */ new Map();
478
+ listeners = /* @__PURE__ */ new Map();
479
+ refetcher = new DocumentRefetcher({
480
+ documents: this.documents,
481
+ fetch: (id) => this.client.get(id),
482
+ notify: (id) => this.notifyListeners(id),
483
+ onFetched: (id, document) => {
484
+ if (document.header.id !== id) this.recordAlias(document.header.id, id);
485
+ }
486
+ });
487
+ /**
488
+ * Cache keys that fetched a document under a name other than its id --
489
+ * slugs, which `client.get` resolves. Change events dispatch by `header.id`,
490
+ * so without this mapping a slug-keyed entry (and its listeners) would never
491
+ * see an update: keyed by the id the events carry, valued by the other keys
492
+ * the same document is cached under.
493
+ */
494
+ aliasKeys = /* @__PURE__ */ new Map();
495
+ /** Operations by document id, then scope. Entries are replaced, never mutated. */
496
+ operationEntries = /* @__PURE__ */ new Map();
497
+ /** In-flight controllers and the next page's cursor/limit, by document id then scope. */
498
+ operationRequests = /* @__PURE__ */ new Map();
499
+ operationListeners = /* @__PURE__ */ new Map();
500
+ /** Documents by type and page size, keyed by typeKey. */
501
+ typeEntries = /* @__PURE__ */ new Map();
502
+ typeRequests = /* @__PURE__ */ new Map();
503
+ typeListeners = /* @__PURE__ */ new Map();
504
+ unsubscribe = null;
505
+ client;
506
+ constructor(client) {
507
+ this.client = readerOf(client);
508
+ this.unsubscribe = this.client.subscribe({}, (event) => {
509
+ this.handleDocumentChange(event);
510
+ });
511
+ }
512
+ handleDocumentChange(event) {
513
+ this.reloadTypesChangedBy(event);
514
+ if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {
515
+ const documentId = event.context?.childId;
516
+ if (documentId) {
517
+ const keys = this.cacheKeysFor(documentId);
518
+ this.handleDocumentDeleted(documentId);
519
+ for (const key of keys) this.invalidateOperations(key);
520
+ }
521
+ } else if (event.type === DOCUMENT_CHANGE_TYPE.Updated) for (const doc of event.documents) {
522
+ const keys = this.cacheKeysFor(doc.header.id);
523
+ this.handleDocumentUpdated(doc.header.id).catch(console.warn);
524
+ for (const key of keys) this.refreshOperations(key);
525
+ }
526
+ }
527
+ handleDocumentDeleted(documentId) {
528
+ for (const key of this.cacheKeysFor(documentId)) {
529
+ const listeners = this.listeners.get(key);
530
+ this.documents.delete(key);
531
+ this.refetcher.forget(key);
532
+ this.invalidateBatchesContaining(key);
533
+ if (listeners) listeners.forEach((listener) => listener());
534
+ this.listeners.delete(key);
535
+ }
536
+ this.aliasKeys.delete(documentId);
537
+ }
538
+ async handleDocumentUpdated(documentId) {
539
+ const refetches = this.cacheKeysFor(documentId).filter((key) => this.documents.has(key)).map((key) => this.get(key, true));
540
+ await Promise.all(refetches);
541
+ }
542
+ notifyListeners(key) {
543
+ for (const listener of this.listeners.get(key) ?? []) listener();
544
+ }
545
+ /** The id an event dispatches by, plus every alias the document is cached under. */
546
+ cacheKeysFor(documentId) {
547
+ return [documentId, ...this.aliasKeys.get(documentId) ?? []];
548
+ }
549
+ /** Records that `key` cached the document change events know as `header.id`. */
550
+ recordAlias(documentId, key) {
551
+ const keys = this.aliasKeys.get(documentId) ?? /* @__PURE__ */ new Set();
552
+ keys.add(key);
553
+ this.aliasKeys.set(documentId, keys);
554
+ }
555
+ invalidateBatchesContaining(documentId) {
556
+ for (const key of this.batchPromises.keys()) if (key.split(",").includes(documentId)) this.batchPromises.delete(key);
557
+ }
558
+ get(id, refetch) {
559
+ const currentData = this.documents.get(id);
560
+ if (currentData && !refetch) return currentData;
561
+ if (currentData && currentData.status !== "rejected") return this.refetcher.refetch(id);
562
+ this.refetcher.forget(id);
563
+ const documentPromise = this.client.get(id);
564
+ documentPromise.then((doc) => {
565
+ if (doc.header.id !== id) this.recordAlias(doc.header.id, id);
566
+ }, () => void 0);
567
+ this.documents.set(id, addPromiseState(documentPromise));
568
+ return documentPromise;
569
+ }
570
+ getRefetchState(id) {
571
+ return this.refetcher.getState(id);
572
+ }
573
+ getBatch(ids) {
574
+ const key = ids.join(",");
575
+ const cached = this.batchPromises.get(key);
576
+ const hasDeletedDocuments = ids.some((id) => !this.documents.has(id));
577
+ if (hasDeletedDocuments) this.loadMany(ids);
578
+ const currentPromises = ids.map((id) => this.get(id));
579
+ if (hasDeletedDocuments) {
580
+ const batchPromise = fulfilledOnly(currentPromises);
581
+ this.batchPromises.set(key, {
582
+ promises: currentPromises,
583
+ promise: batchPromise
584
+ });
585
+ return batchPromise;
586
+ }
587
+ if (cached) {
588
+ if (currentPromises.every((p, i) => p === cached.promises[i])) return cached.promise;
589
+ }
590
+ const states = currentPromises.map((p) => readPromiseState(p));
591
+ if (states.every((s) => s.status !== "pending")) {
592
+ const values = states.filter((s) => s.status === "fulfilled").map((s) => s.value);
593
+ const batchPromise = Promise.resolve(values);
594
+ batchPromise.status = "fulfilled";
595
+ batchPromise.value = values;
596
+ this.batchPromises.set(key, {
597
+ promises: currentPromises,
598
+ promise: batchPromise
599
+ });
600
+ return batchPromise;
601
+ }
602
+ if (cached) return cached.promise;
603
+ const batchPromise = fulfilledOnly(currentPromises);
604
+ this.batchPromises.set(key, {
605
+ promises: currentPromises,
606
+ promise: batchPromise
607
+ });
608
+ return batchPromise;
609
+ }
610
+ /**
611
+ * Reserves an entry for every id not yet cached and fills them from
612
+ * `getMany`, in chunks of {@link GET_MANY_CHUNK_SIZE}. Each id keeps its own
613
+ * entry, settled as `get` would settle it.
614
+ */
615
+ loadMany(ids) {
616
+ const getMany = this.client.getMany?.bind(this.client);
617
+ const missing = [...new Set(ids)].filter((id) => !this.documents.has(id));
618
+ if (!getMany || missing.length < 2) return;
619
+ const pending = /* @__PURE__ */ new Map();
620
+ for (const id of missing) {
621
+ const deferred = createDeferred();
622
+ pending.set(id, deferred);
623
+ this.refetcher.forget(id);
624
+ this.documents.set(id, addPromiseState(deferred.promise));
625
+ }
626
+ for (let i = 0; i < missing.length; i += 100) this.settleMany(missing.slice(i, i + 100), pending, getMany);
627
+ }
628
+ /**
629
+ * `getMany` rejects when any id is unavailable, so a failed chunk is split
630
+ * in half and retried; a single id is read with `get`, so it settles exactly
631
+ * as a single read would.
632
+ */
633
+ async settleMany(ids, pending, getMany) {
634
+ if (ids.length === 1) {
635
+ const id = ids[0];
636
+ try {
637
+ this.settleFetched(id, await this.client.get(id), pending);
638
+ } catch (error) {
639
+ pending.get(id)?.reject(error);
640
+ }
641
+ return;
642
+ }
643
+ let documents;
644
+ try {
645
+ documents = await getMany(ids);
646
+ } catch {
647
+ const half = Math.ceil(ids.length / 2);
648
+ await Promise.all([this.settleMany(ids.slice(0, half), pending, getMany), this.settleMany(ids.slice(half), pending, getMany)]);
649
+ return;
650
+ }
651
+ if (documents.length !== ids.length) {
652
+ await Promise.all(ids.map((id) => this.settleMany([id], pending, getMany)));
653
+ return;
654
+ }
655
+ ids.forEach((id, i) => this.settleFetched(id, documents[i], pending));
656
+ }
657
+ settleFetched(id, document, pending) {
658
+ if (document.header.id !== id) this.recordAlias(document.header.id, id);
659
+ pending.get(id)?.resolve(document);
660
+ }
661
+ subscribe(id, callback) {
662
+ const ids = Array.isArray(id) ? id : [id];
663
+ for (const docId of ids) {
664
+ const listeners = this.listeners.get(docId) ?? [];
665
+ this.listeners.set(docId, [...listeners, callback]);
666
+ }
667
+ return () => {
668
+ for (const docId of ids) {
669
+ const listeners = this.listeners.get(docId) ?? [];
670
+ this.listeners.set(docId, listeners.filter((listener) => listener !== callback));
671
+ }
672
+ };
673
+ }
674
+ getOperationsState(documentId, scope) {
675
+ return this.operationEntries.get(documentId)?.get(scope) ?? IDLE_OPERATIONS_ENTRY;
676
+ }
677
+ loadOperations(documentId, scope, limit) {
678
+ const current = this.getOperationsState(documentId, scope);
679
+ if (current.status !== "idle") return;
680
+ const controller = new AbortController();
681
+ this.setOperationsRequest(documentId, scope, {
682
+ controller,
683
+ nextCursor: void 0,
684
+ limit
685
+ });
686
+ this.setOperationsEntry(documentId, scope, {
687
+ ...current,
688
+ status: "pending"
689
+ });
690
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, void 0, {
691
+ cursor: "",
692
+ limit
693
+ }, controller.signal), controller, limit);
694
+ }
695
+ loadMoreOperations(documentId, scope) {
696
+ const current = this.getOperationsState(documentId, scope);
697
+ const request = this.operationRequests.get(documentId)?.get(scope);
698
+ if (current.status !== "success" || !current.hasNextPage || !request?.nextCursor) return;
699
+ const controller = new AbortController();
700
+ const { nextCursor, limit } = request;
701
+ this.setOperationsRequest(documentId, scope, {
702
+ controller,
703
+ nextCursor,
704
+ limit
705
+ });
706
+ this.setOperationsEntry(documentId, scope, {
707
+ ...current,
708
+ status: "pending"
709
+ });
710
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, void 0, {
711
+ cursor: nextCursor,
712
+ limit
713
+ }, controller.signal), controller, limit);
714
+ }
715
+ /**
716
+ * Bring a document's cached scopes up to date after it changed, without
717
+ * throwing away what is already loaded.
718
+ *
719
+ * The operation stream is append-only: an update adds operations at higher
720
+ * revisions and never rewrites the ones below, so history already paged in
721
+ * is still correct. Dropping it meant a panel showing a fully loaded
722
+ * document re-walked every page on each edit -- the cost of which grows
723
+ * with the document, exactly where it hurts most. Each scope instead asks
724
+ * only for what comes after the newest revision it holds, using the
725
+ * `sinceRevision` filter, and appends the answer.
726
+ *
727
+ * A scope that has not finished paging is dropped as before: it has no
728
+ * meaningful "newest revision" to resume from, since asking for everything
729
+ * past the newest row it happens to hold would skip the pages between that
730
+ * row and the end of the stream.
731
+ */
732
+ refreshOperations(documentId) {
733
+ const scopes = this.operationEntries.get(documentId);
734
+ if (!scopes) return;
735
+ for (const [scope, entry] of [...scopes.entries()]) {
736
+ if (entry.status !== "success" || entry.hasNextPage) {
737
+ this.invalidateOperationsScope(documentId, scope);
738
+ continue;
739
+ }
740
+ const previous = this.operationRequests.get(documentId)?.get(scope);
741
+ const limit = previous?.limit ?? FALLBACK_REFRESH_LIMIT;
742
+ previous?.controller.abort();
743
+ const controller = new AbortController();
744
+ this.setOperationsRequest(documentId, scope, {
745
+ controller,
746
+ nextCursor: void 0,
747
+ limit
748
+ });
749
+ this.setOperationsEntry(documentId, scope, {
750
+ ...entry,
751
+ status: "pending"
752
+ });
753
+ this.settleOperationsPage(documentId, scope, this.client.getOperations(documentId, { scopes: [scope] }, { sinceRevision: highestOperationIndex(entry.operations) + 1 }, {
754
+ cursor: "",
755
+ limit
756
+ }, controller.signal), controller, limit);
757
+ }
758
+ }
759
+ /** Drops one scope of a document, aborting its request if one is in flight. */
760
+ invalidateOperationsScope(documentId, scope) {
761
+ const requests = this.operationRequests.get(documentId);
762
+ const request = requests?.get(scope);
763
+ if (request && requests) {
764
+ request.controller.abort();
765
+ requests.delete(scope);
766
+ if (requests.size === 0) this.operationRequests.delete(documentId);
767
+ }
768
+ const scopes = this.operationEntries.get(documentId);
769
+ if (scopes?.delete(scope)) {
770
+ if (scopes.size === 0) this.operationEntries.delete(documentId);
771
+ this.notifyOperationListeners(documentId);
772
+ }
773
+ }
774
+ invalidateOperations(documentId) {
775
+ const requests = this.operationRequests.get(documentId);
776
+ if (requests) {
777
+ for (const request of requests.values()) request.controller.abort();
778
+ this.operationRequests.delete(documentId);
779
+ }
780
+ if (this.operationEntries.delete(documentId)) this.notifyOperationListeners(documentId);
781
+ }
782
+ subscribeOperations(documentId, callback) {
783
+ const listeners = this.operationListeners.get(documentId) ?? [];
784
+ this.operationListeners.set(documentId, [...listeners, callback]);
785
+ return () => {
786
+ const current = this.operationListeners.get(documentId) ?? [];
787
+ this.operationListeners.set(documentId, current.filter((listener) => listener !== callback));
788
+ };
789
+ }
790
+ settleOperationsPage(documentId, scope, page, controller, limit) {
791
+ page.then((result) => {
792
+ if (controller.signal.aborted) return;
793
+ const current = this.getOperationsState(documentId, scope);
794
+ this.setOperationsRequest(documentId, scope, {
795
+ controller,
796
+ nextCursor: result.nextCursor,
797
+ limit
798
+ });
799
+ this.setOperationsEntry(documentId, scope, {
800
+ status: "success",
801
+ operations: [...current.operations, ...result.results],
802
+ error: void 0,
803
+ hasNextPage: !!result.nextCursor
804
+ });
805
+ }, (reason) => {
806
+ if (controller.signal.aborted) return;
807
+ const current = this.getOperationsState(documentId, scope);
808
+ this.setOperationsEntry(documentId, scope, {
809
+ ...current,
810
+ status: "error",
811
+ error: reason
812
+ });
813
+ });
814
+ }
815
+ setOperationsEntry(documentId, scope, entry) {
816
+ const scopes = this.operationEntries.get(documentId) ?? /* @__PURE__ */ new Map();
817
+ scopes.set(scope, entry);
818
+ this.operationEntries.set(documentId, scopes);
819
+ this.notifyOperationListeners(documentId);
820
+ }
821
+ setOperationsRequest(documentId, scope, request) {
822
+ const scopes = this.operationRequests.get(documentId) ?? /* @__PURE__ */ new Map();
823
+ scopes.set(scope, request);
824
+ this.operationRequests.set(documentId, scopes);
825
+ }
826
+ notifyOperationListeners(documentId) {
827
+ for (const listener of this.operationListeners.get(documentId) ?? []) listener();
828
+ }
829
+ getDocumentsOfTypeState(type, limit) {
830
+ return this.typeEntries.get(typeKey(type, limit)) ?? IDLE_DOCUMENTS_OF_TYPE_ENTRY;
831
+ }
832
+ loadDocumentsOfType(type, limit) {
833
+ const key = typeKey(type, limit);
834
+ const request = this.typeRequests.get(key);
835
+ if (request) return request.firstPage;
836
+ const controller = new AbortController();
837
+ const created = {
838
+ type,
839
+ limit,
840
+ firstPage: fulfilledPromise(void 0),
841
+ controller,
842
+ nextCursor: void 0
843
+ };
844
+ this.typeRequests.set(key, created);
845
+ created.firstPage = addPromiseState(this.loadTypePage(key, "", limit, controller, []));
846
+ return created.firstPage;
847
+ }
848
+ loadMoreDocumentsOfType(type, limit) {
849
+ const key = typeKey(type, limit);
850
+ const entry = this.getDocumentsOfTypeState(type, limit);
851
+ const request = this.typeRequests.get(key);
852
+ if (entry.status !== "success" || !request?.nextCursor) return;
853
+ this.loadTypePage(key, request.nextCursor, limit, request.controller, entry.ids);
854
+ }
855
+ subscribeDocumentsOfType(type, limit, callback) {
856
+ const key = typeKey(type, limit);
857
+ this.typeListeners.set(key, [...this.typeListeners.get(key) ?? [], callback]);
858
+ return () => {
859
+ const current = this.typeListeners.get(key) ?? [];
860
+ this.typeListeners.set(key, current.filter((listener) => listener !== callback));
861
+ };
862
+ }
863
+ /** Loads one page after `before` and appends it; never rejects, the entry holds the error. */
864
+ async loadTypePage(key, cursor, limit, controller, before) {
865
+ const type = this.typeRequests.get(key)?.type ?? "";
866
+ this.setTypeEntry(key, {
867
+ ...this.getTypeEntry(key),
868
+ status: "pending"
869
+ });
870
+ try {
871
+ const page = await this.client.find({ type }, void 0, {
872
+ cursor,
873
+ limit
874
+ }, controller.signal);
875
+ if (controller.signal.aborted) return;
876
+ for (const document of page.results) this.primeDocument(document);
877
+ const request = this.typeRequests.get(key);
878
+ if (request) request.nextCursor = page.nextCursor;
879
+ this.setTypeEntry(key, {
880
+ status: "success",
881
+ ids: [...before, ...page.results.map((d) => d.header.id)],
882
+ error: void 0,
883
+ hasNextPage: !!page.nextCursor
884
+ });
885
+ } catch (error) {
886
+ if (controller.signal.aborted) return;
887
+ this.setTypeEntry(key, {
888
+ ...this.getTypeEntry(key),
889
+ status: "error",
890
+ error
891
+ });
892
+ }
893
+ }
894
+ /** Reloads every loaded page of a type a created or deleted document belongs to. */
895
+ reloadTypesChangedBy(event) {
896
+ if (this.typeRequests.size === 0) return;
897
+ let changed;
898
+ if (event.type === DOCUMENT_CHANGE_TYPE.Created) {
899
+ const types = new Set(event.documents.map((d) => d.header.documentType));
900
+ changed = (_key, type) => types.has(type);
901
+ } else if (event.type === DOCUMENT_CHANGE_TYPE.Deleted) {
902
+ const id = event.context?.childId;
903
+ if (!id) return;
904
+ changed = (key) => this.getTypeEntry(key).ids.includes(id);
905
+ } else return;
906
+ for (const [key, request] of this.typeRequests) {
907
+ if (!changed(key, request.type)) continue;
908
+ request.controller.abort();
909
+ const controller = new AbortController();
910
+ const created = event.type === DOCUMENT_CHANGE_TYPE.Created ? event.documents.filter((d) => d.header.documentType === request.type).length : 0;
911
+ const loaded = this.getTypeEntry(key).ids.length;
912
+ const limit = Math.max(request.limit, loaded + created);
913
+ request.controller = controller;
914
+ this.loadTypePage(key, "", limit, controller, []);
915
+ }
916
+ }
917
+ primeDocument(document) {
918
+ const current = this.documents.get(document.header.id);
919
+ if (current && current.status !== "rejected") return;
920
+ this.documents.set(document.header.id, fulfilledPromise(document));
921
+ }
922
+ getTypeEntry(key) {
923
+ return this.typeEntries.get(key) ?? IDLE_DOCUMENTS_OF_TYPE_ENTRY;
924
+ }
925
+ setTypeEntry(key, entry) {
926
+ this.typeEntries.set(key, entry);
927
+ for (const listener of this.typeListeners.get(key) ?? []) listener();
928
+ }
929
+ /**
930
+ * Disposes of the cache and unsubscribes from document change events.
931
+ */
932
+ dispose() {
933
+ if (this.unsubscribe) {
934
+ this.unsubscribe();
935
+ this.unsubscribe = null;
936
+ }
937
+ for (const requests of this.operationRequests.values()) for (const request of requests.values()) request.controller.abort();
938
+ this.operationRequests.clear();
939
+ this.operationEntries.clear();
940
+ for (const request of this.typeRequests.values()) request.controller.abort();
941
+ this.typeRequests.clear();
942
+ this.typeEntries.clear();
943
+ this.typeListeners.clear();
944
+ this.refetcher.clear();
945
+ this.operationListeners.clear();
946
+ }
947
+ };
948
+ /** The read half of a browser client, or the reader itself. */
949
+ function readerOf(client) {
950
+ return client.read ?? client;
951
+ }
952
+ //#endregion
953
+ //#region src/hooks/document-cache.ts
954
+ const documentEventFunctions = makePHEventFunctions("documentCache");
955
+ /** Returns all documents in the reactor. */
956
+ const useDocumentCache = documentEventFunctions.useValue;
957
+ /** Sets all of the documents in the reactor. */
958
+ const setDocumentCache = documentEventFunctions.setValue;
959
+ /** Adds an event handler for all of the documents in the reactor. */
960
+ const addDocumentCacheEventHandler = documentEventFunctions.addEventHandler;
961
+ /**
962
+ * Reads the state of a document promise and converts it to a query state object.
963
+ * @param promise - The document promise to read
964
+ * @returns An object containing the status, data, error, and isPending flag
965
+ */
966
+ function getDocumentQueryState(promise) {
967
+ const state = readPromiseState(promise);
968
+ switch (state.status) {
969
+ case "pending": return {
970
+ status: "pending",
971
+ isPending: true,
972
+ error: void 0,
973
+ data: void 0
974
+ };
975
+ case "fulfilled": return {
976
+ status: "success",
977
+ isPending: false,
978
+ error: void 0,
979
+ data: state.value
980
+ };
981
+ case "rejected": return {
982
+ status: "error",
983
+ isPending: false,
984
+ error: state.reason,
985
+ data: void 0
986
+ };
987
+ }
988
+ }
989
+ /**
990
+ * Retrieves a document from the reactor and subscribes to changes using React Suspense.
991
+ * This hook will suspend rendering while the document is loading.
992
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
993
+ * @returns The document if found, or undefined if id is null/undefined
994
+ */
995
+ function useDocument(id) {
996
+ const documentCache = useDocumentCache();
997
+ const getDocument = () => id ? documentCache?.get(id) : void 0;
998
+ const document = useSyncExternalStore((cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {}, getDocument, getDocument);
999
+ return document ? use(document) : void 0;
1000
+ }
1001
+ /**
1002
+ * Retrieves a document from the reactor and subscribes to changes without
1003
+ * suspending or throwing. Use this when the ID might be stale (e.g., a
1004
+ * previously selected node that has since been deleted) and the consumer
1005
+ * wants to render a placeholder instead of crashing.
1006
+ *
1007
+ * Unlike {@link useGetDocumentAsync}, this hook subscribes to cache
1008
+ * updates, so the returned state stays in sync with reactor changes.
1009
+ *
1010
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
1011
+ * @returns An object containing:
1012
+ * - status: "initial" | "pending" | "success" | "error"
1013
+ * - data: The document if successfully loaded
1014
+ * - isPending: Whether the document is currently loading
1015
+ * - error: Any error that occurred during loading (e.g., document not found)
1016
+ * - reload: Function to force a refetch, or undefined when no id is supplied
1017
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
1018
+ * - refetchError: The last refetch failure that kept the loaded document
1019
+ */
1020
+ function useDocumentSafe(id) {
1021
+ const documentCache = useDocumentCache();
1022
+ const subscribe = (cb) => id && documentCache ? documentCache.subscribe(id, cb) : () => {};
1023
+ const getPromise = () => id ? documentCache?.get(id) : void 0;
1024
+ const getRefetch = () => readRefetchState(documentCache, id);
1025
+ const promise = useSyncExternalStore(subscribe, getPromise, getPromise);
1026
+ const refetch = useSyncExternalStore(subscribe, getRefetch, getRefetch);
1027
+ const [, bumpOnSettle] = useReducer((count) => count + 1, 0);
1028
+ const pendingPromise = promise && readPromiseState(promise).status === "pending" ? promise : null;
1029
+ useEffect(() => {
1030
+ if (!pendingPromise) return;
1031
+ let active = true;
1032
+ const settled = () => {
1033
+ if (active) bumpOnSettle();
1034
+ };
1035
+ pendingPromise.then(settled, settled);
1036
+ return () => {
1037
+ active = false;
1038
+ };
1039
+ }, [pendingPromise]);
1040
+ if (!promise || !documentCache || !id) return {
1041
+ status: "initial",
1042
+ isPending: false,
1043
+ error: void 0,
1044
+ data: void 0,
1045
+ reload: void 0,
1046
+ isRefetching: false,
1047
+ refetchError: void 0
1048
+ };
1049
+ return {
1050
+ ...getDocumentQueryState(promise),
1051
+ reload: () => documentCache.get(id, true),
1052
+ isRefetching: refetch.isRefetching,
1053
+ refetchError: refetch.error
1054
+ };
1055
+ }
1056
+ function readRefetchState(documentCache, id) {
1057
+ return id && documentCache?.getRefetchState?.(id) || IDLE_REFETCH_STATE;
1058
+ }
1059
+ /**
1060
+ * Retrieves multiple documents from the reactor using React Suspense.
1061
+ * This hook will suspend rendering while any of the documents are loading.
1062
+ *
1063
+ * Uses getBatch from the document cache which handles promise caching internally,
1064
+ * ensuring stable references for useSyncExternalStore.
1065
+ *
1066
+ * @param ids - Array of document IDs to retrieve, or null/undefined to skip retrieval
1067
+ * @returns An array of documents if found, or empty array if ids is null/undefined
1068
+ */
1069
+ function useDocuments(ids) {
1070
+ const documentCache = useDocumentCache();
1071
+ const getBatch = () => ids?.length && documentCache ? documentCache.getBatch(ids) : void 0;
1072
+ const documents = useSyncExternalStore((cb) => ids?.length && documentCache ? documentCache.subscribe(ids, cb) : () => {}, getBatch, getBatch);
1073
+ return documents ? use(documents) : [];
1074
+ }
1075
+ /**
1076
+ * Returns a function to retrieve a document from the cache.
1077
+ * The returned function fetches and returns a document by ID.
1078
+ * @returns A function that takes a document ID and returns a Promise of the document
1079
+ */
1080
+ function useGetDocument() {
1081
+ const documentCache = useDocumentCache();
1082
+ return useCallback((id) => {
1083
+ if (!documentCache) return Promise.reject(/* @__PURE__ */ new Error("Document cache not initialized"));
1084
+ return documentCache.get(id);
1085
+ }, [documentCache]);
1086
+ }
1087
+ /**
1088
+ * Returns a function to retrieve multiple documents from the cache.
1089
+ * The returned function fetches and returns documents by their IDs.
1090
+ * @returns A function that takes an array of document IDs and returns a Promise of the documents
1091
+ */
1092
+ function useGetDocuments() {
1093
+ const documentCache = useDocumentCache();
1094
+ return useCallback((ids) => {
1095
+ if (!documentCache) return Promise.reject(/* @__PURE__ */ new Error("Document cache not initialized"));
1096
+ return documentCache.getBatch(ids);
1097
+ }, [documentCache]);
1098
+ }
1099
+ /**
1100
+ * Retrieves a document from the reactor without suspending rendering.
1101
+ * Returns the current state of the document loading operation.
1102
+ * @param id - The document ID to retrieve, or null/undefined to skip retrieval
1103
+ * @returns An object containing:
1104
+ * - status: "initial" | "pending" | "success" | "error"
1105
+ * - data: The document if successfully loaded
1106
+ * - isPending: Boolean indicating if the document is currently loading
1107
+ * - error: Any error that occurred during loading
1108
+ * - reload: Function to force reload the document from cache
1109
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
1110
+ * - refetchError: The last refetch failure that kept the loaded document
1111
+ */
1112
+ function useGetDocumentAsync(id) {
1113
+ const documentCache = useDocumentCache();
1114
+ if (!id || !documentCache) return {
1115
+ status: "initial",
1116
+ data: void 0,
1117
+ isPending: false,
1118
+ error: void 0,
1119
+ reload: void 0,
1120
+ isRefetching: false,
1121
+ refetchError: void 0
1122
+ };
1123
+ const state = getDocumentQueryState(documentCache.get(id));
1124
+ const refetch = readRefetchState(documentCache, id);
1125
+ return {
1126
+ ...state,
1127
+ reload: () => documentCache.get(id, true),
1128
+ isRefetching: refetch.isRefetching,
1129
+ refetchError: refetch.error
1130
+ };
1131
+ }
1132
+ //#endregion
1133
+ //#region src/hooks/dispatch.ts
1134
+ /** A dispatch to the document `getDocument` returns when it runs. */
1135
+ function createDispatch(getDocument) {
1136
+ /**
1137
+ * Dispatches actions to the document.
1138
+ * @param actionOrActions - The action or actions to dispatch.
1139
+ * @param onErrors - Callback invoked with an `OperationRejectedError` for each action the
1140
+ * document did not apply, or with the failure when the dispatch itself did not complete.
1141
+ * Runs before `onSuccess`.
1142
+ * @param onSuccess - Callback invoked with the document once the write lands, after
1143
+ * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.
1144
+ */
1145
+ return function dispatch(actionOrActions, onErrors, onSuccess) {
1146
+ let answered = false;
1147
+ const reportErrors = onErrors && ((errors) => {
1148
+ answered = true;
1149
+ onErrors(errors);
1150
+ });
1151
+ const reportSuccess = onSuccess && ((result, outcome) => {
1152
+ answered = true;
1153
+ onSuccess(result, outcome);
1154
+ });
1155
+ dispatchActions(actionOrActions, getDocument(), reportErrors, reportSuccess).catch((error) => {
1156
+ logger.error("Failed to dispatch actions: @error", error);
1157
+ if (!answered) onErrors?.([error instanceof Error ? error : new Error(String(error))]);
1158
+ });
1159
+ };
1160
+ }
1161
+ /** Returns the document and a dispatch to it; see `DispatchFn` for the callbacks' order. */
1162
+ function useDispatch(document) {
1163
+ const latest = useRef(document);
1164
+ latest.current = document;
1165
+ const id = document?.header.id;
1166
+ return [document, useMemo(() => createDispatch(() => latest.current), [id])];
1167
+ }
1168
+ //#endregion
1169
+ export { DocumentTypeMismatchError as A, DocumentRefetcher as C, queueOperations as D, queueActions as E, OperationRejectedError as M, UnsupportedDocumentTypeError as N, uploadOperations as O, isDuplicateModuleError as S, dispatchActions as T, isDocumentTypeCache as _, useDocument as a, DOCUMENT_CHANGE_TYPE as b, useDocuments as c, useGetDocuments as d, DocumentCache as f, addPromiseState as g, IDLE_OPERATIONS_ENTRY as h, setDocumentCache as i, NoSelectedDocumentError as j, DocumentModelNotFoundError as k, useGetDocument as l, IDLE_DOCUMENTS_OF_TYPE_ENTRY as m, useDispatch as n, useDocumentCache as o, GET_MANY_CHUNK_SIZE as p, addDocumentCacheEventHandler as r, useDocumentSafe as s, createDispatch as t, useGetDocumentAsync as u, isOperationCache as v, IDLE_REFETCH_STATE as w, isDuplicateManifestError as x, readPromiseState as y };
1170
+
1171
+ //# sourceMappingURL=dispatch-C8J9jQ-o.js.map