@get-bb/plugin-sdk 0.6.59 → 0.6.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,954 @@
1
- // src/testing/app.tsx
2
- import * as React from "react";
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
+ // ../query-tags/src/index.ts
3
83
  import {
4
- createContext,
5
84
  useCallback,
6
- useContext,
7
- useLayoutEffect,
8
85
  useEffect,
9
86
  useMemo,
10
87
  useRef,
11
88
  useState,
12
89
  useSyncExternalStore
13
90
  } from "react";
91
+ import {
92
+ QueryObserver,
93
+ useQuery,
94
+ useQueryClient,
95
+ useMutation,
96
+ useMutationState,
97
+ replaceEqualDeep as replaceEqualDeep2
98
+ } from "@tanstack/react-query";
99
+
100
+ // ../query-tags/src/optimistic.ts
101
+ import {
102
+ notifyManager,
103
+ replaceEqualDeep
104
+ } from "@tanstack/react-query";
105
+ function optimisticQueryUpdate(queryKey, update, path = []) {
106
+ return {
107
+ queryKey,
108
+ path: [...path],
109
+ update: (current) => update(current)
110
+ };
111
+ }
112
+ var predictions = /* @__PURE__ */ new WeakMap();
113
+ var receipts = /* @__PURE__ */ new WeakMap();
114
+ var order = 0;
115
+ function valueAt(data, path) {
116
+ let value = data;
117
+ for (const key of path) {
118
+ if (typeof value !== "object" || value === null || !Object.hasOwn(value, key))
119
+ return;
120
+ value = Reflect.get(value, key);
121
+ }
122
+ return value === void 0 ? void 0 : { value };
123
+ }
124
+ function replaceAt(data, path, value) {
125
+ const [key, ...rest] = path;
126
+ if (key === void 0) return value;
127
+ if (typeof data !== "object" || data === null) return data;
128
+ const next = Array.isArray(data) ? [...data] : { ...data };
129
+ Reflect.set(next, key, replaceAt(Reflect.get(data, key), rest, value));
130
+ return next;
131
+ }
132
+ function prefix(left, right) {
133
+ return left.length <= right.length && left.every((part, index) => part === right[index]);
134
+ }
135
+ function olderPending(state, layer) {
136
+ return state.layers.some(
137
+ (other) => other.order < layer.order && !other.settled && (prefix(other.path, layer.path) || prefix(layer.path, other.path))
138
+ );
139
+ }
140
+ function confirmedValue(current, predicted, confirmed) {
141
+ if (Object.is(predicted, confirmed)) return current;
142
+ 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))
143
+ return confirmed;
144
+ const next = Array.isArray(current) ? [...current] : { ...current };
145
+ for (const key of /* @__PURE__ */ new Set([
146
+ ...Object.keys(predicted),
147
+ ...Object.keys(confirmed)
148
+ ])) {
149
+ if (!Object.hasOwn(confirmed, key)) Reflect.deleteProperty(next, key);
150
+ else
151
+ Reflect.set(
152
+ next,
153
+ key,
154
+ confirmedValue(
155
+ Reflect.get(current, key),
156
+ Reflect.get(predicted, key),
157
+ Reflect.get(confirmed, key)
158
+ )
159
+ );
160
+ }
161
+ return next;
162
+ }
163
+ function projected(state) {
164
+ return state.layers.reduce((data, layer) => {
165
+ const current = valueAt(data, layer.path);
166
+ return replaceAt(
167
+ data,
168
+ layer.path,
169
+ layer.update(current === void 0 ? layer.initial : current.value)
170
+ );
171
+ }, state.base);
172
+ }
173
+ var predictionListeners = /* @__PURE__ */ new WeakMap();
174
+ function subscribeOptimisticQuery(query, listener) {
175
+ if (query === void 0) return () => {
176
+ };
177
+ let listeners = predictionListeners.get(query);
178
+ if (listeners === void 0) {
179
+ listeners = /* @__PURE__ */ new Set();
180
+ predictionListeners.set(query, listeners);
181
+ }
182
+ listeners.add(listener);
183
+ return () => {
184
+ listeners.delete(listener);
185
+ if (listeners.size === 0) predictionListeners.delete(query);
186
+ };
187
+ }
188
+ function publish(query, state) {
189
+ query.setState({
190
+ data: replaceEqualDeep(query.state.data, projected(state))
191
+ });
192
+ if (state.layers.length === 0) predictions.delete(query);
193
+ for (const listener of predictionListeners.get(query) ?? []) listener();
194
+ }
195
+ function taggedReadReceipt(query) {
196
+ const paths = [];
197
+ return {
198
+ start: () => ++order,
199
+ record(started, loaded) {
200
+ paths.push(...loaded.map((path) => ({ path, started })));
201
+ },
202
+ commit(data) {
203
+ receipts.set(query, { data, paths });
204
+ }
205
+ };
206
+ }
207
+ function taggedStructuralSharing(client, queryKey, previous, next) {
208
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
209
+ const state = query === void 0 ? void 0 : predictions.get(query);
210
+ if (query !== void 0) {
211
+ const receipt = receipts.get(query);
212
+ if (receipt !== void 0 && Object.is(receipt.data, next)) {
213
+ receipts.delete(query);
214
+ if (state !== void 0) {
215
+ const refreshed = /* @__PURE__ */ new Set();
216
+ for (const layer of state.layers) {
217
+ if (layer.acceptedAt !== null && receipt.paths.some(
218
+ ({ path, started }) => started > layer.acceptedAt && prefix(path, layer.path)
219
+ )) {
220
+ layer.fresh = true;
221
+ refreshed.add(layer);
222
+ }
223
+ }
224
+ state.layers = state.layers.filter(
225
+ (layer) => !layer.settled || !refreshed.has(layer) || olderPending(state, layer)
226
+ );
227
+ }
228
+ }
229
+ if (state !== void 0) {
230
+ state.base = next;
231
+ next = projected(state);
232
+ if (state.layers.length === 0) predictions.delete(query);
233
+ }
234
+ }
235
+ const sharing = client.defaultQueryOptions({ queryKey }).structuralSharing;
236
+ return sharing === false ? next : typeof sharing === "function" ? sharing(previous, next) : replaceEqualDeep(previous, next);
237
+ }
238
+ function getTaggedReadData(client, queryKey) {
239
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
240
+ const state = query === void 0 ? void 0 : predictions.get(query);
241
+ return state === void 0 ? query?.state.data : state.base;
242
+ }
243
+ function beginOptimisticMutation(client, updates) {
244
+ const owner = {};
245
+ const mutationOrder = ++order;
246
+ let accepted = false;
247
+ const affected = /* @__PURE__ */ new Map();
248
+ const rollback = () => notifyManager.batch(() => {
249
+ if (accepted) return;
250
+ for (const [query, state] of affected) {
251
+ state.layers = state.layers.filter((layer) => layer.owner !== owner);
252
+ publish(query, state);
253
+ }
254
+ });
255
+ try {
256
+ notifyManager.batch(() => {
257
+ for (const update of updates) {
258
+ const query = client.getQueryCache().get(
259
+ client.defaultQueryOptions({ queryKey: update.queryKey }).queryHash
260
+ );
261
+ if (query === void 0 || query.state.data === void 0) continue;
262
+ const state = predictions.get(query) ?? {
263
+ base: query.state.data,
264
+ layers: []
265
+ };
266
+ const current = valueAt(projected(state), update.path);
267
+ if (current === void 0) continue;
268
+ state.layers.push({
269
+ owner,
270
+ order: mutationOrder,
271
+ path: update.path,
272
+ initial: current.value,
273
+ update: update.update,
274
+ acceptedAt: null,
275
+ fresh: false,
276
+ settled: false
277
+ });
278
+ predictions.set(query, state);
279
+ affected.set(query, state);
280
+ publish(query, state);
281
+ }
282
+ });
283
+ } catch (error) {
284
+ rollback();
285
+ throw error;
286
+ }
287
+ return {
288
+ rollback,
289
+ accept() {
290
+ accepted = true;
291
+ const acceptedAt = ++order;
292
+ for (const state of affected.values())
293
+ for (const layer of state.layers)
294
+ if (layer.owner === owner) layer.acceptedAt = acceptedAt;
295
+ },
296
+ settle() {
297
+ notifyManager.batch(() => {
298
+ for (const [query, state] of affected) {
299
+ state.layers = state.layers.filter((layer) => {
300
+ if (layer.owner !== owner) return true;
301
+ layer.settled = true;
302
+ if (!layer.fresh) return true;
303
+ if (!olderPending(state, layer)) return false;
304
+ const current = valueAt(state.base, layer.path);
305
+ if (current !== void 0) {
306
+ const update = layer.update;
307
+ const predicted = update(current.value);
308
+ layer.update = (value) => confirmedValue(update(value), predicted, current.value);
309
+ }
310
+ return true;
311
+ });
312
+ publish(query, state);
313
+ }
314
+ });
315
+ }
316
+ };
317
+ }
318
+
319
+ // ../query-tags/src/index.ts
320
+ function useTaggedQuery(options, client) {
321
+ const queryClient = useQueryClient(client);
322
+ const result = useQuery(options, queryClient);
323
+ const query = queryClient.getQueryCache().get(queryClient.defaultQueryOptions(options).queryHash);
324
+ const subscribed = options.subscribed !== false;
325
+ const subscribe = useCallback(
326
+ (listener) => subscribed ? subscribeOptimisticQuery(query, listener) : () => {
327
+ },
328
+ [query, subscribed]
329
+ );
330
+ const snapshot = useCallback(() => query?.state.data, [query]);
331
+ useSyncExternalStore(subscribe, snapshot, snapshot);
332
+ return result;
333
+ }
334
+ var registrations = /* @__PURE__ */ new WeakMap();
335
+ var reads = /* @__PURE__ */ new WeakMap();
336
+ function taggedQueryOptions(client, queryKey, registration) {
337
+ const meta = {};
338
+ registrations.set(meta, {
339
+ scope: registration.scope,
340
+ tagsOf: (data) => registration.tagsOf(data),
341
+ onInvalidate: (data, tags) => registration.onInvalidate?.(data, tags)
342
+ });
343
+ return {
344
+ meta,
345
+ structuralSharing: (previous, next) => taggedStructuralSharing(client, queryKey, previous, next)
346
+ };
347
+ }
348
+ function registrationOf(query) {
349
+ return query.meta === void 0 ? void 0 : registrations.get(query.meta);
350
+ }
351
+ async function runTaggedRead(client, queryKey, read, paths = () => [[]]) {
352
+ const query = client.getQueryCache().get(client.defaultQueryOptions({ queryKey }).queryHash);
353
+ if (query === void 0) return read();
354
+ const registration = registrationOf(query);
355
+ const receipt = taggedReadReceipt(query);
356
+ for (; ; ) {
357
+ const pending = { tags: /* @__PURE__ */ new Set(), restart: false };
358
+ reads.set(query, pending);
359
+ const started = receipt.start();
360
+ try {
361
+ const result = await read();
362
+ receipt.record(started, paths());
363
+ const overlap = registration?.tagsOf(result).some((tag) => pending.tags.has(tag));
364
+ if (overlap) registration?.onInvalidate?.(result, [...pending.tags]);
365
+ if (pending.restart || overlap) continue;
366
+ receipt.commit(result);
367
+ return result;
368
+ } catch (error) {
369
+ if (pending.restart) continue;
370
+ throw error;
371
+ } finally {
372
+ if (reads.get(query) === pending) reads.delete(query);
373
+ }
374
+ }
375
+ }
376
+ async function invalidateTags(client, scope, tags) {
377
+ if (tags?.length === 0) return;
378
+ const matched = /* @__PURE__ */ new Set();
379
+ const pendingReads = [];
380
+ for (const query of client.getQueryCache().getAll()) {
381
+ const registration = registrationOf(query);
382
+ if (registration?.scope !== scope) continue;
383
+ const pending = reads.get(query);
384
+ const data = getTaggedReadData(client, query.queryKey);
385
+ const matches = tags === null || data === void 0 && pending === void 0 || data !== void 0 && registration.tagsOf(data).some((tag) => tags.includes(tag));
386
+ if (matches) registration.onInvalidate?.(data, tags);
387
+ if (pending !== void 0) {
388
+ if (matches) pending.restart = true;
389
+ else for (const tag of tags ?? []) pending.tags.add(tag);
390
+ if (query.isActive() && query.promise !== void 0)
391
+ pendingReads.push(query.promise);
392
+ }
393
+ if (matches) {
394
+ matched.add(query);
395
+ if (pending === void 0 && query.isActive() && query.state.fetchStatus === "fetching" && query.promise !== void 0) {
396
+ const refetch = () => client.invalidateQueries(
397
+ { predicate: (candidate) => candidate === query },
398
+ { cancelRefetch: false }
399
+ );
400
+ pendingReads.push(query.promise.then(refetch, refetch));
401
+ }
402
+ }
403
+ }
404
+ await Promise.allSettled([
405
+ client.invalidateQueries(
406
+ { predicate: (query) => matched.has(query) },
407
+ { cancelRefetch: false }
408
+ ),
409
+ ...pendingReads
410
+ ]);
411
+ }
412
+ async function executeTaggedMutation(invalidate, call, prediction) {
413
+ const { result, invalidated } = await call();
414
+ prediction?.accept();
415
+ const refresh = async () => {
416
+ try {
417
+ if (invalidated.length > 0) await invalidate(invalidated);
418
+ } finally {
419
+ prediction?.settle();
420
+ }
421
+ };
422
+ void refresh().catch(() => {
423
+ });
424
+ return result;
425
+ }
426
+ var pluginTagScope = (pluginId) => `plugin:${pluginId}`;
427
+ function restartTaggedRead(query) {
428
+ const pending = reads.get(query);
429
+ if (pending) pending.restart = true;
430
+ }
431
+ function useTaggedMutation(client, invalidate, call, optimistic) {
432
+ const [owner] = useState(() => ({}));
433
+ const predict = useRef(optimistic);
434
+ useEffect(() => {
435
+ predict.current = optimistic;
436
+ }, [optimistic]);
437
+ const mutation = useMutation(
438
+ {
439
+ meta: { taggedMutationOwner: owner },
440
+ mutationFn: ({ input, prediction }) => executeTaggedMutation(invalidate, () => call(input), prediction)
441
+ },
442
+ client
443
+ );
444
+ const pendingInputs = useMutationState(
445
+ {
446
+ filters: {
447
+ status: "pending",
448
+ predicate: (entry) => entry.options.meta?.taggedMutationOwner === owner
449
+ },
450
+ select: (entry) => entry.state.variables.input
451
+ },
452
+ client
453
+ );
454
+ const { mutateAsync } = mutation;
455
+ const mutate = useCallback(
456
+ (input) => {
457
+ const prediction = beginOptimisticMutation(
458
+ client,
459
+ predict.current?.(input) ?? []
460
+ );
461
+ return mutateAsync({ input, prediction }).catch((error) => {
462
+ prediction.rollback();
463
+ throw error;
464
+ });
465
+ },
466
+ [client, mutateAsync]
467
+ );
468
+ return {
469
+ mutate,
470
+ pendingInputs,
471
+ isPending: pendingInputs.length > 0,
472
+ error: mutation.error,
473
+ reset: mutation.reset
474
+ };
475
+ }
476
+ function createTaggedKeyedQueryOwner(options) {
477
+ const { client, queryKey, scope, read } = options;
478
+ const keys = /* @__PURE__ */ new Map();
479
+ let readingKeys = /* @__PURE__ */ new Set();
480
+ let missingOnly = false;
481
+ let refreshAll = false;
482
+ const dirtyKeys = /* @__PURE__ */ new Set();
483
+ const collectSubscribedKeys = () => new Promise((resolve) => {
484
+ queueMicrotask(() => resolve([...keys.keys()]));
485
+ });
486
+ const observer = new QueryObserver(client, {
487
+ queryKey,
488
+ ...taggedQueryOptions(client, queryKey, {
489
+ scope,
490
+ tagsOf: (data) => [
491
+ ...data.tags,
492
+ ...Object.values(data.keyTags).flat()
493
+ ],
494
+ onInvalidate: (data, tags) => {
495
+ if (tags === null || data === void 0 || data.tags.some((tag) => tags.includes(tag))) {
496
+ refreshAll = true;
497
+ } else {
498
+ for (const [key, ownTags] of Object.entries(data.keyTags))
499
+ if (ownTags.some((tag) => tags.includes(tag))) dirtyKeys.add(key);
500
+ }
501
+ }
502
+ }),
503
+ queryFn: () => {
504
+ let previous = getTaggedReadData(client, queryKey);
505
+ let loaded = [];
506
+ let refresh = !missingOnly && dirtyKeys.size === 0;
507
+ missingOnly = false;
508
+ const refreshedKeys = /* @__PURE__ */ new Set();
509
+ let refreshedAll = false;
510
+ return runTaggedRead(
511
+ client,
512
+ queryKey,
513
+ async () => {
514
+ const subscribed = await collectSubscribedKeys();
515
+ const all = refreshAll || refresh;
516
+ refresh = false;
517
+ const dirty = new Set(dirtyKeys);
518
+ for (const key of dirty) refreshedKeys.add(key);
519
+ refreshedAll ||= all;
520
+ dirtyKeys.clear();
521
+ refreshAll = false;
522
+ const requested = subscribed.filter(
523
+ (key) => all || dirty.has(key) || !Object.hasOwn(previous?.result ?? {}, key)
524
+ );
525
+ readingKeys = new Set(requested);
526
+ try {
527
+ const results = await Promise.all(
528
+ Array.from(
529
+ { length: Math.ceil(requested.length / 200) },
530
+ async (_, i) => {
531
+ const batch = requested.slice(i * 200, (i + 1) * 200);
532
+ const response = await read(batch);
533
+ for (const key of batch)
534
+ if (!Object.hasOwn(response.result, key))
535
+ throw new Error(`Keyed read omitted key ${key}`);
536
+ return response;
537
+ }
538
+ )
539
+ );
540
+ const retained = (key) => !all && !dirty.has(key) && !readingKeys.has(key);
541
+ loaded = requested;
542
+ previous = {
543
+ result: Object.fromEntries([
544
+ ...Object.entries(previous?.result ?? {}).filter(
545
+ ([key]) => retained(key)
546
+ ),
547
+ ...results.flatMap(
548
+ (response) => Object.entries(response.result)
549
+ )
550
+ ]),
551
+ tags: [
552
+ .../* @__PURE__ */ new Set([
553
+ ...all ? [] : previous?.tags ?? [],
554
+ ...results.flatMap((r) => r.tags)
555
+ ])
556
+ ],
557
+ keyTags: Object.fromEntries([
558
+ ...Object.entries(previous?.keyTags ?? {}).filter(
559
+ ([key]) => retained(key)
560
+ ),
561
+ ...results.flatMap(
562
+ (response) => Object.entries(response.keyTags)
563
+ )
564
+ ])
565
+ };
566
+ return previous;
567
+ } catch (error) {
568
+ for (const key of refreshedKeys) dirtyKeys.add(key);
569
+ refreshAll ||= refreshedAll;
570
+ throw error;
571
+ }
572
+ },
573
+ () => loaded.map((key) => ["result", key])
574
+ );
575
+ }
576
+ });
577
+ const listeners = /* @__PURE__ */ new Set();
578
+ let stop;
579
+ return {
580
+ observer,
581
+ subscribe(requested, listener) {
582
+ let added = false;
583
+ for (const key of requested) {
584
+ if (!keys.has(key)) added = true;
585
+ keys.set(key, (keys.get(key) ?? 0) + 1);
586
+ }
587
+ const cached = getTaggedReadData(client, queryKey);
588
+ const missing = requested.filter(
589
+ (key) => !Object.hasOwn(cached?.result ?? {}, key)
590
+ );
591
+ if (!stop) missingOnly = cached === void 0;
592
+ listeners.add(listener);
593
+ if (!stop) {
594
+ stop = observer.subscribe(() => {
595
+ for (const notify of listeners) notify();
596
+ });
597
+ }
598
+ if (added && missing.length > 0) {
599
+ if (observer.getCurrentResult().isFetching) {
600
+ if (readingKeys.size > 0 && missing.some((key) => !readingKeys.has(key)))
601
+ restartTaggedRead(observer.getCurrentQuery());
602
+ } else {
603
+ missingOnly = true;
604
+ void observer.refetch({ cancelRefetch: false });
605
+ }
606
+ }
607
+ return () => {
608
+ listeners.delete(listener);
609
+ for (const key of requested) {
610
+ const count = (keys.get(key) ?? 1) - 1;
611
+ if (count > 0) keys.set(key, count);
612
+ else keys.delete(key);
613
+ }
614
+ queueMicrotask(() => {
615
+ if (listeners.size === 0) {
616
+ stop?.();
617
+ stop = void 0;
618
+ }
619
+ });
620
+ };
621
+ }
622
+ };
623
+ }
624
+ function useQuerySelection(subscribe, getSnapshot, select) {
625
+ const committed = useRef(null);
626
+ const getSelection = useMemo(() => {
627
+ let cached;
628
+ return () => {
629
+ const snapshot = getSnapshot();
630
+ if (cached && Object.is(cached.snapshot, snapshot)) return cached.value;
631
+ cached = {
632
+ snapshot,
633
+ value: replaceEqualDeep2(
634
+ cached?.value ?? committed.current?.value,
635
+ select(snapshot)
636
+ )
637
+ };
638
+ return cached.value;
639
+ };
640
+ }, [getSnapshot, select]);
641
+ const value = useSyncExternalStore(subscribe, getSelection, getSelection);
642
+ useEffect(() => {
643
+ committed.current = { value };
644
+ }, [value]);
645
+ return value;
646
+ }
647
+
648
+ // src/testing/app.tsx
649
+ import { QueryClient } from "@tanstack/react-query";
650
+
651
+ // src/internal/rpc-query-host.ts
652
+ import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2 } from "react";
653
+ import { useIsFetching } from "@tanstack/react-query";
654
+
655
+ // ../domain/src/json-value.ts
656
+ import { z } from "zod";
657
+ var jsonValueSchema = z.lazy(
658
+ () => z.union([
659
+ z.string(),
660
+ z.number(),
661
+ z.boolean(),
662
+ z.null(),
663
+ z.array(jsonValueSchema),
664
+ z.record(z.string(), jsonValueSchema)
665
+ ])
666
+ );
667
+ var jsonObjectSchema = z.record(
668
+ z.string(),
669
+ jsonValueSchema
670
+ );
671
+
672
+ // src/internal/rpc-query-host.ts
673
+ import { z as z2 } from "zod";
674
+ var envelopeSchema = z2.object({
675
+ result: jsonValueSchema,
676
+ tags: z2.array(z2.string()).default([]),
677
+ keyTags: z2.record(z2.string(), z2.array(z2.string())).default({}),
678
+ invalidated: z2.array(z2.string()).default([])
679
+ });
680
+ var rpcQueryKey = (pluginId, method, input) => [
681
+ "plugin-rpc",
682
+ pluginId,
683
+ method,
684
+ input
685
+ ];
686
+ var keyedQueryKey = (pluginId, method) => rpcQueryKey(pluginId, method, { keyed: true });
687
+ function optimisticCache(pluginId, updates) {
688
+ const add = (prediction) => {
689
+ updates.push({
690
+ ...prediction,
691
+ update: (current) => jsonValueSchema.parse(prediction.update(current))
692
+ });
693
+ };
694
+ return {
695
+ update(method, input, update) {
696
+ add(
697
+ optimisticQueryUpdate(
698
+ rpcQueryKey(pluginId, method, jsonValueSchema.parse(input ?? null)),
699
+ update,
700
+ ["result"]
701
+ )
702
+ );
703
+ },
704
+ updateKey(method, key, update) {
705
+ add(
706
+ optimisticQueryUpdate(keyedQueryKey(pluginId, method), update, [
707
+ "result",
708
+ key
709
+ ])
710
+ );
711
+ }
712
+ };
713
+ }
714
+ async function callRpcEnvelope(host, pluginId, method, input) {
715
+ let raw;
716
+ try {
717
+ raw = await host.call(pluginId, method, input);
718
+ } catch (error) {
719
+ throw experimental_PluginRpcCallError.from(error);
720
+ }
721
+ const parsed = envelopeSchema.safeParse(raw);
722
+ if (!parsed.success)
723
+ throw new experimental_PluginRpcCallError({
724
+ code: "invalid_response",
725
+ message: `Invalid RPC response for ${method}`
726
+ });
727
+ return parsed.data;
728
+ }
729
+ var tagsOf = (data) => [
730
+ ...data.tags,
731
+ ...Object.values(data.keyTags).flat()
732
+ ];
733
+ var owners = /* @__PURE__ */ new WeakMap();
734
+ function createRpcQueryHooks(useHost) {
735
+ function useSubscription(host, pluginId, enabled) {
736
+ useEffect2(
737
+ () => enabled ? host.subscribe(pluginId) : void 0,
738
+ [host, pluginId, enabled]
739
+ );
740
+ }
741
+ const experimental_useRpcQuery = (options) => {
742
+ const host = useHost();
743
+ const pluginId = options.pluginId ?? host.pluginId;
744
+ const input = jsonValueSchema.parse(options.input ?? null);
745
+ const queryKey = rpcQueryKey(pluginId, options.method, input);
746
+ useSubscription(host, pluginId, options.enabled ?? true);
747
+ const query = useTaggedQuery(
748
+ {
749
+ queryKey,
750
+ enabled: options.enabled,
751
+ ...taggedQueryOptions(host.queryClient, queryKey, {
752
+ scope: pluginTagScope(pluginId),
753
+ tagsOf
754
+ }),
755
+ queryFn: () => runTaggedRead(
756
+ host.queryClient,
757
+ queryKey,
758
+ async () => callRpcEnvelope(host, pluginId, options.method, input)
759
+ )
760
+ },
761
+ host.queryClient
762
+ );
763
+ return {
764
+ data: query.data?.result,
765
+ error: query.error === null ? null : experimental_PluginRpcCallError.from(
766
+ query.error,
767
+ "invalid_response"
768
+ ),
769
+ isLoading: (options.enabled ?? true) && query.isLoading,
770
+ isFetching: query.isFetching,
771
+ refetch: async () => {
772
+ await query.refetch();
773
+ }
774
+ };
775
+ };
776
+ function experimental_useRpcKeyedQuery(options) {
777
+ const host = useHost();
778
+ const pluginId = options.pluginId ?? host.pluginId;
779
+ const enabled = options.enabled ?? true;
780
+ const identity = JSON.stringify([...new Set(options.keys)].sort());
781
+ const keys = useMemo2(
782
+ () => z2.array(z2.string()).parse(JSON.parse(identity)),
783
+ [identity]
784
+ );
785
+ let cache = owners.get(host.queryClient);
786
+ if (!cache) {
787
+ cache = /* @__PURE__ */ new Map();
788
+ owners.set(host.queryClient, cache);
789
+ }
790
+ const id = JSON.stringify([pluginId, options.method]);
791
+ let owner = cache.get(id);
792
+ if (!owner) {
793
+ owner = createTaggedKeyedQueryOwner({
794
+ client: host.queryClient,
795
+ queryKey: keyedQueryKey(pluginId, options.method),
796
+ scope: pluginTagScope(pluginId),
797
+ read: async (keys2) => {
798
+ const response = await callRpcEnvelope(
799
+ host,
800
+ pluginId,
801
+ options.method,
802
+ { keys: [...keys2] }
803
+ );
804
+ return {
805
+ ...response,
806
+ result: z2.record(z2.string(), jsonValueSchema).parse(response.result)
807
+ };
808
+ }
809
+ });
810
+ cache.set(id, owner);
811
+ }
812
+ const current = owner;
813
+ useSubscription(host, pluginId, enabled && keys.length > 0);
814
+ const subscribe = useCallback2(
815
+ (listener) => enabled && keys.length > 0 ? current.subscribe(keys, listener) : () => {
816
+ },
817
+ [current, keys, enabled]
818
+ );
819
+ const getSnapshot = useCallback2(
820
+ () => current.observer.getCurrentResult(),
821
+ [current]
822
+ );
823
+ const { select: selectRows } = options;
824
+ const select = useCallback2(
825
+ (query2) => {
826
+ const rows = query2.data?.result ?? {};
827
+ const data = Object.fromEntries(
828
+ keys.filter((key) => Object.hasOwn(rows, key)).map((key) => [key, rows[key]])
829
+ );
830
+ return {
831
+ data: selectRows ? selectRows(data) : data,
832
+ error: query2.error === null ? null : experimental_PluginRpcCallError.from(
833
+ query2.error,
834
+ "invalid_response"
835
+ ),
836
+ isLoading: enabled && keys.some((key) => !Object.hasOwn(rows, key)) && query2.isFetching,
837
+ isFetching: query2.isFetching
838
+ };
839
+ },
840
+ [keys, enabled, selectRows]
841
+ );
842
+ const query = useQuerySelection(subscribe, getSnapshot, select);
843
+ const refetch = useCallback2(async () => {
844
+ await current.observer.refetch();
845
+ }, [current]);
846
+ return {
847
+ ...query,
848
+ refetch
849
+ };
850
+ }
851
+ function experimental_useRpcMutation(options) {
852
+ const host = useHost();
853
+ const pluginId = options.pluginId ?? host.pluginId;
854
+ const mutation = useTaggedMutation(
855
+ host.queryClient,
856
+ (tags) => invalidateTags(host.queryClient, pluginTagScope(pluginId), tags),
857
+ async (input) => {
858
+ const response = await callRpcEnvelope(
859
+ host,
860
+ pluginId,
861
+ options.method,
862
+ jsonValueSchema.parse(input)
863
+ );
864
+ return {
865
+ ...response,
866
+ result: response.result
867
+ };
868
+ },
869
+ (input) => {
870
+ const updates = [];
871
+ options.optimistic?.(
872
+ input,
873
+ optimisticCache(pluginId, updates)
874
+ );
875
+ return updates;
876
+ }
877
+ );
878
+ const { mutate } = mutation;
879
+ return {
880
+ ...mutation,
881
+ error: mutation.error === null ? null : experimental_PluginRpcCallError.from(
882
+ mutation.error,
883
+ "invalid_input"
884
+ ),
885
+ mutate: useCallback2(
886
+ async (...args) => {
887
+ try {
888
+ return await mutate(
889
+ args[0] ?? null
890
+ );
891
+ } catch (error) {
892
+ throw experimental_PluginRpcCallError.from(error);
893
+ }
894
+ },
895
+ [mutate]
896
+ )
897
+ };
898
+ }
899
+ function experimental_useRpcRefresh() {
900
+ const host = useHost();
901
+ const isRefreshing = useIsFetching(
902
+ { queryKey: ["plugin-rpc", host.pluginId] },
903
+ host.queryClient
904
+ ) > 0;
905
+ return {
906
+ isRefreshing,
907
+ refresh: () => {
908
+ void invalidateTags(
909
+ host.queryClient,
910
+ pluginTagScope(host.pluginId),
911
+ null
912
+ );
913
+ }
914
+ };
915
+ }
916
+ return {
917
+ experimental_useRpcQuery,
918
+ experimental_useRpcKeyedQuery,
919
+ experimental_useRpcMutation,
920
+ experimental_useRpcRefresh
921
+ };
922
+ }
923
+
924
+ // src/internal/rpc-tags.ts
925
+ import { z as z3 } from "zod";
926
+ var rpcInvalidationTags = z3.array(z3.string().min(1)).min(1);
927
+ function rpcResponseTags(declarations, input, output) {
928
+ const tags = z3.array(z3.string().min(1)).parse(declarations.tags?.(input, output) ?? []);
929
+ const keyTags = {};
930
+ if (declarations.keyTags && typeof output === "object" && output !== null && !Array.isArray(output)) {
931
+ for (const [key, value] of Object.entries(output)) {
932
+ keyTags[key] = z3.array(z3.string().min(1)).parse(declarations.keyTags(key, value));
933
+ }
934
+ }
935
+ const invalidated = z3.array(z3.string().min(1)).parse(declarations.invalidates?.(input, output) ?? []);
936
+ return { tags, keyTags, invalidated };
937
+ }
938
+
939
+ // src/testing/app.tsx
940
+ import * as React from "react";
941
+ import {
942
+ createContext,
943
+ useCallback as useCallback3,
944
+ useContext,
945
+ useLayoutEffect,
946
+ useEffect as useEffect3,
947
+ useMemo as useMemo3,
948
+ useRef as useRef2,
949
+ useState as useState2,
950
+ useSyncExternalStore as useSyncExternalStore2
951
+ } from "react";
14
952
  import { act, render } from "@testing-library/react";
