@get-bb/plugin-sdk 0.6.60 → 0.6.68
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundled-types/bb-plugin-sdk-app.d.ts +477 -169
- package/bundled-types/bb-plugin-sdk-host.d.ts +196 -214
- package/bundled-types/bb-plugin-sdk-internal-composer-handle.d.ts +60 -35
- package/bundled-types/bb-plugin-sdk-internal-host-policy.d.ts +17 -7
- package/bundled-types/bb-plugin-sdk-internal-plugin-app-collector.d.ts +5 -11
- package/bundled-types/bb-plugin-sdk-internal-rpc-query-host.d.ts +192 -0
- package/bundled-types/bb-plugin-sdk-internal-rpc-tags.d.ts +23 -0
- package/bundled-types/bb-plugin-sdk-testing-app.d.ts +8 -2
- package/bundled-types/bb-plugin-sdk-testing.d.ts +29 -5
- package/bundled-types/bb-plugin-sdk.d.ts +622 -195
- package/dist/app.js +98 -0
- package/dist/host.js +12 -0
- package/dist/index.js +81 -0
- package/dist/internal/composer-handle.js +13 -14
- package/dist/internal/host-policy.js +33 -1
- package/dist/internal/plugin-app-collector.js +104 -85
- package/dist/internal/rpc-query-host.js +1574 -0
- package/dist/internal/rpc-tags.js +18 -0
- package/dist/provider-bridge-acp-next.js +2636 -2653
- package/dist/provider-bridge-acp.js +2636 -2653
- package/dist/provider-bridge-testing.js +1210 -1238
- package/dist/provider-bridge.js +1279 -1306
- package/dist/replay-provider-child.mjs +6 -2
- package/dist/testing/app.js +1826 -163
- package/dist/testing/index.js +302 -104
- package/package.json +16 -2
|
@@ -0,0 +1,1574 @@
|
|
|
1
|
+
// src/rpc-contract.ts
|
|
2
|
+
var rpcErrorCodes = [
|
|
3
|
+
"forbidden",
|
|
4
|
+
"not_found",
|
|
5
|
+
"conflict",
|
|
6
|
+
"invalid",
|
|
7
|
+
"invalid_json",
|
|
8
|
+
"invalid_input",
|
|
9
|
+
"handler_error",
|
|
10
|
+
"invalid_output",
|
|
11
|
+
"non_json_result",
|
|
12
|
+
"unknown_method",
|
|
13
|
+
"transport_error",
|
|
14
|
+
"invalid_response",
|
|
15
|
+
"unknown_error"
|
|
16
|
+
];
|
|
17
|
+
var callErrorBrand = /* @__PURE__ */ Symbol.for("@get-bb/plugin-sdk/rpc-call-error");
|
|
18
|
+
var experimental_PluginRpcCallError = class _experimental_PluginRpcCallError extends Error {
|
|
19
|
+
/** Recognizes errors across the packed SDK's separately bundled entries. */
|
|
20
|
+
static [Symbol.hasInstance](value) {
|
|
21
|
+
return typeof value === "object" && value !== null && Reflect.get(value, callErrorBrand) === true && rpcErrorCodes.some((code) => code === Reflect.get(value, "code")) && typeof Reflect.get(value, "message") === "string";
|
|
22
|
+
}
|
|
23
|
+
code;
|
|
24
|
+
issues;
|
|
25
|
+
status;
|
|
26
|
+
serverCode;
|
|
27
|
+
constructor(args) {
|
|
28
|
+
super(args.message);
|
|
29
|
+
this.name = "experimental_PluginRpcCallError";
|
|
30
|
+
Object.defineProperty(this, callErrorBrand, { value: true });
|
|
31
|
+
this.code = args.code;
|
|
32
|
+
this.issues = args.issues;
|
|
33
|
+
this.status = args.status;
|
|
34
|
+
this.serverCode = args.serverCode;
|
|
35
|
+
}
|
|
36
|
+
/** Normalize failures at the RPC boundary; preserves an existing client error. */
|
|
37
|
+
static from(error, fallback = "transport_error") {
|
|
38
|
+
if (error instanceof _experimental_PluginRpcCallError) return error;
|
|
39
|
+
const record = typeof error === "object" && error !== null ? error : {};
|
|
40
|
+
const rawCode = Reflect.get(record, "code");
|
|
41
|
+
const code = rpcErrorCodes.find((value) => value === rawCode);
|
|
42
|
+
const message = Reflect.get(record, "message");
|
|
43
|
+
const status = Reflect.get(record, "status");
|
|
44
|
+
const rawIssues = Reflect.get(record, "issues");
|
|
45
|
+
const issues = [];
|
|
46
|
+
if (Array.isArray(rawIssues))
|
|
47
|
+
for (const issue of rawIssues) {
|
|
48
|
+
if (typeof issue !== "object" || issue === null || typeof Reflect.get(issue, "message") !== "string")
|
|
49
|
+
continue;
|
|
50
|
+
const path = Reflect.get(issue, "path");
|
|
51
|
+
if (path !== void 0 && (!Array.isArray(path) || !path.every(
|
|
52
|
+
(part) => typeof part === "string" || typeof part === "number" && Number.isFinite(part)
|
|
53
|
+
)))
|
|
54
|
+
continue;
|
|
55
|
+
issues.push({
|
|
56
|
+
message: Reflect.get(issue, "message"),
|
|
57
|
+
...path === void 0 ? {} : { path }
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return new _experimental_PluginRpcCallError({
|
|
61
|
+
code: code ?? (typeof rawCode === "string" ? "unknown_error" : fallback),
|
|
62
|
+
message: typeof message === "string" ? message : typeof error === "string" ? error : "Plugin RPC request failed",
|
|
63
|
+
...issues.length === 0 ? {} : { issues },
|
|
64
|
+
...typeof status === "number" ? { status } : {},
|
|
65
|
+
...typeof rawCode === "string" && code === void 0 ? { serverCode: rawCode } : {}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
var refusalBrand = /* @__PURE__ */ Symbol.for("@get-bb/plugin-sdk/rpc-refusal");
|
|
70
|
+
var experimental_PluginRpcRefusal = class extends Error {
|
|
71
|
+
[refusalBrand] = true;
|
|
72
|
+
code;
|
|
73
|
+
issues;
|
|
74
|
+
constructor(args) {
|
|
75
|
+
super(args.message);
|
|
76
|
+
this.name = "experimental_PluginRpcRefusal";
|
|
77
|
+
this.code = args.code;
|
|
78
|
+
this.issues = args.issues;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
// src/internal/rpc-query-host.ts
|
|
83
|
+
import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2 } from "react";
|
|
84
|
+
import { useIsFetching } from "@tanstack/react-query";
|
|
85
|
+
|
|
86
|
+
// ../query-tags/src/index.ts
|
|
87
|
+
import {
|
|
88
|
+
useCallback,
|
|
89
|
+
useEffect,
|
|
90
|
+
useMemo,
|
|
91
|
+
useRef,
|
|
92
|
+
useState,
|
|
93
|
+
useSyncExternalStore
|
|
94
|
+
} from "react";
|
|
95
|
+
import {
|
|
96
|
+
QueryObserver,
|
|
97
|
+
useQuery,
|
|
98
|
+
useQueryClient,
|
|
99
|
+
useMutation,
|
|
100
|
+
useMutationState,
|
|
101
|
+
replaceEqualDeep as replaceEqualDeep3
|
|
102
|
+
} from "@tanstack/react-query";
|
|
103
|
+
|
|
104
|
+
// ../query-tags/src/clock.ts
|
|
105
|
+
var order = 0;
|
|
106
|
+
function tick() {
|
|
107
|
+
return ++order;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// ../query-tags/src/keyed-store.ts
|
|
111
|
+
import {
|
|
112
|
+
notifyManager,
|
|
113
|
+
replaceEqualDeep
|
|
114
|
+
} from "@tanstack/react-query";
|
|
115
|
+
var KeyedCollection = class {
|
|
116
|
+
constructor(name) {
|
|
117
|
+
this.name = name;
|
|
118
|
+
}
|
|
119
|
+
name;
|
|
120
|
+
};
|
|
121
|
+
var stores = /* @__PURE__ */ new WeakMap();
|
|
122
|
+
function isObject(value) {
|
|
123
|
+
return typeof value === "object" && value !== null;
|
|
124
|
+
}
|
|
125
|
+
function collectionOf(store, token) {
|
|
126
|
+
let collection = store.collections.get(token);
|
|
127
|
+
if (collection === void 0) {
|
|
128
|
+
collection = {
|
|
129
|
+
base: /* @__PURE__ */ new Map(),
|
|
130
|
+
visible: /* @__PURE__ */ new Map(),
|
|
131
|
+
layers: [],
|
|
132
|
+
acknowledgedAt: /* @__PURE__ */ new Map(),
|
|
133
|
+
views: /* @__PURE__ */ new Map()
|
|
134
|
+
};
|
|
135
|
+
store.collections.set(token, collection);
|
|
136
|
+
}
|
|
137
|
+
return collection;
|
|
138
|
+
}
|
|
139
|
+
function readEntity(collection, id) {
|
|
140
|
+
const cached = collection.visible.get(id);
|
|
141
|
+
if (cached !== void 0) return cached;
|
|
142
|
+
let entity = collection.base.get(id);
|
|
143
|
+
if (entity === void 0) return void 0;
|
|
144
|
+
for (const layer of collection.layers)
|
|
145
|
+
if (layer.ids.has(id)) entity = layer.apply(entity, id);
|
|
146
|
+
collection.visible.set(id, entity);
|
|
147
|
+
return entity;
|
|
148
|
+
}
|
|
149
|
+
function changed(store, collection, ids) {
|
|
150
|
+
const dirty = new Set(ids);
|
|
151
|
+
for (const id of dirty) collection.visible.delete(id);
|
|
152
|
+
if (store.batching > 0) {
|
|
153
|
+
const pending = store.dirtyIds.get(collection) ?? /* @__PURE__ */ new Set();
|
|
154
|
+
for (const id of dirty) pending.add(id);
|
|
155
|
+
store.dirtyIds.set(collection, pending);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const views = /* @__PURE__ */ new Map();
|
|
159
|
+
for (const id of dirty)
|
|
160
|
+
for (const view of collection.views.get(id) ?? []) {
|
|
161
|
+
const viewIds = views.get(view) ?? /* @__PURE__ */ new Set();
|
|
162
|
+
viewIds.add(id);
|
|
163
|
+
views.set(view, viewIds);
|
|
164
|
+
}
|
|
165
|
+
notifyManager.batch(() => {
|
|
166
|
+
for (const [view, viewIds] of views) rematerialize(store, view, viewIds);
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
function writeBase(store, collection, id, update) {
|
|
170
|
+
const current = collection.base.get(id);
|
|
171
|
+
const next = update(current);
|
|
172
|
+
if (next === void 0 || next === current) return;
|
|
173
|
+
collection.base.set(id, next);
|
|
174
|
+
changed(store, collection, [id]);
|
|
175
|
+
}
|
|
176
|
+
function ingest(store, skeleton, id, item, readStart) {
|
|
177
|
+
const fresh = readStart > (skeleton.collection.acknowledgedAt.get(id) ?? -1);
|
|
178
|
+
writeBase(
|
|
179
|
+
store,
|
|
180
|
+
skeleton.collection,
|
|
181
|
+
id,
|
|
182
|
+
(current) => skeleton.view.read(item, current, fresh)
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
function materializeItem(store, view, item, entity) {
|
|
186
|
+
if (!isObject(item) || !isObject(entity)) return view.render(item, entity);
|
|
187
|
+
let byEntity = store.rows.get(item);
|
|
188
|
+
if (byEntity === void 0) {
|
|
189
|
+
byEntity = /* @__PURE__ */ new WeakMap();
|
|
190
|
+
store.rows.set(item, byEntity);
|
|
191
|
+
}
|
|
192
|
+
const cached = byEntity.get(entity);
|
|
193
|
+
if (cached !== void 0) return cached;
|
|
194
|
+
const row = view.render(item, entity);
|
|
195
|
+
byEntity.set(entity, row);
|
|
196
|
+
return row;
|
|
197
|
+
}
|
|
198
|
+
function rematerialize(store, query, dirty) {
|
|
199
|
+
const skeleton = store.skeletons.get(query);
|
|
200
|
+
if (skeleton === void 0) return;
|
|
201
|
+
const { view, collection } = skeleton;
|
|
202
|
+
const previous = store.materialized.get(query);
|
|
203
|
+
const incremental = dirty !== void 0 && previous !== void 0;
|
|
204
|
+
const slotKeys = /* @__PURE__ */ new Set();
|
|
205
|
+
if (incremental) {
|
|
206
|
+
for (const id of dirty)
|
|
207
|
+
for (const slot of skeleton.slotsById.get(id) ?? []) slotKeys.add(slot);
|
|
208
|
+
} else for (const slot of skeleton.slots.keys()) slotKeys.add(slot);
|
|
209
|
+
if (slotKeys.size === 0) return;
|
|
210
|
+
const items = /* @__PURE__ */ new Map();
|
|
211
|
+
const materialized = new Map(previous);
|
|
212
|
+
for (const slot of slotKeys) {
|
|
213
|
+
const prior = previous?.get(slot);
|
|
214
|
+
const visible = /* @__PURE__ */ new Map();
|
|
215
|
+
const rows = [];
|
|
216
|
+
for (const entry of skeleton.slots.get(slot) ?? []) {
|
|
217
|
+
if (entry.id === null) {
|
|
218
|
+
rows.push(entry.item);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const entity = readEntity(collection, entry.id);
|
|
222
|
+
if (entity !== void 0 && view.shows !== void 0 && !view.shows(entity, query.queryKey))
|
|
223
|
+
continue;
|
|
224
|
+
const previousRow = incremental ? prior?.get(entry.id) : void 0;
|
|
225
|
+
const row = previousRow !== void 0 && dirty?.has(entry.id) === false ? previousRow : replaceEqualDeep(
|
|
226
|
+
previousRow,
|
|
227
|
+
entity === void 0 ? entry.item : materializeItem(store, view, entry.item, entity)
|
|
228
|
+
);
|
|
229
|
+
visible.set(entry.id, row);
|
|
230
|
+
rows.push(row);
|
|
231
|
+
}
|
|
232
|
+
const unchanged = prior !== void 0 && prior.size === rows.length && [...prior.values()].every((row, index) => row === rows[index]);
|
|
233
|
+
if (incremental && unchanged) continue;
|
|
234
|
+
items.set(slot, rows);
|
|
235
|
+
materialized.set(slot, visible);
|
|
236
|
+
}
|
|
237
|
+
if (items.size === 0) return;
|
|
238
|
+
let next = view.rebuild(
|
|
239
|
+
incremental ? query.state.data : skeleton.data,
|
|
240
|
+
items
|
|
241
|
+
);
|
|
242
|
+
if (!incremental) {
|
|
243
|
+
next = replaceEqualDeep(query.state.data, next);
|
|
244
|
+
for (const slot of view.slots(next) ?? []) {
|
|
245
|
+
const visible = /* @__PURE__ */ new Map();
|
|
246
|
+
for (const item of slot.items) {
|
|
247
|
+
const id = view.keyOf(item);
|
|
248
|
+
if (id !== void 0) visible.set(id, item);
|
|
249
|
+
}
|
|
250
|
+
materialized.set(slot.key, visible);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
store.materialized.set(query, materialized);
|
|
254
|
+
if (next !== query.state.data) query.setState({ data: next });
|
|
255
|
+
}
|
|
256
|
+
function skeletonIds(skeleton) {
|
|
257
|
+
const ids = /* @__PURE__ */ new Set();
|
|
258
|
+
for (const entries of skeleton?.slots.values() ?? [])
|
|
259
|
+
for (const { id } of entries) if (id !== null) ids.add(id);
|
|
260
|
+
return ids;
|
|
261
|
+
}
|
|
262
|
+
function setSkeleton(store, query, skeleton) {
|
|
263
|
+
const previous = store.skeletons.get(query);
|
|
264
|
+
const previousIds = skeletonIds(previous);
|
|
265
|
+
const nextIds = skeletonIds(skeleton);
|
|
266
|
+
if (skeleton === void 0) {
|
|
267
|
+
store.skeletons.delete(query);
|
|
268
|
+
store.materialized.delete(query);
|
|
269
|
+
} else store.skeletons.set(query, skeleton);
|
|
270
|
+
const collection = skeleton?.collection ?? previous?.collection;
|
|
271
|
+
if (collection === void 0) return;
|
|
272
|
+
for (const id of nextIds) {
|
|
273
|
+
let views = collection.views.get(id);
|
|
274
|
+
if (views === void 0) {
|
|
275
|
+
views = /* @__PURE__ */ new Set();
|
|
276
|
+
collection.views.set(id, views);
|
|
277
|
+
}
|
|
278
|
+
views.add(query);
|
|
279
|
+
}
|
|
280
|
+
for (const id of previousIds) {
|
|
281
|
+
if (nextIds.has(id)) continue;
|
|
282
|
+
const views = collection.views.get(id);
|
|
283
|
+
views?.delete(query);
|
|
284
|
+
if (views === void 0 || views.size === 0) {
|
|
285
|
+
collection.views.delete(id);
|
|
286
|
+
collection.base.delete(id);
|
|
287
|
+
collection.visible.delete(id);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
function priorItem(materialized, slot, id) {
|
|
292
|
+
const same = materialized?.get(slot)?.get(id);
|
|
293
|
+
if (same !== void 0) return same;
|
|
294
|
+
for (const visible of materialized?.values() ?? []) {
|
|
295
|
+
const item = visible.get(id);
|
|
296
|
+
if (item !== void 0) return item;
|
|
297
|
+
}
|
|
298
|
+
return void 0;
|
|
299
|
+
}
|
|
300
|
+
function isHidden(entry, visible) {
|
|
301
|
+
return entry.id !== null && !visible.has(entry.id);
|
|
302
|
+
}
|
|
303
|
+
function keepHiddenEntries(previous, next, visible) {
|
|
304
|
+
if (!previous.some((entry) => isHidden(entry, visible))) return next;
|
|
305
|
+
const result = [...next];
|
|
306
|
+
let insertAt = result.length;
|
|
307
|
+
for (let index = previous.length - 1; index >= 0; index--) {
|
|
308
|
+
const entry = previous[index];
|
|
309
|
+
const existing = entry.id === null ? -1 : result.findIndex(({ id }) => id === entry.id);
|
|
310
|
+
if (existing >= 0) insertAt = existing;
|
|
311
|
+
else if (isHidden(entry, visible)) result.splice(insertAt, 0, entry);
|
|
312
|
+
}
|
|
313
|
+
return result;
|
|
314
|
+
}
|
|
315
|
+
function keptInsertions(store, query, slot, readStart) {
|
|
316
|
+
const insertions = (store.insertions.get(query) ?? []).filter(
|
|
317
|
+
(insertion) => insertion.at > readStart
|
|
318
|
+
);
|
|
319
|
+
store.insertions.set(query, insertions);
|
|
320
|
+
return insertions.filter((insertion) => insertion.slot === slot);
|
|
321
|
+
}
|
|
322
|
+
function batch(store, run) {
|
|
323
|
+
store.batching++;
|
|
324
|
+
try {
|
|
325
|
+
notifyManager.batch(run);
|
|
326
|
+
} finally {
|
|
327
|
+
store.batching--;
|
|
328
|
+
}
|
|
329
|
+
if (store.batching > 0) return;
|
|
330
|
+
const full = new Set(store.dirtyViews);
|
|
331
|
+
const partial = /* @__PURE__ */ new Map();
|
|
332
|
+
for (const [collection, ids] of store.dirtyIds)
|
|
333
|
+
for (const id of ids)
|
|
334
|
+
for (const view of collection.views.get(id) ?? []) {
|
|
335
|
+
if (full.has(view)) continue;
|
|
336
|
+
const viewIds = partial.get(view) ?? /* @__PURE__ */ new Set();
|
|
337
|
+
viewIds.add(id);
|
|
338
|
+
partial.set(view, viewIds);
|
|
339
|
+
}
|
|
340
|
+
store.dirtyIds.clear();
|
|
341
|
+
store.dirtyViews.clear();
|
|
342
|
+
notifyManager.batch(() => {
|
|
343
|
+
for (const view of full) rematerialize(store, view);
|
|
344
|
+
for (const [view, ids] of partial) rematerialize(store, view, ids);
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
function onViewWritten(store, query, view, manual) {
|
|
348
|
+
const data = query.state.data;
|
|
349
|
+
const slots = data === void 0 ? void 0 : view.slots(data);
|
|
350
|
+
if (slots === void 0) {
|
|
351
|
+
setSkeleton(store, query, void 0);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
const collection = collectionOf(store, view.collection);
|
|
355
|
+
const target = { view, collection };
|
|
356
|
+
const previous = store.skeletons.get(query);
|
|
357
|
+
const materialized = manual ? store.materialized.get(query) : void 0;
|
|
358
|
+
const readStart = manual ? -1 : store.fetchStartedAt.get(query) ?? 0;
|
|
359
|
+
const receipt = manual ? void 0 : store.receipts.get(query);
|
|
360
|
+
if (receipt !== void 0) store.receipts.delete(query);
|
|
361
|
+
batch(store, () => {
|
|
362
|
+
const nextSlots = /* @__PURE__ */ new Map();
|
|
363
|
+
const slotsById = /* @__PURE__ */ new Map();
|
|
364
|
+
for (const slot of slots) {
|
|
365
|
+
const entries = [];
|
|
366
|
+
for (const item of slot.items) {
|
|
367
|
+
const id = view.keyOf(item);
|
|
368
|
+
entries.push({ id: id ?? null, item });
|
|
369
|
+
if (id === void 0) continue;
|
|
370
|
+
const prior = priorItem(materialized, slot.key, id);
|
|
371
|
+
if (prior !== void 0) {
|
|
372
|
+
if (prior !== item)
|
|
373
|
+
writeBase(
|
|
374
|
+
store,
|
|
375
|
+
collection,
|
|
376
|
+
id,
|
|
377
|
+
(current) => current === void 0 ? current : view.write(item, prior, current)
|
|
378
|
+
);
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
const start = receipt === void 0 ? readStart : receipt.get(id);
|
|
382
|
+
if (start !== void 0) ingest(store, target, id, item, start);
|
|
383
|
+
else if (!collection.base.has(id))
|
|
384
|
+
ingest(store, target, id, item, readStart);
|
|
385
|
+
}
|
|
386
|
+
const previousEntries = previous?.slots.get(slot.key);
|
|
387
|
+
const visible = materialized?.get(slot.key);
|
|
388
|
+
const kept = previousEntries !== void 0 && visible !== void 0 ? keepHiddenEntries(previousEntries, entries, visible) : entries;
|
|
389
|
+
if (!manual) {
|
|
390
|
+
for (const insertion of keptInsertions(
|
|
391
|
+
store,
|
|
392
|
+
query,
|
|
393
|
+
slot.key,
|
|
394
|
+
readStart
|
|
395
|
+
))
|
|
396
|
+
if (!kept.some(({ id }) => id === insertion.entry.id))
|
|
397
|
+
kept.push(insertion.entry);
|
|
398
|
+
}
|
|
399
|
+
nextSlots.set(slot.key, kept);
|
|
400
|
+
for (const { id } of kept) {
|
|
401
|
+
if (id === null) continue;
|
|
402
|
+
const slotKeys = slotsById.get(id) ?? /* @__PURE__ */ new Set();
|
|
403
|
+
slotKeys.add(slot.key);
|
|
404
|
+
slotsById.set(id, slotKeys);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
setSkeleton(store, query, {
|
|
408
|
+
view,
|
|
409
|
+
collection,
|
|
410
|
+
data,
|
|
411
|
+
slots: nextSlots,
|
|
412
|
+
slotsById
|
|
413
|
+
});
|
|
414
|
+
store.dirtyViews.add(query);
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
function viewOf(store, query) {
|
|
418
|
+
const exact = store.exact.get(query.queryHash);
|
|
419
|
+
if (exact !== void 0) return exact;
|
|
420
|
+
for (const resolve of store.resolvers) {
|
|
421
|
+
const view = resolve(query.queryKey);
|
|
422
|
+
if (view !== void 0) return view;
|
|
423
|
+
}
|
|
424
|
+
return void 0;
|
|
425
|
+
}
|
|
426
|
+
function storeOf(client) {
|
|
427
|
+
const existing = stores.get(client);
|
|
428
|
+
if (existing !== void 0) return existing;
|
|
429
|
+
const store = {
|
|
430
|
+
client,
|
|
431
|
+
collections: /* @__PURE__ */ new Map(),
|
|
432
|
+
resolvers: [],
|
|
433
|
+
exact: /* @__PURE__ */ new Map(),
|
|
434
|
+
skeletons: /* @__PURE__ */ new Map(),
|
|
435
|
+
insertions: /* @__PURE__ */ new WeakMap(),
|
|
436
|
+
materialized: /* @__PURE__ */ new WeakMap(),
|
|
437
|
+
fetchStartedAt: /* @__PURE__ */ new WeakMap(),
|
|
438
|
+
receipts: /* @__PURE__ */ new WeakMap(),
|
|
439
|
+
rows: /* @__PURE__ */ new WeakMap(),
|
|
440
|
+
batching: 0,
|
|
441
|
+
dirtyIds: /* @__PURE__ */ new Map(),
|
|
442
|
+
dirtyViews: /* @__PURE__ */ new Set()
|
|
443
|
+
};
|
|
444
|
+
stores.set(client, store);
|
|
445
|
+
client.getQueryCache().subscribe((event) => {
|
|
446
|
+
const { query } = event;
|
|
447
|
+
if (event.type === "removed") {
|
|
448
|
+
if (store.skeletons.has(query)) setSkeleton(store, query, void 0);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
if (event.type !== "updated") return;
|
|
452
|
+
const { type } = event.action;
|
|
453
|
+
if (type !== "fetch" && type !== "success") return;
|
|
454
|
+
const view = viewOf(store, query);
|
|
455
|
+
if (view === void 0) return;
|
|
456
|
+
if (event.action.type === "fetch") {
|
|
457
|
+
store.fetchStartedAt.set(query, tick());
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (event.action.type === "success")
|
|
461
|
+
onViewWritten(store, query, view, event.action.manual === true);
|
|
462
|
+
});
|
|
463
|
+
return store;
|
|
464
|
+
}
|
|
465
|
+
function adopt(store, matches) {
|
|
466
|
+
for (const query of store.client.getQueryCache().getAll()) {
|
|
467
|
+
const view = matches(query);
|
|
468
|
+
if (view !== void 0 && query.state.data !== void 0)
|
|
469
|
+
onViewWritten(store, query, view, true);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
function registerKeyedView(client, queryKey, view) {
|
|
473
|
+
const store = storeOf(client);
|
|
474
|
+
const { queryHash } = client.defaultQueryOptions({ queryKey });
|
|
475
|
+
if (store.exact.has(queryHash)) return;
|
|
476
|
+
store.exact.set(queryHash, view);
|
|
477
|
+
adopt(store, (query) => query.queryHash === queryHash ? view : void 0);
|
|
478
|
+
}
|
|
479
|
+
function recordKeyedRead(client, queryKey, startedAt) {
|
|
480
|
+
const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
|
|
481
|
+
if (query !== void 0) storeOf(client).receipts.set(query, startedAt);
|
|
482
|
+
}
|
|
483
|
+
function bakeSettledLayers(collection) {
|
|
484
|
+
const baked = /* @__PURE__ */ new Set();
|
|
485
|
+
const pending = /* @__PURE__ */ new Set();
|
|
486
|
+
collection.layers = collection.layers.filter((layer) => {
|
|
487
|
+
const blocked = [...layer.ids].some((id) => pending.has(id));
|
|
488
|
+
if (!layer.settled || blocked) {
|
|
489
|
+
for (const id of layer.ids) pending.add(id);
|
|
490
|
+
return true;
|
|
491
|
+
}
|
|
492
|
+
for (const id of layer.ids) {
|
|
493
|
+
const current = collection.base.get(id);
|
|
494
|
+
if (current !== void 0)
|
|
495
|
+
collection.base.set(id, layer.apply(current, id));
|
|
496
|
+
baked.add(id);
|
|
497
|
+
}
|
|
498
|
+
return false;
|
|
499
|
+
});
|
|
500
|
+
return baked;
|
|
501
|
+
}
|
|
502
|
+
function predictKeyed(client, token, ids, apply) {
|
|
503
|
+
const store = storeOf(client);
|
|
504
|
+
const collection = collectionOf(store, token);
|
|
505
|
+
const layer = { ids, apply, settled: false };
|
|
506
|
+
collection.layers.push(layer);
|
|
507
|
+
changed(store, collection, ids);
|
|
508
|
+
const live = () => !layer.settled && collection.layers.includes(layer);
|
|
509
|
+
return {
|
|
510
|
+
accept() {
|
|
511
|
+
if (!live()) return;
|
|
512
|
+
const at = tick();
|
|
513
|
+
for (const id of ids) collection.acknowledgedAt.set(id, at);
|
|
514
|
+
layer.settled = true;
|
|
515
|
+
changed(store, collection, [...ids, ...bakeSettledLayers(collection)]);
|
|
516
|
+
},
|
|
517
|
+
remove() {
|
|
518
|
+
if (!live()) return;
|
|
519
|
+
collection.layers = collection.layers.filter((other) => other !== layer);
|
|
520
|
+
changed(store, collection, [...ids, ...bakeSettledLayers(collection)]);
|
|
521
|
+
}
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// ../query-tags/src/optimistic.ts
|
|
526
|
+
import {
|
|
527
|
+
matchQuery,
|
|
528
|
+
notifyManager as notifyManager2,
|
|
529
|
+
replaceEqualDeep as replaceEqualDeep2
|
|
530
|
+
} from "@tanstack/react-query";
|
|
531
|
+
function optimisticKeyedUpdate(collection, key, update) {
|
|
532
|
+
return {
|
|
533
|
+
collection,
|
|
534
|
+
key,
|
|
535
|
+
update: (current, result) => update(current, result)
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
function optimisticQueryUpdate(queryKey, update, path = []) {
|
|
539
|
+
return {
|
|
540
|
+
queryKey,
|
|
541
|
+
path: [...path],
|
|
542
|
+
update: (current, result) => update(current, result)
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
var predictions = /* @__PURE__ */ new WeakMap();
|
|
546
|
+
var receipts = /* @__PURE__ */ new WeakMap();
|
|
547
|
+
var taggedMeta = /* @__PURE__ */ new WeakSet();
|
|
548
|
+
var syncedClients = /* @__PURE__ */ new WeakMap();
|
|
549
|
+
function valueAt(data, path) {
|
|
550
|
+
let value = data;
|
|
551
|
+
for (const key of path) {
|
|
552
|
+
if (typeof value !== "object" || value === null || !Object.hasOwn(value, key))
|
|
553
|
+
return;
|
|
554
|
+
value = Reflect.get(value, key);
|
|
555
|
+
}
|
|
556
|
+
return value === void 0 ? void 0 : { value };
|
|
557
|
+
}
|
|
558
|
+
function replaceAt(data, path, value) {
|
|
559
|
+
const [key, ...rest] = path;
|
|
560
|
+
if (key === void 0) return value;
|
|
561
|
+
if (typeof data !== "object" || data === null) return data;
|
|
562
|
+
const next = Array.isArray(data) ? [...data] : { ...data };
|
|
563
|
+
Reflect.set(next, key, replaceAt(Reflect.get(data, key), rest, value));
|
|
564
|
+
return next;
|
|
565
|
+
}
|
|
566
|
+
function prefix(left, right) {
|
|
567
|
+
return left.length <= right.length && left.every((part, index) => part === right[index]);
|
|
568
|
+
}
|
|
569
|
+
function olderPending(state, layer) {
|
|
570
|
+
return state.layers.some(
|
|
571
|
+
(other) => other.order < layer.order && !other.settled && (prefix(other.path, layer.path) || prefix(layer.path, other.path))
|
|
572
|
+
);
|
|
573
|
+
}
|
|
574
|
+
function confirmedValue(current, predicted, confirmed) {
|
|
575
|
+
if (Object.is(predicted, confirmed)) return current;
|
|
576
|
+
if (typeof current !== "object" || current === null || typeof predicted !== "object" || predicted === null || typeof confirmed !== "object" || confirmed === null || Array.isArray(predicted) !== Array.isArray(confirmed) || Array.isArray(predicted) && (!Array.isArray(confirmed) || predicted.length !== confirmed.length))
|
|
577
|
+
return confirmed;
|
|
578
|
+
const next = Array.isArray(current) ? [...current] : { ...current };
|
|
579
|
+
for (const key of /* @__PURE__ */ new Set([
|
|
580
|
+
...Object.keys(predicted),
|
|
581
|
+
...Object.keys(confirmed)
|
|
582
|
+
])) {
|
|
583
|
+
if (!Object.hasOwn(confirmed, key)) Reflect.deleteProperty(next, key);
|
|
584
|
+
else
|
|
585
|
+
Reflect.set(
|
|
586
|
+
next,
|
|
587
|
+
key,
|
|
588
|
+
confirmedValue(
|
|
589
|
+
Reflect.get(current, key),
|
|
590
|
+
Reflect.get(predicted, key),
|
|
591
|
+
Reflect.get(confirmed, key)
|
|
592
|
+
)
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
return next;
|
|
596
|
+
}
|
|
597
|
+
function rebase(base, visible, next) {
|
|
598
|
+
if (Object.is(visible, next)) return base;
|
|
599
|
+
if (typeof base !== "object" || base === null || typeof visible !== "object" || visible === null || typeof next !== "object" || next === null || Array.isArray(base) || Array.isArray(visible) || Array.isArray(next))
|
|
600
|
+
return next;
|
|
601
|
+
const result = {};
|
|
602
|
+
for (const key of Object.keys(base))
|
|
603
|
+
if (!Object.hasOwn(visible, key) && !Object.hasOwn(next, key))
|
|
604
|
+
result[key] = Reflect.get(base, key);
|
|
605
|
+
for (const key of Object.keys(next))
|
|
606
|
+
result[key] = Object.hasOwn(visible, key) && Object.hasOwn(base, key) ? rebase(
|
|
607
|
+
Reflect.get(base, key),
|
|
608
|
+
Reflect.get(visible, key),
|
|
609
|
+
Reflect.get(next, key)
|
|
610
|
+
) : Reflect.get(next, key);
|
|
611
|
+
return result;
|
|
612
|
+
}
|
|
613
|
+
function projected(state) {
|
|
614
|
+
return state.layers.reduce((data, layer) => {
|
|
615
|
+
const current = valueAt(data, layer.path);
|
|
616
|
+
return replaceAt(
|
|
617
|
+
data,
|
|
618
|
+
layer.path,
|
|
619
|
+
layer.update(current === void 0 ? layer.initial : current.value)
|
|
620
|
+
);
|
|
621
|
+
}, state.base);
|
|
622
|
+
}
|
|
623
|
+
var predictionListeners = /* @__PURE__ */ new WeakMap();
|
|
624
|
+
function subscribeOptimisticQuery(query, listener) {
|
|
625
|
+
if (query === void 0) return () => {
|
|
626
|
+
};
|
|
627
|
+
let listeners = predictionListeners.get(query);
|
|
628
|
+
if (listeners === void 0) {
|
|
629
|
+
listeners = /* @__PURE__ */ new Set();
|
|
630
|
+
predictionListeners.set(query, listeners);
|
|
631
|
+
}
|
|
632
|
+
listeners.add(listener);
|
|
633
|
+
return () => {
|
|
634
|
+
listeners.delete(listener);
|
|
635
|
+
if (listeners.size === 0) predictionListeners.delete(query);
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
function isTaggedQuery(query) {
|
|
639
|
+
return query.meta !== void 0 && taggedMeta.has(query.meta);
|
|
640
|
+
}
|
|
641
|
+
function applyLayer(data, layer) {
|
|
642
|
+
const current = valueAt(data, layer.path);
|
|
643
|
+
return replaceAt(
|
|
644
|
+
data,
|
|
645
|
+
layer.path,
|
|
646
|
+
layer.update(current === void 0 ? layer.initial : current.value)
|
|
647
|
+
);
|
|
648
|
+
}
|
|
649
|
+
function confirmLayers(query, state, ready) {
|
|
650
|
+
const tagged = isTaggedQuery(query);
|
|
651
|
+
while (state.layers[0] !== void 0 && ready(state.layers[0])) {
|
|
652
|
+
const layer = state.layers.shift();
|
|
653
|
+
state.base = applyLayer(state.base, layer);
|
|
654
|
+
if (tagged && !layer.fresh) state.guards.push(layer);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
function confirmBeforeWrite(query, state) {
|
|
658
|
+
confirmLayers(query, state, (layer) => layer.acceptedAt !== null);
|
|
659
|
+
}
|
|
660
|
+
function isIdle(state) {
|
|
661
|
+
return state.layers.length === 0 && state.guards.length === 0;
|
|
662
|
+
}
|
|
663
|
+
function untrack(query, state) {
|
|
664
|
+
predictions.delete(query);
|
|
665
|
+
const synced = syncedClients.get(state.client);
|
|
666
|
+
if (synced === void 0) return;
|
|
667
|
+
synced.queries.delete(query);
|
|
668
|
+
if (synced.queries.size === 0) {
|
|
669
|
+
synced.unsubscribe();
|
|
670
|
+
syncedClients.delete(state.client);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
function track(query, state) {
|
|
674
|
+
predictions.set(query, state);
|
|
675
|
+
let synced = syncedClients.get(state.client);
|
|
676
|
+
if (synced === void 0) {
|
|
677
|
+
const queries = /* @__PURE__ */ new Set();
|
|
678
|
+
const unsubscribe = state.client.getQueryCache().subscribe((event) => {
|
|
679
|
+
if (event.type !== "updated" || event.action.type !== "success") return;
|
|
680
|
+
const current = predictions.get(event.query);
|
|
681
|
+
if (current === void 0 || isTaggedQuery(event.query)) return;
|
|
682
|
+
const data = event.query.state.data;
|
|
683
|
+
if (event.action.manual) {
|
|
684
|
+
confirmBeforeWrite(event.query, current);
|
|
685
|
+
current.base = rebase(current.base, current.visible, data);
|
|
686
|
+
} else {
|
|
687
|
+
current.base = data;
|
|
688
|
+
}
|
|
689
|
+
publish(event.query, current);
|
|
690
|
+
});
|
|
691
|
+
synced = { queries, unsubscribe };
|
|
692
|
+
syncedClients.set(state.client, synced);
|
|
693
|
+
}
|
|
694
|
+
synced.queries.add(query);
|
|
695
|
+
}
|
|
696
|
+
function publish(query, state) {
|
|
697
|
+
if (!isTaggedQuery(query))
|
|
698
|
+
confirmLayers(query, state, (layer) => layer.settled);
|
|
699
|
+
const data = replaceEqualDeep2(query.state.data, projected(state));
|
|
700
|
+
state.visible = data;
|
|
701
|
+
query.setState({ data });
|
|
702
|
+
if (isIdle(state)) untrack(query, state);
|
|
703
|
+
for (const listener of predictionListeners.get(query) ?? []) listener();
|
|
704
|
+
}
|
|
705
|
+
function markTaggedQueryMeta(meta) {
|
|
706
|
+
taggedMeta.add(meta);
|
|
707
|
+
}
|
|
708
|
+
function commitTaggedReadReceipt(query, data, started) {
|
|
709
|
+
receipts.set(query, { data, started });
|
|
710
|
+
}
|
|
711
|
+
function consumeReceipt(query, next) {
|
|
712
|
+
const receipt = receipts.get(query);
|
|
713
|
+
if (receipt === void 0 || !Object.is(receipt.data, next)) return;
|
|
714
|
+
receipts.delete(query);
|
|
715
|
+
return receipt;
|
|
716
|
+
}
|
|
717
|
+
function refreshedBy(receipt, layer) {
|
|
718
|
+
return layer.acceptedAt !== null && receipt.started > layer.acceptedAt;
|
|
719
|
+
}
|
|
720
|
+
function taggedStructuralSharing(client, queryKey, previous, next) {
|
|
721
|
+
const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
|
|
722
|
+
if (query !== void 0 && Object.is(previous, query.state.data)) {
|
|
723
|
+
const receipt = consumeReceipt(query, next);
|
|
724
|
+
const state = predictions.get(query);
|
|
725
|
+
if (state !== void 0) {
|
|
726
|
+
if (receipt !== void 0) {
|
|
727
|
+
const refreshed = /* @__PURE__ */ new Set();
|
|
728
|
+
for (const layer of state.layers) {
|
|
729
|
+
if (refreshedBy(receipt, layer)) {
|
|
730
|
+
layer.fresh = true;
|
|
731
|
+
refreshed.add(layer);
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
state.layers = state.layers.filter(
|
|
735
|
+
(layer) => !layer.settled || !refreshed.has(layer) || olderPending(state, layer)
|
|
736
|
+
);
|
|
737
|
+
}
|
|
738
|
+
if (receipt !== void 0) {
|
|
739
|
+
state.guards = state.guards.filter(
|
|
740
|
+
(guard) => !refreshedBy(receipt, guard)
|
|
741
|
+
);
|
|
742
|
+
state.base = state.guards.reduce(applyLayer, next);
|
|
743
|
+
} else {
|
|
744
|
+
confirmBeforeWrite(query, state);
|
|
745
|
+
state.base = rebase(state.base, previous, next);
|
|
746
|
+
}
|
|
747
|
+
next = projected(state);
|
|
748
|
+
state.visible = next;
|
|
749
|
+
if (isIdle(state)) untrack(query, state);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
const sharing = client.defaultQueryOptions({ queryKey }).structuralSharing;
|
|
753
|
+
return sharing === false ? next : typeof sharing === "function" ? sharing(previous, next) : replaceEqualDeep2(previous, next);
|
|
754
|
+
}
|
|
755
|
+
function getTaggedReadData(client, queryKey) {
|
|
756
|
+
const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
|
|
757
|
+
const state = query === void 0 ? void 0 : predictions.get(query);
|
|
758
|
+
return state === void 0 ? query?.state.data : state.base;
|
|
759
|
+
}
|
|
760
|
+
function isKeyedUpdate(update) {
|
|
761
|
+
return "collection" in update;
|
|
762
|
+
}
|
|
763
|
+
function beginKeyedPredictions(client, updates, result) {
|
|
764
|
+
const byCollection = /* @__PURE__ */ new Map();
|
|
765
|
+
for (const update of updates) {
|
|
766
|
+
const byKey = byCollection.get(update.collection) ?? /* @__PURE__ */ new Map();
|
|
767
|
+
byKey.set(update.key, [...byKey.get(update.key) ?? [], update]);
|
|
768
|
+
byCollection.set(update.collection, byKey);
|
|
769
|
+
}
|
|
770
|
+
return [...byCollection].map(
|
|
771
|
+
([collection, byKey]) => predictKeyed(
|
|
772
|
+
client,
|
|
773
|
+
collection,
|
|
774
|
+
new Set(byKey.keys()),
|
|
775
|
+
(entity, key) => (byKey.get(key) ?? []).reduce(
|
|
776
|
+
(current, update) => update.update(current, result()),
|
|
777
|
+
entity
|
|
778
|
+
)
|
|
779
|
+
)
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
function beginOptimisticMutation(client, allUpdates) {
|
|
783
|
+
const owner = {};
|
|
784
|
+
const mutationOrder = tick();
|
|
785
|
+
let accepted;
|
|
786
|
+
let done = false;
|
|
787
|
+
const updates = allUpdates.filter(
|
|
788
|
+
(update) => !isKeyedUpdate(update)
|
|
789
|
+
);
|
|
790
|
+
const keyed = beginKeyedPredictions(
|
|
791
|
+
client,
|
|
792
|
+
allUpdates.filter(isKeyedUpdate),
|
|
793
|
+
() => accepted?.result.value === void 0 ? void 0 : accepted.result
|
|
794
|
+
);
|
|
795
|
+
const affected = /* @__PURE__ */ new Map();
|
|
796
|
+
const attached = new Map(
|
|
797
|
+
updates.map((update) => [update, /* @__PURE__ */ new Set()])
|
|
798
|
+
);
|
|
799
|
+
const attach = (query, update) => {
|
|
800
|
+
const queries = attached.get(update);
|
|
801
|
+
if (queries.has(query) || query.state.data === void 0) return;
|
|
802
|
+
const state = predictions.get(query) ?? {
|
|
803
|
+
client,
|
|
804
|
+
base: query.state.data,
|
|
805
|
+
visible: query.state.data,
|
|
806
|
+
layers: [],
|
|
807
|
+
guards: []
|
|
808
|
+
};
|
|
809
|
+
const current = valueAt(projected(state), update.path);
|
|
810
|
+
if (current === void 0) return;
|
|
811
|
+
queries.add(query);
|
|
812
|
+
const layer = {
|
|
813
|
+
owner,
|
|
814
|
+
order: mutationOrder,
|
|
815
|
+
path: update.path,
|
|
816
|
+
initial: current.value,
|
|
817
|
+
update: (value) => update.update(value, accepted?.result),
|
|
818
|
+
acceptedAt: accepted?.at ?? null,
|
|
819
|
+
fresh: false,
|
|
820
|
+
settled: false
|
|
821
|
+
};
|
|
822
|
+
const index = state.layers.findIndex((other) => other.order > layer.order);
|
|
823
|
+
if (index < 0) state.layers.push(layer);
|
|
824
|
+
else state.layers.splice(index, 0, layer);
|
|
825
|
+
track(query, state);
|
|
826
|
+
affected.set(query, state);
|
|
827
|
+
publish(query, state);
|
|
828
|
+
};
|
|
829
|
+
const unsubscribe = updates.length === 0 ? () => {
|
|
830
|
+
} : client.getQueryCache().subscribe((event) => {
|
|
831
|
+
if (event.type !== "updated" || event.action.type !== "success")
|
|
832
|
+
return;
|
|
833
|
+
for (const update of updates)
|
|
834
|
+
if (matchQuery(
|
|
835
|
+
{ queryKey: update.queryKey, exact: true },
|
|
836
|
+
event.query
|
|
837
|
+
))
|
|
838
|
+
attach(event.query, update);
|
|
839
|
+
});
|
|
840
|
+
const finish = () => {
|
|
841
|
+
done = true;
|
|
842
|
+
unsubscribe();
|
|
843
|
+
};
|
|
844
|
+
const rollback = () => notifyManager2.batch(() => {
|
|
845
|
+
if (accepted !== void 0 || done) return;
|
|
846
|
+
finish();
|
|
847
|
+
for (const prediction of keyed) prediction.remove();
|
|
848
|
+
for (const [query, state] of affected) {
|
|
849
|
+
state.layers = state.layers.filter((layer) => layer.owner !== owner);
|
|
850
|
+
publish(query, state);
|
|
851
|
+
}
|
|
852
|
+
});
|
|
853
|
+
try {
|
|
854
|
+
notifyManager2.batch(() => {
|
|
855
|
+
for (const update of updates)
|
|
856
|
+
for (const query of client.getQueryCache().findAll({
|
|
857
|
+
queryKey: update.queryKey,
|
|
858
|
+
exact: true
|
|
859
|
+
}))
|
|
860
|
+
attach(query, update);
|
|
861
|
+
});
|
|
862
|
+
} catch (error) {
|
|
863
|
+
rollback();
|
|
864
|
+
throw error;
|
|
865
|
+
}
|
|
866
|
+
return {
|
|
867
|
+
rollback,
|
|
868
|
+
accept(result) {
|
|
869
|
+
accepted = { at: tick(), result: { value: result } };
|
|
870
|
+
notifyManager2.batch(() => {
|
|
871
|
+
for (const prediction of keyed) prediction.accept();
|
|
872
|
+
for (const [query, state] of affected) {
|
|
873
|
+
for (const layer of state.layers)
|
|
874
|
+
if (layer.owner === owner) layer.acceptedAt = accepted.at;
|
|
875
|
+
publish(query, state);
|
|
876
|
+
}
|
|
877
|
+
});
|
|
878
|
+
},
|
|
879
|
+
settle() {
|
|
880
|
+
if (done) return;
|
|
881
|
+
finish();
|
|
882
|
+
notifyManager2.batch(() => {
|
|
883
|
+
for (const [query, state] of affected) {
|
|
884
|
+
const tagged = isTaggedQuery(query);
|
|
885
|
+
state.layers = state.layers.filter((layer) => {
|
|
886
|
+
if (layer.owner !== owner) return true;
|
|
887
|
+
layer.settled = true;
|
|
888
|
+
if (!tagged) return true;
|
|
889
|
+
if (!layer.fresh) return true;
|
|
890
|
+
if (!olderPending(state, layer)) return false;
|
|
891
|
+
const current = valueAt(state.base, layer.path);
|
|
892
|
+
if (current !== void 0) {
|
|
893
|
+
const update = layer.update;
|
|
894
|
+
const predicted = update(current.value);
|
|
895
|
+
layer.update = (value) => confirmedValue(update(value), predicted, current.value);
|
|
896
|
+
}
|
|
897
|
+
return true;
|
|
898
|
+
});
|
|
899
|
+
publish(query, state);
|
|
900
|
+
}
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
// ../query-tags/src/index.ts
|
|
907
|
+
function useTaggedQuery(options, client) {
|
|
908
|
+
const queryClient = useQueryClient(client);
|
|
909
|
+
const result = useQuery(options, queryClient);
|
|
910
|
+
const query = queryClient.getQueryCache().get(queryClient.defaultQueryOptions(options).queryHash);
|
|
911
|
+
const subscribed = options.subscribed !== false;
|
|
912
|
+
const subscribe = useCallback(
|
|
913
|
+
(listener) => subscribed ? subscribeOptimisticQuery(query, listener) : () => {
|
|
914
|
+
},
|
|
915
|
+
[query, subscribed]
|
|
916
|
+
);
|
|
917
|
+
const snapshot = useCallback(() => query?.state.data, [query]);
|
|
918
|
+
useSyncExternalStore(subscribe, snapshot, snapshot);
|
|
919
|
+
return result;
|
|
920
|
+
}
|
|
921
|
+
var registrations = /* @__PURE__ */ new WeakMap();
|
|
922
|
+
var reads = /* @__PURE__ */ new WeakMap();
|
|
923
|
+
function taggedQueryOptions(client, queryKey, registration) {
|
|
924
|
+
const meta = {};
|
|
925
|
+
markTaggedQueryMeta(meta);
|
|
926
|
+
registrations.set(meta, {
|
|
927
|
+
scope: registration.scope,
|
|
928
|
+
tagsOf: (data) => registration.tagsOf(data),
|
|
929
|
+
onInvalidate: (data, tags) => registration.onInvalidate?.(data, tags)
|
|
930
|
+
});
|
|
931
|
+
return {
|
|
932
|
+
meta,
|
|
933
|
+
structuralSharing: (previous, next) => taggedStructuralSharing(client, queryKey, previous, next)
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
function registrationOf(query) {
|
|
937
|
+
return query.meta === void 0 ? void 0 : registrations.get(query.meta);
|
|
938
|
+
}
|
|
939
|
+
async function runTaggedRead(client, queryKey, read) {
|
|
940
|
+
const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
|
|
941
|
+
if (query === void 0) return read();
|
|
942
|
+
const registration = registrationOf(query);
|
|
943
|
+
for (; ; ) {
|
|
944
|
+
const pending = { tags: /* @__PURE__ */ new Set(), restart: false };
|
|
945
|
+
reads.set(query, pending);
|
|
946
|
+
const started = tick();
|
|
947
|
+
try {
|
|
948
|
+
const result = await read();
|
|
949
|
+
const overlap = registration?.tagsOf(result).some((tag) => pending.tags.has(tag));
|
|
950
|
+
if (overlap) registration?.onInvalidate?.(result, [...pending.tags]);
|
|
951
|
+
if (pending.restart || overlap) continue;
|
|
952
|
+
commitTaggedReadReceipt(query, result, started);
|
|
953
|
+
return result;
|
|
954
|
+
} catch (error) {
|
|
955
|
+
if (pending.restart) continue;
|
|
956
|
+
throw error;
|
|
957
|
+
} finally {
|
|
958
|
+
if (reads.get(query) === pending) reads.delete(query);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
async function invalidateTags(client, scope, tags) {
|
|
963
|
+
if (tags?.length === 0) return;
|
|
964
|
+
const matched = /* @__PURE__ */ new Set();
|
|
965
|
+
const pendingReads = [];
|
|
966
|
+
for (const query of client.getQueryCache().getAll()) {
|
|
967
|
+
const registration = registrationOf(query);
|
|
968
|
+
if (registration?.scope !== scope) continue;
|
|
969
|
+
const pending = reads.get(query);
|
|
970
|
+
const data = getTaggedReadData(client, query.queryKey);
|
|
971
|
+
const matches = tags === null || data === void 0 && pending === void 0 || data !== void 0 && registration.tagsOf(data).some((tag) => tags.includes(tag));
|
|
972
|
+
if (matches) registration.onInvalidate?.(data, tags);
|
|
973
|
+
if (pending !== void 0) {
|
|
974
|
+
if (matches) pending.restart = true;
|
|
975
|
+
else for (const tag of tags ?? []) pending.tags.add(tag);
|
|
976
|
+
if (query.isActive() && query.promise !== void 0)
|
|
977
|
+
pendingReads.push(query.promise);
|
|
978
|
+
}
|
|
979
|
+
if (matches) {
|
|
980
|
+
matched.add(query);
|
|
981
|
+
if (pending === void 0 && query.isActive() && query.state.fetchStatus === "fetching" && query.promise !== void 0) {
|
|
982
|
+
const refetch = () => client.invalidateQueries(
|
|
983
|
+
{ predicate: (candidate) => candidate === query },
|
|
984
|
+
{ cancelRefetch: false }
|
|
985
|
+
);
|
|
986
|
+
pendingReads.push(query.promise.then(refetch, refetch));
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
await Promise.allSettled([
|
|
991
|
+
client.invalidateQueries(
|
|
992
|
+
{ predicate: (query) => matched.has(query) },
|
|
993
|
+
{ cancelRefetch: false }
|
|
994
|
+
),
|
|
995
|
+
...pendingReads
|
|
996
|
+
]);
|
|
997
|
+
}
|
|
998
|
+
async function executeTaggedMutation(invalidate, call, prediction) {
|
|
999
|
+
const { result, invalidated } = await call();
|
|
1000
|
+
prediction?.accept(result);
|
|
1001
|
+
const refresh = async () => {
|
|
1002
|
+
try {
|
|
1003
|
+
if (invalidate !== void 0 && invalidated.length > 0)
|
|
1004
|
+
await invalidate(invalidated);
|
|
1005
|
+
} finally {
|
|
1006
|
+
prediction?.settle();
|
|
1007
|
+
}
|
|
1008
|
+
};
|
|
1009
|
+
void refresh().catch(() => {
|
|
1010
|
+
});
|
|
1011
|
+
return result;
|
|
1012
|
+
}
|
|
1013
|
+
var pluginTagScope = (pluginId) => `plugin:${pluginId}`;
|
|
1014
|
+
function restartTaggedRead(query) {
|
|
1015
|
+
const pending = reads.get(query);
|
|
1016
|
+
if (pending) pending.restart = true;
|
|
1017
|
+
}
|
|
1018
|
+
function useTaggedMutation({
|
|
1019
|
+
client,
|
|
1020
|
+
invalidate,
|
|
1021
|
+
call,
|
|
1022
|
+
optimistic,
|
|
1023
|
+
meta
|
|
1024
|
+
}) {
|
|
1025
|
+
const [owner] = useState(() => ({}));
|
|
1026
|
+
const predict = useRef(optimistic);
|
|
1027
|
+
useEffect(() => {
|
|
1028
|
+
predict.current = optimistic;
|
|
1029
|
+
}, [optimistic]);
|
|
1030
|
+
const mutation = useMutation(
|
|
1031
|
+
{
|
|
1032
|
+
meta: { ...meta, taggedMutationOwner: owner },
|
|
1033
|
+
mutationFn: ({ input, prediction }) => executeTaggedMutation(invalidate, () => call(input), prediction)
|
|
1034
|
+
},
|
|
1035
|
+
client
|
|
1036
|
+
);
|
|
1037
|
+
const pendingInputs = useMutationState(
|
|
1038
|
+
{
|
|
1039
|
+
filters: {
|
|
1040
|
+
status: "pending",
|
|
1041
|
+
predicate: (entry) => entry.options.meta?.taggedMutationOwner === owner
|
|
1042
|
+
},
|
|
1043
|
+
select: (entry) => entry.state.variables.input
|
|
1044
|
+
},
|
|
1045
|
+
client
|
|
1046
|
+
);
|
|
1047
|
+
const { mutateAsync } = mutation;
|
|
1048
|
+
const mutate = useCallback(
|
|
1049
|
+
(input) => {
|
|
1050
|
+
const prediction = beginOptimisticMutation(
|
|
1051
|
+
client,
|
|
1052
|
+
predict.current?.(input) ?? []
|
|
1053
|
+
);
|
|
1054
|
+
return mutateAsync({ input, prediction }).catch((error) => {
|
|
1055
|
+
prediction.rollback();
|
|
1056
|
+
throw error;
|
|
1057
|
+
});
|
|
1058
|
+
},
|
|
1059
|
+
[client, mutateAsync]
|
|
1060
|
+
);
|
|
1061
|
+
return {
|
|
1062
|
+
mutate,
|
|
1063
|
+
pendingInputs,
|
|
1064
|
+
isPending: pendingInputs.length > 0,
|
|
1065
|
+
error: mutation.error,
|
|
1066
|
+
reset: mutation.reset
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
function hasRows(data) {
|
|
1070
|
+
return typeof data === "object" && data !== null && "result" in data && typeof data.result === "object" && data.result !== null;
|
|
1071
|
+
}
|
|
1072
|
+
var rowKey = (item) => Array.isArray(item) && typeof item[0] === "string" ? item[0] : void 0;
|
|
1073
|
+
var rowValue = (item) => Array.isArray(item) ? item[1] : void 0;
|
|
1074
|
+
function keyedRowsView(collection) {
|
|
1075
|
+
return {
|
|
1076
|
+
collection,
|
|
1077
|
+
slots: (data) => hasRows(data) ? [{ key: "result", items: Object.entries(data.result) }] : void 0,
|
|
1078
|
+
rebuild: (data, items) => hasRows(data) ? {
|
|
1079
|
+
...data,
|
|
1080
|
+
result: Object.fromEntries(
|
|
1081
|
+
(items.get("result") ?? []).flatMap((item) => {
|
|
1082
|
+
const key = rowKey(item);
|
|
1083
|
+
return key === void 0 ? [] : [[key, rowValue(item)]];
|
|
1084
|
+
})
|
|
1085
|
+
)
|
|
1086
|
+
} : data,
|
|
1087
|
+
keyOf: rowKey,
|
|
1088
|
+
read: (item, current, fresh) => current === void 0 || fresh ? rowValue(item) : current,
|
|
1089
|
+
write: rowValue,
|
|
1090
|
+
render: (item, entity) => Object.is(rowValue(item), entity) ? item : [rowKey(item), entity]
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
function createTaggedKeyedQueryOwner(options) {
|
|
1094
|
+
const { client, queryKey, scope, collection, read } = options;
|
|
1095
|
+
registerKeyedView(client, queryKey, keyedRowsView(collection));
|
|
1096
|
+
const keys = /* @__PURE__ */ new Map();
|
|
1097
|
+
let readingKeys = /* @__PURE__ */ new Set();
|
|
1098
|
+
let missingOnly = false;
|
|
1099
|
+
let refreshAll = false;
|
|
1100
|
+
const dirtyKeys = /* @__PURE__ */ new Set();
|
|
1101
|
+
const collectSubscribedKeys = () => new Promise((resolve) => {
|
|
1102
|
+
queueMicrotask(() => resolve([...keys.keys()]));
|
|
1103
|
+
});
|
|
1104
|
+
const observer = new QueryObserver(client, {
|
|
1105
|
+
queryKey,
|
|
1106
|
+
...taggedQueryOptions(client, queryKey, {
|
|
1107
|
+
scope,
|
|
1108
|
+
tagsOf: (data) => [
|
|
1109
|
+
...data.tags,
|
|
1110
|
+
...Object.values(data.keyTags).flat()
|
|
1111
|
+
],
|
|
1112
|
+
onInvalidate: (data, tags) => {
|
|
1113
|
+
if (tags === null || data === void 0 || data.tags.some((tag) => tags.includes(tag))) {
|
|
1114
|
+
refreshAll = true;
|
|
1115
|
+
} else {
|
|
1116
|
+
for (const [key, ownTags] of Object.entries(data.keyTags))
|
|
1117
|
+
if (ownTags.some((tag) => tags.includes(tag))) dirtyKeys.add(key);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
}),
|
|
1121
|
+
queryFn: () => {
|
|
1122
|
+
let previous = getTaggedReadData(client, queryKey);
|
|
1123
|
+
const startedAt = /* @__PURE__ */ new Map();
|
|
1124
|
+
let refresh = !missingOnly && dirtyKeys.size === 0;
|
|
1125
|
+
missingOnly = false;
|
|
1126
|
+
const refreshedKeys = /* @__PURE__ */ new Set();
|
|
1127
|
+
let refreshedAll = false;
|
|
1128
|
+
return runTaggedRead(client, queryKey, async () => {
|
|
1129
|
+
const subscribed = await collectSubscribedKeys();
|
|
1130
|
+
const all = refreshAll || refresh;
|
|
1131
|
+
refresh = false;
|
|
1132
|
+
const dirty = new Set(dirtyKeys);
|
|
1133
|
+
for (const key of dirty) refreshedKeys.add(key);
|
|
1134
|
+
refreshedAll ||= all;
|
|
1135
|
+
dirtyKeys.clear();
|
|
1136
|
+
refreshAll = false;
|
|
1137
|
+
const requested = subscribed.filter(
|
|
1138
|
+
(key) => all || dirty.has(key) || !Object.hasOwn(previous?.result ?? {}, key)
|
|
1139
|
+
);
|
|
1140
|
+
readingKeys = new Set(requested);
|
|
1141
|
+
const started = tick();
|
|
1142
|
+
try {
|
|
1143
|
+
const results = await Promise.all(
|
|
1144
|
+
Array.from(
|
|
1145
|
+
{ length: Math.ceil(requested.length / 200) },
|
|
1146
|
+
async (_, i) => {
|
|
1147
|
+
const batch2 = requested.slice(i * 200, (i + 1) * 200);
|
|
1148
|
+
const response = await read(batch2);
|
|
1149
|
+
for (const key of batch2)
|
|
1150
|
+
if (!Object.hasOwn(response.result, key))
|
|
1151
|
+
throw new Error(`Keyed read omitted key ${key}`);
|
|
1152
|
+
return response;
|
|
1153
|
+
}
|
|
1154
|
+
)
|
|
1155
|
+
);
|
|
1156
|
+
const retained = (key) => !all && !dirty.has(key) && !readingKeys.has(key);
|
|
1157
|
+
for (const key of requested) startedAt.set(key, started);
|
|
1158
|
+
previous = {
|
|
1159
|
+
result: Object.fromEntries([
|
|
1160
|
+
...Object.entries(previous?.result ?? {}).filter(
|
|
1161
|
+
([key]) => retained(key)
|
|
1162
|
+
),
|
|
1163
|
+
...results.flatMap((response) => Object.entries(response.result))
|
|
1164
|
+
]),
|
|
1165
|
+
tags: [
|
|
1166
|
+
.../* @__PURE__ */ new Set([
|
|
1167
|
+
...all ? [] : previous?.tags ?? [],
|
|
1168
|
+
...results.flatMap((r) => r.tags)
|
|
1169
|
+
])
|
|
1170
|
+
],
|
|
1171
|
+
keyTags: Object.fromEntries([
|
|
1172
|
+
...Object.entries(previous?.keyTags ?? {}).filter(
|
|
1173
|
+
([key]) => retained(key)
|
|
1174
|
+
),
|
|
1175
|
+
...results.flatMap(
|
|
1176
|
+
(response) => Object.entries(response.keyTags)
|
|
1177
|
+
)
|
|
1178
|
+
])
|
|
1179
|
+
};
|
|
1180
|
+
return previous;
|
|
1181
|
+
} catch (error) {
|
|
1182
|
+
for (const key of refreshedKeys) dirtyKeys.add(key);
|
|
1183
|
+
refreshAll ||= refreshedAll;
|
|
1184
|
+
throw error;
|
|
1185
|
+
}
|
|
1186
|
+
}).then((data) => {
|
|
1187
|
+
recordKeyedRead(client, queryKey, startedAt);
|
|
1188
|
+
return data;
|
|
1189
|
+
});
|
|
1190
|
+
}
|
|
1191
|
+
});
|
|
1192
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
1193
|
+
let stop;
|
|
1194
|
+
return {
|
|
1195
|
+
observer,
|
|
1196
|
+
subscribe(requested, listener) {
|
|
1197
|
+
let added = false;
|
|
1198
|
+
for (const key of requested) {
|
|
1199
|
+
if (!keys.has(key)) added = true;
|
|
1200
|
+
keys.set(key, (keys.get(key) ?? 0) + 1);
|
|
1201
|
+
}
|
|
1202
|
+
const cached = getTaggedReadData(client, queryKey);
|
|
1203
|
+
const missing = requested.filter(
|
|
1204
|
+
(key) => !Object.hasOwn(cached?.result ?? {}, key)
|
|
1205
|
+
);
|
|
1206
|
+
if (!stop) missingOnly = cached === void 0;
|
|
1207
|
+
listeners.add(listener);
|
|
1208
|
+
if (!stop) {
|
|
1209
|
+
stop = observer.subscribe(() => {
|
|
1210
|
+
for (const notify of listeners) notify();
|
|
1211
|
+
});
|
|
1212
|
+
}
|
|
1213
|
+
if (added && missing.length > 0) {
|
|
1214
|
+
if (observer.getCurrentResult().isFetching) {
|
|
1215
|
+
if (readingKeys.size > 0 && missing.some((key) => !readingKeys.has(key)))
|
|
1216
|
+
restartTaggedRead(observer.getCurrentQuery());
|
|
1217
|
+
} else {
|
|
1218
|
+
missingOnly = true;
|
|
1219
|
+
void observer.refetch({ cancelRefetch: false });
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
return () => {
|
|
1223
|
+
listeners.delete(listener);
|
|
1224
|
+
for (const key of requested) {
|
|
1225
|
+
const count = (keys.get(key) ?? 1) - 1;
|
|
1226
|
+
if (count > 0) keys.set(key, count);
|
|
1227
|
+
else keys.delete(key);
|
|
1228
|
+
}
|
|
1229
|
+
queueMicrotask(() => {
|
|
1230
|
+
if (listeners.size === 0) {
|
|
1231
|
+
stop?.();
|
|
1232
|
+
stop = void 0;
|
|
1233
|
+
}
|
|
1234
|
+
});
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
function useQuerySelection(subscribe, getSnapshot, select) {
|
|
1240
|
+
const committed = useRef(null);
|
|
1241
|
+
const getSelection = useMemo(() => {
|
|
1242
|
+
let cached;
|
|
1243
|
+
return () => {
|
|
1244
|
+
const snapshot = getSnapshot();
|
|
1245
|
+
if (cached && Object.is(cached.snapshot, snapshot)) return cached.value;
|
|
1246
|
+
cached = {
|
|
1247
|
+
snapshot,
|
|
1248
|
+
value: replaceEqualDeep3(
|
|
1249
|
+
cached?.value ?? committed.current?.value,
|
|
1250
|
+
select(snapshot)
|
|
1251
|
+
)
|
|
1252
|
+
};
|
|
1253
|
+
return cached.value;
|
|
1254
|
+
};
|
|
1255
|
+
}, [getSnapshot, select]);
|
|
1256
|
+
const value = useSyncExternalStore(subscribe, getSelection, getSelection);
|
|
1257
|
+
useEffect(() => {
|
|
1258
|
+
committed.current = { value };
|
|
1259
|
+
}, [value]);
|
|
1260
|
+
return value;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
// ../domain/src/json-value.ts
|
|
1264
|
+
import { z } from "zod";
|
|
1265
|
+
var jsonValueSchema = z.lazy(
|
|
1266
|
+
() => z.union([
|
|
1267
|
+
z.string(),
|
|
1268
|
+
z.number(),
|
|
1269
|
+
z.boolean(),
|
|
1270
|
+
z.null(),
|
|
1271
|
+
z.array(jsonValueSchema),
|
|
1272
|
+
z.record(z.string(), jsonValueSchema)
|
|
1273
|
+
])
|
|
1274
|
+
);
|
|
1275
|
+
var jsonObjectSchema = z.record(
|
|
1276
|
+
z.string(),
|
|
1277
|
+
jsonValueSchema
|
|
1278
|
+
);
|
|
1279
|
+
|
|
1280
|
+
// src/internal/rpc-tags.ts
|
|
1281
|
+
import { z as z2 } from "zod";
|
|
1282
|
+
var rpcInvalidationTags = z2.array(z2.string().min(1)).min(1);
|
|
1283
|
+
function rpcResponseTags(declarations, input, output) {
|
|
1284
|
+
const tags = z2.array(z2.string().min(1)).parse(declarations.tags?.(input, output) ?? []);
|
|
1285
|
+
const keyTags = {};
|
|
1286
|
+
if (declarations.keyTags && typeof output === "object" && output !== null && !Array.isArray(output)) {
|
|
1287
|
+
for (const [key, value] of Object.entries(output)) {
|
|
1288
|
+
keyTags[key] = z2.array(z2.string().min(1)).parse(declarations.keyTags(key, value));
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
const invalidated = z2.array(z2.string().min(1)).parse(declarations.invalidates?.(input, output) ?? []);
|
|
1292
|
+
return { tags, keyTags, invalidated };
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1295
|
+
// src/internal/rpc-query-host.ts
|
|
1296
|
+
import { z as z3 } from "zod";
|
|
1297
|
+
var rpcQueryKey = (pluginId, method, input) => [
|
|
1298
|
+
"plugin-rpc",
|
|
1299
|
+
pluginId,
|
|
1300
|
+
method,
|
|
1301
|
+
input
|
|
1302
|
+
];
|
|
1303
|
+
var keyedQueryKey = (pluginId, method) => rpcQueryKey(pluginId, method, { keyed: true });
|
|
1304
|
+
var keyedCollections = /* @__PURE__ */ new Map();
|
|
1305
|
+
function keyedCollection(pluginId, method) {
|
|
1306
|
+
const name = JSON.stringify([pluginId, method]);
|
|
1307
|
+
let collection = keyedCollections.get(name);
|
|
1308
|
+
if (!collection) {
|
|
1309
|
+
collection = new KeyedCollection(name);
|
|
1310
|
+
keyedCollections.set(name, collection);
|
|
1311
|
+
}
|
|
1312
|
+
return collection;
|
|
1313
|
+
}
|
|
1314
|
+
function parsedUpdate(update) {
|
|
1315
|
+
return (current) => jsonValueSchema.parse(update(current));
|
|
1316
|
+
}
|
|
1317
|
+
function optimisticCache(pluginId, updates) {
|
|
1318
|
+
return {
|
|
1319
|
+
update(method, input, update) {
|
|
1320
|
+
updates.push(
|
|
1321
|
+
optimisticQueryUpdate(
|
|
1322
|
+
rpcQueryKey(pluginId, method, jsonValueSchema.parse(input ?? null)),
|
|
1323
|
+
parsedUpdate(update),
|
|
1324
|
+
["result"]
|
|
1325
|
+
)
|
|
1326
|
+
);
|
|
1327
|
+
},
|
|
1328
|
+
updateKey(method, key, update) {
|
|
1329
|
+
updates.push(
|
|
1330
|
+
optimisticKeyedUpdate(
|
|
1331
|
+
keyedCollection(pluginId, method),
|
|
1332
|
+
key,
|
|
1333
|
+
parsedUpdate(update)
|
|
1334
|
+
)
|
|
1335
|
+
);
|
|
1336
|
+
}
|
|
1337
|
+
};
|
|
1338
|
+
}
|
|
1339
|
+
async function callRpc(host, pluginId, contract, method, input) {
|
|
1340
|
+
let raw;
|
|
1341
|
+
try {
|
|
1342
|
+
raw = await host.call(pluginId, method, input);
|
|
1343
|
+
} catch (error) {
|
|
1344
|
+
throw experimental_PluginRpcCallError.from(error);
|
|
1345
|
+
}
|
|
1346
|
+
const result = jsonValueSchema.safeParse(raw);
|
|
1347
|
+
if (!result.success)
|
|
1348
|
+
throw new experimental_PluginRpcCallError({
|
|
1349
|
+
code: "invalid_response",
|
|
1350
|
+
message: `Invalid RPC response for ${method}`
|
|
1351
|
+
});
|
|
1352
|
+
const methodContract = contract[method];
|
|
1353
|
+
if (methodContract === void 0)
|
|
1354
|
+
throw new experimental_PluginRpcCallError({
|
|
1355
|
+
code: "unknown_method",
|
|
1356
|
+
message: `rpc method "${method}" isn't in the contract`
|
|
1357
|
+
});
|
|
1358
|
+
const parsedInput = await methodContract.input["~standard"].validate(input);
|
|
1359
|
+
if (parsedInput.issues !== void 0)
|
|
1360
|
+
throw new experimental_PluginRpcCallError({
|
|
1361
|
+
code: "invalid_input",
|
|
1362
|
+
message: `rpc input validation failed for ${method}`
|
|
1363
|
+
});
|
|
1364
|
+
return {
|
|
1365
|
+
result: result.data,
|
|
1366
|
+
...rpcResponseTags(methodContract, parsedInput.value, result.data)
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
1369
|
+
var tagsOf = (data) => [
|
|
1370
|
+
...data.tags,
|
|
1371
|
+
...Object.values(data.keyTags).flat()
|
|
1372
|
+
];
|
|
1373
|
+
var owners = /* @__PURE__ */ new WeakMap();
|
|
1374
|
+
function createRpcQueryHooks(useHost) {
|
|
1375
|
+
function useSubscription(host, pluginId, enabled) {
|
|
1376
|
+
useEffect2(
|
|
1377
|
+
() => enabled ? host.subscribe(pluginId) : void 0,
|
|
1378
|
+
[host, pluginId, enabled]
|
|
1379
|
+
);
|
|
1380
|
+
}
|
|
1381
|
+
const experimental_useRpcQuery = (options) => {
|
|
1382
|
+
const host = useHost();
|
|
1383
|
+
const pluginId = options.pluginId ?? host.pluginId;
|
|
1384
|
+
const input = jsonValueSchema.parse(options.input ?? null);
|
|
1385
|
+
const queryKey = rpcQueryKey(pluginId, options.method, input);
|
|
1386
|
+
useSubscription(host, pluginId, options.enabled ?? true);
|
|
1387
|
+
const query = useTaggedQuery(
|
|
1388
|
+
{
|
|
1389
|
+
queryKey,
|
|
1390
|
+
enabled: options.enabled,
|
|
1391
|
+
...taggedQueryOptions(host.queryClient, queryKey, {
|
|
1392
|
+
scope: pluginTagScope(pluginId),
|
|
1393
|
+
tagsOf
|
|
1394
|
+
}),
|
|
1395
|
+
queryFn: () => runTaggedRead(
|
|
1396
|
+
host.queryClient,
|
|
1397
|
+
queryKey,
|
|
1398
|
+
async () => callRpc(
|
|
1399
|
+
host,
|
|
1400
|
+
pluginId,
|
|
1401
|
+
options.contract,
|
|
1402
|
+
options.method,
|
|
1403
|
+
input
|
|
1404
|
+
)
|
|
1405
|
+
)
|
|
1406
|
+
},
|
|
1407
|
+
host.queryClient
|
|
1408
|
+
);
|
|
1409
|
+
return {
|
|
1410
|
+
data: query.data?.result,
|
|
1411
|
+
error: query.error === null ? null : experimental_PluginRpcCallError.from(
|
|
1412
|
+
query.error,
|
|
1413
|
+
"invalid_response"
|
|
1414
|
+
),
|
|
1415
|
+
isLoading: (options.enabled ?? true) && query.isLoading,
|
|
1416
|
+
isFetching: query.isFetching,
|
|
1417
|
+
refetch: async () => {
|
|
1418
|
+
await query.refetch();
|
|
1419
|
+
}
|
|
1420
|
+
};
|
|
1421
|
+
};
|
|
1422
|
+
function experimental_useRpcKeyedQuery(options) {
|
|
1423
|
+
const host = useHost();
|
|
1424
|
+
const pluginId = options.pluginId ?? host.pluginId;
|
|
1425
|
+
const enabled = options.enabled ?? true;
|
|
1426
|
+
const identity = JSON.stringify([...new Set(options.keys)].sort());
|
|
1427
|
+
const keys = useMemo2(
|
|
1428
|
+
() => z3.array(z3.string()).parse(JSON.parse(identity)),
|
|
1429
|
+
[identity]
|
|
1430
|
+
);
|
|
1431
|
+
let cache = owners.get(host.queryClient);
|
|
1432
|
+
if (!cache) {
|
|
1433
|
+
cache = /* @__PURE__ */ new Map();
|
|
1434
|
+
owners.set(host.queryClient, cache);
|
|
1435
|
+
}
|
|
1436
|
+
const id = JSON.stringify([pluginId, options.method]);
|
|
1437
|
+
let owner = cache.get(id);
|
|
1438
|
+
if (!owner) {
|
|
1439
|
+
owner = createTaggedKeyedQueryOwner({
|
|
1440
|
+
client: host.queryClient,
|
|
1441
|
+
queryKey: keyedQueryKey(pluginId, options.method),
|
|
1442
|
+
scope: pluginTagScope(pluginId),
|
|
1443
|
+
collection: keyedCollection(pluginId, options.method),
|
|
1444
|
+
read: async (keys2) => {
|
|
1445
|
+
const response = await callRpc(
|
|
1446
|
+
host,
|
|
1447
|
+
pluginId,
|
|
1448
|
+
options.contract,
|
|
1449
|
+
options.method,
|
|
1450
|
+
{ keys: [...keys2] }
|
|
1451
|
+
);
|
|
1452
|
+
return {
|
|
1453
|
+
...response,
|
|
1454
|
+
result: z3.record(z3.string(), jsonValueSchema).parse(response.result)
|
|
1455
|
+
};
|
|
1456
|
+
}
|
|
1457
|
+
});
|
|
1458
|
+
cache.set(id, owner);
|
|
1459
|
+
}
|
|
1460
|
+
const current = owner;
|
|
1461
|
+
useSubscription(host, pluginId, enabled && keys.length > 0);
|
|
1462
|
+
const subscribe = useCallback2(
|
|
1463
|
+
(listener) => enabled && keys.length > 0 ? current.subscribe(keys, listener) : () => {
|
|
1464
|
+
},
|
|
1465
|
+
[current, keys, enabled]
|
|
1466
|
+
);
|
|
1467
|
+
const getSnapshot = useCallback2(
|
|
1468
|
+
() => current.observer.getCurrentResult(),
|
|
1469
|
+
[current]
|
|
1470
|
+
);
|
|
1471
|
+
const { select: selectRows } = options;
|
|
1472
|
+
const select = useCallback2(
|
|
1473
|
+
(query2) => {
|
|
1474
|
+
const rows = query2.data?.result ?? {};
|
|
1475
|
+
const data = Object.fromEntries(
|
|
1476
|
+
keys.filter((key) => Object.hasOwn(rows, key)).map((key) => [key, rows[key]])
|
|
1477
|
+
);
|
|
1478
|
+
return {
|
|
1479
|
+
data: selectRows ? selectRows(data) : data,
|
|
1480
|
+
error: query2.error === null ? null : experimental_PluginRpcCallError.from(
|
|
1481
|
+
query2.error,
|
|
1482
|
+
"invalid_response"
|
|
1483
|
+
),
|
|
1484
|
+
isLoading: enabled && keys.some((key) => !Object.hasOwn(rows, key)) && query2.isFetching,
|
|
1485
|
+
isFetching: query2.isFetching
|
|
1486
|
+
};
|
|
1487
|
+
},
|
|
1488
|
+
[keys, enabled, selectRows]
|
|
1489
|
+
);
|
|
1490
|
+
const query = useQuerySelection(subscribe, getSnapshot, select);
|
|
1491
|
+
const refetch = useCallback2(async () => {
|
|
1492
|
+
await current.observer.refetch();
|
|
1493
|
+
}, [current]);
|
|
1494
|
+
return {
|
|
1495
|
+
...query,
|
|
1496
|
+
refetch
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
function experimental_useRpcMutation(options) {
|
|
1500
|
+
const host = useHost();
|
|
1501
|
+
const pluginId = options.pluginId ?? host.pluginId;
|
|
1502
|
+
const mutation = useTaggedMutation({
|
|
1503
|
+
client: host.queryClient,
|
|
1504
|
+
invalidate: (tags) => invalidateTags(host.queryClient, pluginTagScope(pluginId), tags),
|
|
1505
|
+
call: async (input) => {
|
|
1506
|
+
const response = await callRpc(
|
|
1507
|
+
host,
|
|
1508
|
+
pluginId,
|
|
1509
|
+
options.contract,
|
|
1510
|
+
options.method,
|
|
1511
|
+
jsonValueSchema.parse(input)
|
|
1512
|
+
);
|
|
1513
|
+
return {
|
|
1514
|
+
...response,
|
|
1515
|
+
result: response.result
|
|
1516
|
+
};
|
|
1517
|
+
},
|
|
1518
|
+
optimistic: (input) => {
|
|
1519
|
+
const updates = [];
|
|
1520
|
+
options.optimistic?.(
|
|
1521
|
+
input,
|
|
1522
|
+
optimisticCache(pluginId, updates)
|
|
1523
|
+
);
|
|
1524
|
+
return updates;
|
|
1525
|
+
}
|
|
1526
|
+
});
|
|
1527
|
+
const { mutate } = mutation;
|
|
1528
|
+
return {
|
|
1529
|
+
...mutation,
|
|
1530
|
+
error: mutation.error === null ? null : experimental_PluginRpcCallError.from(
|
|
1531
|
+
mutation.error,
|
|
1532
|
+
"invalid_input"
|
|
1533
|
+
),
|
|
1534
|
+
mutate: useCallback2(
|
|
1535
|
+
async (...args) => {
|
|
1536
|
+
try {
|
|
1537
|
+
return await mutate(
|
|
1538
|
+
args[0] ?? null
|
|
1539
|
+
);
|
|
1540
|
+
} catch (error) {
|
|
1541
|
+
throw experimental_PluginRpcCallError.from(error);
|
|
1542
|
+
}
|
|
1543
|
+
},
|
|
1544
|
+
[mutate]
|
|
1545
|
+
)
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
function experimental_useRpcRefresh() {
|
|
1549
|
+
const host = useHost();
|
|
1550
|
+
const isRefreshing = useIsFetching(
|
|
1551
|
+
{ queryKey: ["plugin-rpc", host.pluginId] },
|
|
1552
|
+
host.queryClient
|
|
1553
|
+
) > 0;
|
|
1554
|
+
return {
|
|
1555
|
+
isRefreshing,
|
|
1556
|
+
refresh: () => {
|
|
1557
|
+
void invalidateTags(
|
|
1558
|
+
host.queryClient,
|
|
1559
|
+
pluginTagScope(host.pluginId),
|
|
1560
|
+
null
|
|
1561
|
+
);
|
|
1562
|
+
}
|
|
1563
|
+
};
|
|
1564
|
+
}
|
|
1565
|
+
return {
|
|
1566
|
+
experimental_useRpcQuery,
|
|
1567
|
+
experimental_useRpcKeyedQuery,
|
|
1568
|
+
experimental_useRpcMutation,
|
|
1569
|
+
experimental_useRpcRefresh
|
|
1570
|
+
};
|
|
1571
|
+
}
|
|
1572
|
+
export {
|
|
1573
|
+
createRpcQueryHooks
|
|
1574
|
+
};
|