15
953
 
16
954
  // src/internal/composer-view.ts
@@ -75,71 +1013,71 @@ function reconcileComposerMentions(currentText, nextText, mentions) {
75
1013
  }
76
1014
 
77
1015
  // src/internal/composer-draft-actions.ts
78
- import { z } from "zod";
1016
+ import { z as z4 } from "zod";
79
1017
  var range = {
80
- from: z.number().int().nonnegative(),
81
- to: z.number().int().nonnegative(),
82
- label: z.string()
1018
+ from: z4.number().int().nonnegative(),
1019
+ to: z4.number().int().nonnegative(),
1020
+ label: z4.string()
83
1021
  };
84
- var mentionSchema = z.discriminatedUnion("kind", [
85
- z.object({
1022
+ var mentionSchema = z4.discriminatedUnion("kind", [
1023
+ z4.object({
86
1024
  ...range,
87
- kind: z.literal("thread"),
88
- threadId: z.string(),
89
- projectId: z.string().optional()
1025
+ kind: z4.literal("thread"),
1026
+ threadId: z4.string(),
1027
+ projectId: z4.string().optional()
90
1028
  }),
91
- z.object({ ...range, kind: z.literal("project"), projectId: z.string() }),
92
- z.object({ ...range, kind: z.literal("section"), sectionId: z.string() }),
93
- z.object({
1029
+ z4.object({ ...range, kind: z4.literal("project"), projectId: z4.string() }),
1030
+ z4.object({ ...range, kind: z4.literal("section"), sectionId: z4.string() }),
1031
+ z4.object({
94
1032
  ...range,
95
- kind: z.literal("path"),
96
- path: z.string(),
97
- source: z.enum(["workspace", "thread-storage"]),
98
- entryKind: z.enum(["file", "directory"])
1033
+ kind: z4.literal("path"),
1034
+ path: z4.string(),
1035
+ source: z4.enum(["workspace", "thread-storage"]),
1036
+ entryKind: z4.enum(["file", "directory"])
99
1037
  }),
100
- z.object({
1038
+ z4.object({
101
1039
  ...range,
102
- kind: z.literal("command"),
103
- trigger: z.enum(["/", "$"]),
104
- name: z.string(),
105
- source: z.enum(["skill", "command"]),
106
- origin: z.enum(["builtin", "project", "user"]),
107
- argumentHint: z.string().nullable()
1040
+ kind: z4.literal("command"),
1041
+ trigger: z4.enum(["/", "$"]),
1042
+ name: z4.string(),
1043
+ source: z4.enum(["skill", "command"]),
1044
+ origin: z4.enum(["builtin", "project", "user"]),
1045
+ argumentHint: z4.string().nullable()
108
1046
  }),
109
- z.object({ ...range, kind: z.literal("attachment"), path: z.string() }),
110
- z.object({
1047
+ z4.object({ ...range, kind: z4.literal("attachment"), path: z4.string() }),
1048
+ z4.object({
111
1049
  ...range,
112
- kind: z.literal("plugin"),
113
- pluginId: z.string(),
114
- provider: z.string().min(1).refine((value) => !value.includes(":")),
115
- id: z.string(),
116
- icon: z.string().nullable().optional()
1050
+ kind: z4.literal("plugin"),
1051
+ pluginId: z4.string(),
1052
+ provider: z4.string().min(1).refine((value) => !value.includes(":")),
1053
+ id: z4.string(),
1054
+ icon: z4.string().nullable().optional()
117
1055
  })
118
1056
  ]);
119
1057
  var attachmentFields = {
120
- type: z.enum(["localImage", "localFile"]),
121
- path: z.string().min(1),
122
- name: z.string(),
123
- mimeType: z.string().optional(),
124
- sizeBytes: z.number().nonnegative().optional()
1058
+ type: z4.enum(["localImage", "localFile"]),
1059
+ path: z4.string().min(1),
1060
+ name: z4.string(),
1061
+ mimeType: z4.string().optional(),
1062
+ sizeBytes: z4.number().nonnegative().optional()
125
1063
  };
126
- var attachmentsSchema = z.array(
127
- z.union([
128
- z.object({
1064
+ var attachmentsSchema = z4.array(
1065
+ z4.union([
1066
+ z4.object({
129
1067
  ...attachmentFields,
130
- hostId: z.string().min(1),
131
- sourceProjectId: z.undefined().optional()
1068
+ hostId: z4.string().min(1),
1069
+ sourceProjectId: z4.undefined().optional()
132
1070
  }),
133
- z.object({
1071
+ z4.object({
134
1072
  ...attachmentFields,
135
- sourceProjectId: z.string().min(1).optional(),
136
- hostId: z.undefined().optional()
1073
+ sourceProjectId: z4.string().min(1).optional(),
1074
+ hostId: z4.undefined().optional()
137
1075
  })
138
1076
  ])
139
1077
  );
140
- var replacementSchema = z.object({
141
- text: z.string(),
142
- mentions: z.array(mentionSchema),
1078
+ var replacementSchema = z4.object({
1079
+ text: z4.string(),
1080
+ mentions: z4.array(mentionSchema),
143
1081
  attachments: attachmentsSchema.optional()
144
1082
  }).superRefine((draft, context) => {
145
1083
  let end = 0;
@@ -967,7 +1905,7 @@ var experimental_THREAD_ACTION_GROUPS = {
967
1905
  };
968
1906
 
969
1907
  // src/internal/plugin-app-collector.ts
970
- import { z as z2 } from "zod";
1908
+ import { z as z5 } from "zod";
971
1909
  var CODE_FENCE_LANGUAGE_PATTERN = /^[a-z0-9][a-z0-9+#._-]*$/;
972
1910
  var sidebarFooterCommandSequence = 0;
973
1911
  var SIDEBAR_FOOTER_ACTION_KEYS = /* @__PURE__ */ new Set([
@@ -1099,6 +2037,8 @@ var NAV_PANEL_REGISTRATION_KEYS = new Set(
1099
2037
  component: true,
1100
2038
  fixedTabs: true,
1101
2039
  experimental_useBadge: true,
2040
+ experimental_usePageTitle: true,
2041
+ experimental_sidebar: true,
1102
2042
  headerContent: true
1103
2043
  })
1104
2044
  );
@@ -1128,8 +2068,8 @@ function checkStaleNavPanelKeys(kind, registration, onWarning) {
1128
2068
  }
1129
2069
  }
1130
2070
  }
1131
- var commandShortcutSchema = z2.object({
1132
- key: z2.string().min(1).max(32).refine(
2071
+ var commandShortcutSchema = z5.object({
2072
+ key: z5.string().min(1).max(32).refine(
1133
2073
  (key) => ![
1134
2074
  "Alt",
1135
2075
  "Control",
@@ -1140,11 +2080,11 @@ var commandShortcutSchema = z2.object({
1140
2080
  "Unidentified"
1141
2081
  ].includes(key)
1142
2082
  ),
1143
- mod: z2.boolean().default(false),
1144
- meta: z2.boolean().default(false),
1145
- control: z2.boolean().default(false),
1146
- alt: z2.boolean().default(false),
1147
- shift: z2.boolean().default(false)
2083
+ mod: z5.boolean().default(false),
2084
+ meta: z5.boolean().default(false),
2085
+ control: z5.boolean().default(false),
2086
+ alt: z5.boolean().default(false),
2087
+ shift: z5.boolean().default(false)
1148
2088
  }).strict().refine(
1149
2089
  (shortcut) => shortcut.mod || shortcut.meta || shortcut.control || shortcut.alt || /^F(?:[1-9]|1[0-9]|2[0-4])$/u.test(shortcut.key),
1150
2090
  "Use Command, Control, or Alt with a key, or a function key"
@@ -1358,6 +2298,16 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
1358
2298
  `${kind}: "experimental_useBadge" must be a React hook function when set`
1359
2299
  );
1360
2300
  }
2301
+ if (registration.experimental_sidebar !== void 0 && typeof registration.experimental_sidebar !== "function") {
2302
+ throw new Error(
2303
+ `${kind}: "experimental_sidebar" must be a React component function when set`
2304
+ );
2305
+ }
2306
+ if (registration.experimental_usePageTitle !== void 0 && typeof registration.experimental_usePageTitle !== "function") {
2307
+ throw new Error(
2308
+ `${kind}: "experimental_usePageTitle" must be a React hook function when set`
2309
+ );
2310
+ }
1361
2311
  const fixedTabs = (() => {
1362
2312
  if (registration.fixedTabs === void 0) return [];
1363
2313
  if (!Array.isArray(registration.fixedTabs)) {
@@ -1418,6 +2368,10 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
1418
2368
  ...registration.experimental_useBadge !== void 0 ? {
1419
2369
  experimental_useBadge: registration.experimental_useBadge
1420
2370
  } : {},
2371
+ ...registration.experimental_usePageTitle !== void 0 ? {
2372
+ experimental_usePageTitle: registration.experimental_usePageTitle
2373
+ } : {},
2374
+ ...registration.experimental_sidebar !== void 0 ? { experimental_sidebar: registration.experimental_sidebar } : {},
1421
2375
  ...registration.headerContent !== void 0 ? { headerContent: registration.headerContent } : {}
1422
2376
  });
1423
2377
  },
@@ -1550,9 +2504,9 @@ function collectPluginAppRegistrations(definition, onWarning = (message) => cons
1550
2504
  );
1551
2505
  }
1552
2506
  const extensions = rawExtensions.map((extension) => {
1553
- if (typeof extension !== "string" || !/^[a-z0-9]+$/.test(extension)) {
2507
+ if (typeof extension !== "string" || !/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/.test(extension)) {
1554
2508
  throw new Error(
1555
- `${kind}: extensions must be lowercase alphanumerics without the dot, got ${JSON.stringify(extension)}`
2509
+ `${kind}: extensions must be lowercase alphanumerics with single underscores or hyphens between segments, without the dot, got ${JSON.stringify(extension)}`
1556
2510
  );
1557
2511
  }
1558
2512
  return extension;
@@ -1775,7 +2729,7 @@ function attachLegacySidebarHeaders(navigations, headers, onWarning) {
1775
2729
  }
1776
2730
 
1777
2731
  // src/testing/app.tsx
1778
- import { jsx, jsxs } from "react/jsx-runtime";
2732
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
1779
2733
  function TestSidebarNavigationIcon({
1780
2734
  icon,
1781
2735
  className
@@ -1874,7 +2828,7 @@ function SlotLifecycleGuard({
1874
2828
  children,
1875
2829
  onUnmount
1876
2830
  }) {
1877
- useEffect(() => () => onUnmount(), [onUnmount]);
2831
+ useEffect3(() => () => onUnmount(), [onUnmount]);
1878
2832
  return children;
1879
2833
  }
1880
2834
  var SlotEnvContext = createContext(null);
@@ -1934,7 +2888,7 @@ function useTestMenuOpenState({
1934
2888
  onOpenChange,
1935
2889
  onCloseAutoFocus
1936
2890
  }) {
1937
- const [open, setOpen] = useState(false);
2891
+ const [open, setOpen] = useState2(false);
1938
2892
  return {
1939
2893
  open,
1940
2894
  show: () => {
@@ -1958,7 +2912,7 @@ function TestThreadActionsMenu({
1958
2912
  onCloseAutoFocus
1959
2913
  }) {
1960
2914
  const menu = useTestMenuOpenState({ onOpenChange, onCloseAutoFocus });
1961
- const triggerElement = useRef(null);
2915
+ const triggerElement = useRef2(null);
1962
2916
  useLayoutEffect(() => {
1963
2917
  const element = triggerElement.current;
1964
2918
  if (element?.getAttribute("aria-haspopup") !== "menu") {
@@ -2179,7 +3133,7 @@ function TestNewThreadComposer({
2179
3133
  draftKey,
2180
3134
  onSubmit
2181
3135
  }) {
2182
- const [text, setText] = useState(initialPrompt ?? "");
3136
+ const [text, setText] = useState2(initialPrompt ?? "");
2183
3137
  return /* @__PURE__ */ jsxs(
2184
3138
  "div",
2185
3139
  {
@@ -2239,9 +3193,9 @@ function TestProviderModelPicker({
2239
3193
  disabled,
2240
3194
  className
2241
3195
  }) {
2242
- const [draft, setDraft] = useState(value);
3196
+ const [draft, setDraft] = useState2(value);
2243
3197
  const { providerId, model, reasoningLevel, serviceTier } = value;
2244
- useEffect(
3198
+ useEffect3(
2245
3199
  () => setDraft({
2246
3200
  providerId,
2247
3201
  model,
@@ -2469,16 +3423,17 @@ function captureClipboardWrites(result) {
2469
3423
  }
2470
3424
  var testPluginSdkApp = {
2471
3425
  definePluginApp,
3426
+ ...createRpcQueryHooks(() => useSlotEnv("rpc query").rpcQueryHost),
2472
3427
  useRpc() {
2473
3428
  return useSlotEnv("useRpc").rpcClient;
2474
3429
  },
2475
3430
  useRealtime(channel, handler) {
2476
3431
  const env = useSlotEnv("useRealtime");
2477
- const handlerRef = useRef(handler);
2478
- useEffect(() => {
3432
+ const handlerRef = useRef2(handler);
3433
+ useEffect3(() => {
2479
3434
  handlerRef.current = handler;
2480
3435
  });
2481
- useEffect(() => {
3436
+ useEffect3(() => {
2482
3437
  const listener = (payload) => handlerRef.current(payload);
2483
3438
  let listeners = env.realtimeHandlers.get(channel);
2484
3439
  if (!listeners) {
@@ -2495,7 +3450,7 @@ var testPluginSdkApp = {
2495
3450
  const connection = useSlotEnv(
2496
3451
  "useRealtimeConnectionState"
2497
3452
  ).realtimeConnection;
2498
- return useSyncExternalStore(
3453
+ return useSyncExternalStore2(
2499
3454
  connection.subscribe,
2500
3455
  connection.getSnapshot,
2501
3456
  connection.getSnapshot
@@ -2521,7 +3476,7 @@ var testPluginSdkApp = {
2521
3476
  },
2522
3477
  experimental_useFixedTabTarget(tab) {
2523
3478
  const store = useSlotEnv("experimental_useFixedTabTarget").fixedTabTarget;
2524
- const state = useSyncExternalStore(
3479
+ const state = useSyncExternalStore2(
2525
3480
  store.subscribe,
2526
3481
  store.getSnapshot,
2527
3482
  store.getSnapshot
@@ -2542,7 +3497,7 @@ var testPluginSdkApp = {
2542
3497
  },
2543
3498
  useComposer() {
2544
3499
  const composer = useSlotEnv("useComposer").composer;
2545
- useSyncExternalStore(
3500
+ useSyncExternalStore2(
2546
3501
  composer.subscribe,
2547
3502
  composer.getVersionSnapshot,
2548
3503
  composer.getVersionSnapshot
@@ -2551,7 +3506,7 @@ var testPluginSdkApp = {
2551
3506
  },
2552
3507
  useComposers() {
2553
3508
  const composer = useSlotEnv("useComposers").composer;
2554
- useSyncExternalStore(
3509
+ useSyncExternalStore2(
2555
3510
  composer.subscribe,
2556
3511
  composer.getVersionSnapshot,
2557
3512
  composer.getVersionSnapshot
@@ -2622,7 +3577,7 @@ var testPluginSdkApp = {
2622
3577
  const calls = useSlotEnv(
2623
3578
  "experimental_useArchiveEnvironmentThreads"
2624
3579
  ).environmentArchiveCalls;
2625
- return useCallback(
3580
+ return useCallback3(
2626
3581
  async (environmentId) => {
2627
3582
  calls.push(environmentId);
2628
3583
  },
@@ -2634,32 +3589,37 @@ var testPluginSdkApp = {
2634
3589
  },
2635
3590
  experimental_ThreadActionsMenu: TestThreadActionsMenu,
2636
3591
  experimental_ThreadActionsContextMenu: TestThreadActionsContextMenu,
3592
+ experimental_PluginRpcCallError,
2637
3593
  experimental_THREAD_ACTION_GROUPS,
2638
3594
  experimental_useSidebarNavigation() {
2639
3595
  return useSlotEnv("experimental_useSidebarNavigation").sidebarNavigation;
2640
3596
  },
2641
3597
  experimental_useSidebarNavigationSplit(itemId, _options) {
2642
3598
  const env = useSlotEnv("experimental_useSidebarNavigationSplit");
2643
- return useMemo(
3599
+ const kind = env.sidebarNavigation.items.find(
3600
+ (item) => item.id === itemId
3601
+ )?.action.kind;
3602
+ const isAvailable = kind === "new-thread" || kind === "open-plugin-panel";
3603
+ return useMemo3(
2644
3604
  () => ({
2645
- splitProps: {
3605
+ splitProps: isAvailable ? {
2646
3606
  onPointerDown: () => {
2647
3607
  env.sidebarNavigationCalls.push({
2648
3608
  method: "beginSplitDrag",
2649
3609
  itemId
2650
3610
  });
2651
3611
  }
2652
- },
2653
- isAvailable: true,
3612
+ } : {},
3613
+ isAvailable,
2654
3614
  layout: null
2655
3615
  }),
2656
- [env, itemId]
3616
+ [env, isAvailable, itemId]
2657
3617
  );
2658
3618
  },
2659
3619
  experimental_SidebarNavigationIcon: TestSidebarNavigationIcon,
2660
3620
  experimental_useSidebarThreadSplit(threadId) {
2661
3621
  const env = useSlotEnv("experimental_useSidebarThreadSplit");
2662
- return useMemo(
3622
+ return useMemo3(
2663
3623
  () => ({
2664
3624
  splitProps: {
2665
3625
  onPointerDown: () => {
@@ -2674,7 +3634,7 @@ var testPluginSdkApp = {
2674
3634
  },
2675
3635
  useSidebarThreadDraft(threadId) {
2676
3636
  const env = useSlotEnv("useSidebarThreadDraft");
2677
- return useMemo(
3637
+ return useMemo3(
2678
3638
  () => ({ hasUnsubmittedDraft: env.sidebarDraftThreadIds.has(threadId) }),
2679
3639
  [env, threadId]
2680
3640
  );
@@ -2706,7 +3666,7 @@ var testPluginSdkApp = {
2706
3666
  },
2707
3667
  experimental_useSidebarThreadPullRequest(threadId) {
2708
3668
  const env = useSlotEnv("experimental_useSidebarThreadPullRequest");
2709
- return useMemo(
3669
+ return useMemo3(
2710
3670
  () => ({
2711
3671
  isLoading: false,
2712
3672
  pullRequest: env.sidebarPullRequests.get(threadId) ?? null
@@ -2716,12 +3676,12 @@ var testPluginSdkApp = {
2716
3676
  },
2717
3677
  useComposerView() {
2718
3678
  const composer = useSlotEnv("useComposerView").composer;
2719
- const version = useSyncExternalStore(
3679
+ const version = useSyncExternalStore2(
2720
3680
  composer.subscribe,
2721
3681
  composer.getVersionSnapshot,
2722
3682
  composer.getVersionSnapshot
2723
3683
  );
2724
- return useMemo(() => {
3684
+ return useMemo3(() => {
2725
3685
  const text = composer.getText();
2726
3686
  const attachmentCount = composer.getAttachmentCount();
2727
3687
  return {
@@ -2895,19 +3855,47 @@ function renderSlot(registration, props, options = {}) {
2895
3855
  installTestPluginRuntime();
2896
3856
  const rpcCalls = [];
2897
3857
  const rpcHandlers = options.rpc ?? {};
2898
- const rpcClient = {
2899
- async call(method, input) {
2900
- const normalizedInput = input === void 0 ? null : strictJsonRoundTrip(input, `rpc "${method}" input`);
2901
- rpcCalls.push({ method, input: normalizedInput });
2902
- const handler = rpcHandlers[method];
2903
- if (!handler) {
2904
- throw new Error(
2905
- `no rpc handler for "${method}" \u2014 add it to renderSlot options.rpc`
2906
- );
2907
- }
2908
- const result2 = await handler(normalizedInput);
2909
- return strictJsonRoundTrip(result2, `rpc "${method}" result`);
3858
+ const parseRpcValue = async (schema, value, code) => {
3859
+ const parsed = await schema["~standard"].validate(value);
3860
+ if (parsed.issues !== void 0)
3861
+ throw new experimental_PluginRpcCallError({
3862
+ code,
3863
+ message: parsed.issues.map((issue) => issue.message).join("; ")
3864
+ });
3865
+ return parsed.value;
3866
+ };
3867
+ const queryClient = new QueryClient();
3868
+ const callRpc = async (method, input) => {
3869
+ const normalizedInput = input === void 0 ? null : strictJsonRoundTrip(input, `rpc "${method}" input`);
3870
+ rpcCalls.push({ method, input: normalizedInput });
3871
+ const handler = rpcHandlers[method];
3872
+ if (!handler) {
3873
+ throw new experimental_PluginRpcCallError({
3874
+ code: "unknown_method",
3875
+ message: `no rpc handler for "${method}" \u2014 add it to renderSlot options.rpc`
3876
+ });
2910
3877
  }
3878
+ const declaration = options.experimental_rpcContract?.[method];
3879
+ const parsedInput = declaration ? await parseRpcValue(declaration.input, normalizedInput, "invalid_input") : normalizedInput;
3880
+ let result2;
3881
+ try {
3882
+ result2 = await handler(parsedInput);
3883
+ } catch (error) {
3884
+ throw experimental_PluginRpcCallError.from(error, "handler_error");
3885
+ }
3886
+ const parsedOutput = declaration ? await parseRpcValue(declaration.output, result2, "invalid_output") : result2;
3887
+ const envelope = rpcResponseTags(
3888
+ declaration ?? {},
3889
+ parsedInput,
3890
+ parsedOutput
3891
+ );
3892
+ return {
3893
+ result: strictJsonRoundTrip(parsedOutput, `rpc "${method}" result`),
3894
+ ...envelope
3895
+ };
3896
+ };
3897
+ const rpcClient = {
3898
+ call: async (method, input) => (await callRpc(method, input)).result
2911
3899
  };
2912
3900
  const realtimeHandlers = /* @__PURE__ */ new Map();
2913
3901
  let realtimeConnectionState = options.realtimeConnectionState ?? "connected";
@@ -3001,11 +3989,14 @@ function renderSlot(registration, props, options = {}) {
3001
3989
  sidebarNavigationCalls.push({
3002
3990
  method: "activate",
3003
3991
  itemId,
3004
- openInSplit: activationOptions.openInSplit
3992
+ target: activationOptions.target
3005
3993
  });
3006
3994
  },
3007
- goHome() {
3008
- sidebarNavigationCalls.push({ method: "goHome" });
3995
+ goHome(activationOptions) {
3996
+ sidebarNavigationCalls.push({
3997
+ method: "goHome",
3998
+ target: activationOptions?.target ?? "current"
3999
+ });
3009
4000
  },
3010
4001
  setVisible(itemId, isVisible) {
3011
4002
  sidebarNavigationCalls.push({
@@ -3393,7 +4384,15 @@ ${block}
3393
4384
  return () => composerListeners.delete(listener);
3394
4385
  }
3395
4386
  };
4387
+ const rpcQueryHost = {
4388
+ pluginId: options.pluginId ?? "test-plugin",
4389
+ queryClient,
4390
+ subscribe: () => () => {
4391
+ },
4392
+ call: (_pluginId, method, input) => callRpc(method, input)
4393
+ };
3396
4394
  const env = {
4395
+ rpcQueryHost,
3397
4396
  rpcClient,
3398
4397
  rpcCalls,
3399
4398
  realtimeHandlers,
@@ -3453,7 +4452,19 @@ ${block}
3453
4452
  composerLog.textEffect = null;
3454
4453
  composerLog.inputLocked = false;
3455
4454
  };
3456
- const renderSlotTree = (ui) => /* @__PURE__ */ jsx(SlotEnvContext.Provider, { value: env, children: /* @__PURE__ */ jsx(SlotLifecycleGuard, { onUnmount: releaseComposerOwnership, children: ui }) });
4455
+ let pageTitle = null;
4456
+ const usePageTitle = registration.experimental_usePageTitle;
4457
+ function SlotPageTitle({ children }) {
4458
+ const value = usePageTitle ? usePageTitle(props) : null;
4459
+ useLayoutEffect(() => {
4460
+ pageTitle = value;
4461
+ return () => {
4462
+ pageTitle = null;
4463
+ };
4464
+ }, [value]);
4465
+ return /* @__PURE__ */ jsx(Fragment, { children });
4466
+ }
4467
+ const renderSlotTree = (ui) => /* @__PURE__ */ jsx(SlotEnvContext.Provider, { value: env, children: /* @__PURE__ */ jsx(SlotLifecycleGuard, { onUnmount: releaseComposerOwnership, children: /* @__PURE__ */ jsx(SlotPageTitle, { children: ui }) }) });
3457
4468
  const Component = registration.component;
3458
4469
  const element = renderSlotTree(/* @__PURE__ */ jsx(Component, { ...props }));
3459
4470
  const result = render(element);
@@ -3481,6 +4492,15 @@ ${block}
3481
4492
  notifyComposerListeners();
3482
4493
  });
3483
4494
  };
4495
+ const experimental_invalidateRpc = async (tags) => {
4496
+ await act(async () => {
4497
+ await invalidateTags(
4498
+ queryClient,
4499
+ pluginTagScope(rpcQueryHost.pluginId),
4500
+ tags
4501
+ );
4502
+ });
4503
+ };
3484
4504
  const unmountSlot = () => {
3485
4505
  if (!composerOwnership.active) return;
3486
4506
  result.unmount();
@@ -3490,6 +4510,7 @@ ${block}
3490
4510
  rerender: rerenderSlot,
3491
4511
  unmount: unmountSlot,
3492
4512
  rpcCalls,
4513
+ experimental_invalidateRpc,
3493
4514
  emitRealtime,
3494
4515
  setRealtimeConnectionState,
3495
4516
  setComposerText: setComposerText2,
@@ -3503,12 +4524,16 @@ ${block}
3503
4524
  experimental_clipboardWrites,
3504
4525
  composer: composerLog,
3505
4526
  behavior: {
4527
+ experimental_invalidateRpc,
3506
4528
  emitRealtime,
3507
4529
  setRealtimeConnectionState,
3508
4530
  setComposerText: setComposerText2,
3509
4531
  setComposerScope
3510
4532
  },
3511
4533
  inspection: {
4534
+ get experimental_pageTitle() {
4535
+ return pageTitle;
4536
+ },
3512
4537
  rpcCalls,
3513
4538
  navigateCalls,
3514
4539
  experimental_fixedTabOpenCalls,
@@ -3519,6 +4544,9 @@ ${block}
3519
4544
  experimental_clipboardWrites,
3520
4545
  composer: composerLog
3521
4546
  },
4547
+ get experimental_pageTitle() {
4548
+ return pageTitle;
4549
+ },
3522
4550
  lifecycle: { rerender: rerenderSlot, unmount: unmountSlot }
3523
4551
  };
3524
4552
  }