@voltro/client 0.83.0 → 0.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,346 @@
1
+ import { S as e, a as t, c as n, h as r, i, n as a, s as o, u as s } from "./runRpc-DvHpFZAZ.js";
2
+ import { Context as c, Effect as l, Either as u, Layer as d, ManagedRuntime as f, Scheduler as p, Schema as m, Stream as h } from "effect";
3
+ import * as g from "@effect/platform/Headers";
4
+ import { RpcClient as _, RpcSerialization as v } from "@effect/rpc";
5
+ import { compareSurfaces as y, groupShapeDigests as b } from "@voltro/protocol";
6
+ import * as x from "@effect/platform/Socket";
7
+ //#region src/clientScheduler.ts
8
+ var S = {
9
+ channel: "timer",
10
+ yield: (e) => {
11
+ setTimeout(e, 0);
12
+ }
13
+ }, C = (e) => {
14
+ let t = [];
15
+ return e.port1.onmessage = () => {
16
+ t.shift()?.();
17
+ }, e.port1.unref?.(), {
18
+ channel: "message-channel",
19
+ yield: (n) => {
20
+ t.push(n), e.port2.postMessage(null);
21
+ }
22
+ };
23
+ }, w = () => globalThis.window !== void 0 && typeof MessageChannel == "function" ? C(new MessageChannel()) : S, T = 2048, E = (e = w(), t = T) => {
24
+ let n = p.SchedulerRunner.cached((n, r) => {
25
+ n >= t ? e.yield(() => r(0)) : Promise.resolve().then(() => r(n + 1));
26
+ });
27
+ return {
28
+ yieldChannel: e.channel,
29
+ shouldYield: p.defaultShouldYield,
30
+ scheduleTask: (e, t, r) => {
31
+ n(r).scheduleTask(e, t);
32
+ }
33
+ };
34
+ }, D = (e, t, n) => {
35
+ try {
36
+ let r = globalThis.location, i = typeof r == "object" && r ? r.href : void 0, a = new URL(e, i);
37
+ if (a.protocol === "wss:" ? a.protocol = "https:" : a.protocol === "ws:" && (a.protocol = "http:"), n !== void 0) return new URL(n, a).toString();
38
+ let o = `/ws/${t}`;
39
+ if (a.pathname === o) a.pathname = `/_voltro/api/${encodeURIComponent(t)}/_voltro/runtime-capabilities`;
40
+ else {
41
+ let e = a.pathname.lastIndexOf("/");
42
+ a.pathname = `${e <= 0 ? "" : a.pathname.slice(0, e)}/_voltro/runtime-capabilities`;
43
+ }
44
+ return a.search = "", a.hash = "", a.toString();
45
+ } catch {
46
+ return;
47
+ }
48
+ }, O = async (e, t, n = fetch, r = 1500, i) => {
49
+ let a = D(e, t, i);
50
+ if (a === void 0) return;
51
+ let o = new AbortController(), s = setTimeout(() => o.abort(), r);
52
+ try {
53
+ let e = await n(a, {
54
+ method: "GET",
55
+ headers: { accept: "application/json" },
56
+ cache: "no-store",
57
+ signal: o.signal
58
+ });
59
+ if (!e.ok) return;
60
+ let t = await e.json();
61
+ if (t.protocol !== 1 || typeof t.mutationReplay != "boolean") return;
62
+ let r = (e) => typeof e == "object" && e && !Array.isArray(e) && Object.values(e).every((e) => typeof e == "string") ? e : void 0, i = r(t.surface), s = r(t.serviceSurface);
63
+ return {
64
+ protocol: 1,
65
+ mutationReplay: t.mutationReplay,
66
+ ...i === void 0 ? {} : { surface: i },
67
+ ...s === void 0 ? {} : { serviceSurface: s }
68
+ };
69
+ } catch {
70
+ return;
71
+ } finally {
72
+ clearTimeout(s);
73
+ }
74
+ }, k = class {
75
+ #e;
76
+ #t;
77
+ #n;
78
+ #r = /* @__PURE__ */ new Set();
79
+ getSnapshot = () => this.#n;
80
+ subscribe = (e) => (this.#r.add(e), () => {
81
+ this.#r.delete(e);
82
+ });
83
+ begin() {
84
+ let e = {};
85
+ return this.#e = e, this.#i(), {
86
+ open: () => {
87
+ if (this.#e === e) return this.#n === void 0 && (this.#t = new AbortController(), this.#n = Object.freeze({ signal: this.#t.signal }), this.#a()), this.#e === e ? this.#n : void 0;
88
+ },
89
+ close: () => {
90
+ this.#e === e && (this.#e = void 0, this.#i());
91
+ }
92
+ };
93
+ }
94
+ #i() {
95
+ let e = this.#t, t = this.#n !== void 0;
96
+ this.#t = void 0, this.#n = void 0, e?.abort(), t && this.#a();
97
+ }
98
+ #a() {
99
+ for (let e of this.#r) try {
100
+ e();
101
+ } catch {}
102
+ }
103
+ }, A = /* @__PURE__ */ new WeakMap(), j = (e, t) => {
104
+ A.set(e, t);
105
+ }, M = (e) => A.get(e), N = async (t, n, r, i) => {
106
+ if (r !== void 0) try {
107
+ let a = await r({
108
+ apiName: t,
109
+ descriptors: i
110
+ });
111
+ return e(t, "runtime.mirror", {
112
+ generation: n,
113
+ mirrored: a !== void 0
114
+ }), a;
115
+ } catch (r) {
116
+ e(t, "runtime.mirror", {
117
+ generation: n,
118
+ mirrored: !1,
119
+ errorName: r instanceof Error ? r.name : typeof r
120
+ });
121
+ return;
122
+ }
123
+ }, P = (e, t, n = new k()) => x.Socket.of({
124
+ ...e,
125
+ runRaw: (r, i) => l.acquireUseRelease(l.sync(() => n.begin()), (n) => e.runRaw(r, {
126
+ ...i,
127
+ onOpen: l.zipRight(i?.onOpen ?? l.void, l.sync(() => {
128
+ n.open() !== void 0 && t();
129
+ }))
130
+ }), (e) => l.sync(e.close))
131
+ }), F = 3, I = (t, n, r) => {
132
+ let i;
133
+ try {
134
+ i = y(b(n), r);
135
+ } catch {
136
+ return;
137
+ }
138
+ let { differing: a, missingHere: o } = i;
139
+ if (a.length === 0 && o.length === 0) return;
140
+ e(t, "runtime.surface-mismatch", {
141
+ differing: a.length,
142
+ missingHere: o.length,
143
+ first: a[0] ?? o[0] ?? null
144
+ });
145
+ let s = [...a, ...o].slice(0, F), c = a.length + o.length - s.length;
146
+ console.warn(`[voltro] the api client this page loaded does not match what the '${t}' server binds: ${s.join(", ")}${c > 0 ? ` and ${c} more` : ""}. Responses for those procedures may decode against the wrong schema — a field the server sends and this client does not know is dropped silently. Reload; if it persists, stop the dev server, delete \`.framework/.vite\`, and start it again.`);
147
+ }, L = async (n) => {
148
+ let { name: i, wsUrl: p, group: y, headers: b, webSocketConstructor: S } = n, C = n.generation ?? 0;
149
+ e(i, "runtime.build-started", { generation: C });
150
+ let w = n.errorBus ?? new s(), T = n.recovery ?? t(w, i), D = o(T.options.retry, (t, n) => {
151
+ e(i, "socket.retry-scheduled", {
152
+ generation: C,
153
+ attempt: t,
154
+ delayMs: n,
155
+ owner: "socket"
156
+ });
157
+ });
158
+ O(p, i, fetch, 1500, T.options.capabilitiesUrl).then((t) => {
159
+ T.setMutationReplaySupported(t?.mutationReplay === !0, C), e(i, "runtime.capabilities", {
160
+ mutationReplay: t?.mutationReplay === !0,
161
+ discovered: t !== void 0
162
+ });
163
+ let r = n.surfaceAudience === "service" ? t?.serviceSurface : t?.surface;
164
+ r !== void 0 && I(i, y, r);
165
+ });
166
+ let A = n.descriptors ?? {}, M = await N(i, C, n.mirror, A), F = new r({
167
+ errorBus: w,
168
+ apiName: i,
169
+ ...M === void 0 ? {} : { mirror: M }
170
+ }), L = new k(), R;
171
+ class z extends c.Tag(`@voltro/client/AppClient/${i}`)() {}
172
+ let B = d.succeed(x.WebSocketConstructor, S), V = x.layerWebSocket(p).pipe(d.provide(B)), H = d.effect(x.Socket, l.map(x.Socket, (t) => P(t, () => {
173
+ D.reset();
174
+ let t = 0;
175
+ R !== void 0 && (t = F.resumeTransportFailures(R)), e(i, "protocol.ready", {
176
+ generation: C,
177
+ resumed: t
178
+ }), T.protocolReady();
179
+ }, L))).pipe(d.provide(V)), U = _.layerProtocolSocket({ retrySchedule: D.schedule }).pipe(d.provide(v.layerJson), d.provide(H)), W = typeof b == "function" ? await b() : b, G = d.scoped(z, _.make(y)).pipe(d.provide(U)), K = W ? d.locallyScoped(_.currentHeaders, g.fromInput(W)) : d.empty, q = E(), J = f.make(d.merge(G, K).pipe(d.provide(d.setScheduler(q))));
180
+ R = J, j(R, L);
181
+ try {
182
+ let t = await J.runPromise(z);
183
+ e(i, "runtime.resolved", {
184
+ generation: C,
185
+ scheduler: q.yieldChannel
186
+ });
187
+ let n = (M?.warmTags ?? []).filter((e) => {
188
+ let t = A[e]?.input;
189
+ return t !== void 0 && u.isRight(m.decodeUnknownEither(t)({}));
190
+ }).map((e) => [e, {}]);
191
+ for (let [e, r] of [...M?.warm ?? [], ...n]) {
192
+ let n = A[e]?.source;
193
+ F.subscribe([e, r], () => h.suspend(() => a(t, e)(r)), J, () => {}, n === void 0 ? {} : { source: n });
194
+ }
195
+ return {
196
+ runtime: J,
197
+ client: t,
198
+ cache: F,
199
+ errorBus: w,
200
+ recovery: T
201
+ };
202
+ } catch (t) {
203
+ throw e(i, "runtime.failed", {
204
+ generation: C,
205
+ errorName: t instanceof Error ? t.name : typeof t
206
+ }), J.dispose(), t;
207
+ }
208
+ }, R = (e, t, n) => ({
209
+ resolved: null,
210
+ retryToken: 0,
211
+ failureCount: 0,
212
+ generation: 0,
213
+ reconnectStatusDispose: null,
214
+ everOpened: !1,
215
+ wedgeStop: null,
216
+ subjectMayHaveChanged: !1,
217
+ errorBus: e,
218
+ recovery: t,
219
+ stopRecoveryError: e.on((e) => t.observeError(e)),
220
+ stopRecoverySuccess: e.onSuccess((e) => t.observeSuccess(e)),
221
+ ownsRecovery: n
222
+ }), z = (e) => {
223
+ e.wedgeStop !== null && (e.wedgeStop(), e.wedgeStop = null);
224
+ }, B = (e) => {
225
+ e.cache.destroy(e.runtime), e.runtime.dispose();
226
+ }, V = (t) => {
227
+ let r = t.apis, a = t.buildClient, o = t.onChange, c = t.stableWindowMs ?? 5e3, l = t.scheduler?.setTimeout ?? ((e, t) => setTimeout(e, t)), u = t.scheduler?.clearTimeout ?? ((e) => {
228
+ clearTimeout(e);
229
+ }), d = t.scheduler?.queueMicrotask ?? queueMicrotask, f = t.onReconnecting, p = t.wedgeBackstop, m = /* @__PURE__ */ new Map();
230
+ for (let e of r) {
231
+ let n = t.errorBusFor?.(e.name) ?? new s(), r = t.recoveryFor?.(e.name, e.recovery), a = r ?? new i(e.name, e.recovery);
232
+ m.set(e.name, R(n, a, r === void 0));
233
+ }
234
+ let h = !1, g = /* @__PURE__ */ new Set(), _ = (e, t) => {
235
+ let n = l(() => {
236
+ g.delete(n), e();
237
+ }, t);
238
+ return g.add(n), n;
239
+ }, v = () => {
240
+ if (h) return;
241
+ let e = /* @__PURE__ */ new Map();
242
+ for (let [t, n] of m) n.resolved && e.set(t, n.resolved);
243
+ o(e, r.every((t) => e.has(t.name)));
244
+ }, y = (e, t) => {
245
+ t.failureCount += 1, !t.reconnectStatusDispose && f && (t.reconnectStatusDispose = f(e.name)), p && t.everOpened && t.failureCount >= p.afterFailures && t.wedgeStop === null && (t.wedgeStop = p.arm(e.name));
246
+ }, b = (r) => {
247
+ if (h) return;
248
+ let i = m.get(r.name);
249
+ if (!i) return;
250
+ y(r, i);
251
+ let a = t.retryDelayMs?.(i.failureCount) ?? n(i.recovery.options.retry, i.failureCount);
252
+ e(r.name, "socket.retry-scheduled", {
253
+ generation: i.generation,
254
+ attempt: i.failureCount,
255
+ delayMs: a,
256
+ owner: "runtime-build"
257
+ });
258
+ let o = ++i.retryToken;
259
+ _(() => {
260
+ h || i.retryToken === o && (i.generation += 1, x(r));
261
+ }, a);
262
+ }, x = async (t) => {
263
+ if (h) return;
264
+ let n = m.get(t.name);
265
+ if (!n) return;
266
+ let r = n.generation, i = () => {
267
+ if (h || n.generation !== r) return;
268
+ n.everOpened = !0, z(n), n.reconnectStatusDispose &&= (n.reconnectStatusDispose(), null), n.retryToken++;
269
+ let e = n.failureCount;
270
+ _(() => {
271
+ h || n.failureCount === e && (n.failureCount = 0);
272
+ }, c);
273
+ }, o = (e) => {
274
+ h || n.generation !== r || (n.recovery.transportIssue(), y(t, n));
275
+ };
276
+ try {
277
+ let s = await a(t, r, i, o, n.errorBus, n.recovery);
278
+ if (h || n.generation !== r) {
279
+ B(s);
280
+ return;
281
+ }
282
+ let c = n.resolved, l = n.subjectMayHaveChanged, u = c && !l ? s.cache.seedStaleFrom(c.cache) : 0;
283
+ n.subjectMayHaveChanged = !1, n.resolved = s, e(t.name, "runtime.swapped", {
284
+ generation: r,
285
+ replaced: c !== null,
286
+ seeded: u,
287
+ subjectMayHaveChanged: l
288
+ }), v(), c && B(c);
289
+ } catch {
290
+ if (h || n.generation !== r) return;
291
+ b(t);
292
+ }
293
+ }, S = (e) => {
294
+ if (!h) for (let t of r) {
295
+ let n = m.get(t.name);
296
+ n && (e && (n.subjectMayHaveChanged = !0), n.retryToken += 1, n.generation += 1, e && n.recovery.resetForSubjectChange(n.generation), n.failureCount = 0, z(n), x(t));
297
+ }
298
+ };
299
+ return r.length === 0 ? (o(/* @__PURE__ */ new Map(), !0), {
300
+ dispose: () => {
301
+ h = !0;
302
+ },
303
+ reconnect: () => {},
304
+ refreshAuth: () => {}
305
+ }) : (d(() => {
306
+ if (!h) for (let e of r) x(e);
307
+ }), {
308
+ dispose: () => {
309
+ if (!h) {
310
+ h = !0;
311
+ for (let e of g) u(e);
312
+ g.clear();
313
+ for (let [, e] of m) e.resolved && B(e.resolved), e.reconnectStatusDispose && e.reconnectStatusDispose(), z(e), e.stopRecoveryError(), e.stopRecoverySuccess(), e.ownsRecovery && e.recovery.dispose();
314
+ for (let t of r) e(t.name, "runtime.disposed");
315
+ m.clear();
316
+ }
317
+ },
318
+ reconnect: () => {
319
+ S(!0);
320
+ },
321
+ refreshAuth: () => {
322
+ S(!1);
323
+ }
324
+ });
325
+ }, H = 0, U = () => {
326
+ let e = typeof crypto < "u" ? crypto : void 0;
327
+ return e && typeof e.randomUUID == "function" ? e.randomUUID() : `idem_${Date.now().toString(36)}_${H += 1}`;
328
+ }, W = (e, t) => e.pipe(l.locallyWith(_.currentHeaders, (e) => g.set(e, "idempotency-key", t))), G = (e) => e?._tag === "Unauthenticated", K = (e, t, n = {}) => {
329
+ let r = n.cooldownMs ?? 15e3, i = n.maxConsecutive ?? 3, a = n.now ?? (() => Date.now()), o = -Infinity, s = 0, c = e.on((e) => {
330
+ if (!G(e.error) || s >= i) return;
331
+ let n = a();
332
+ n - o < r || (o = n, s += 1, t());
333
+ }), l = e.onSuccess(() => {
334
+ s = 0;
335
+ });
336
+ return {
337
+ dispose: () => {
338
+ c(), l();
339
+ },
340
+ noteSuccess: () => {
341
+ s = 0;
342
+ }
343
+ };
344
+ };
345
+ //#endregion
346
+ export { V as a, M as c, W as i, K as n, L as o, U as r, P as s, G as t };
package/dist/index.d.ts CHANGED
@@ -185,6 +185,22 @@ export declare interface Analytics<E extends ReadonlyArray<EventDescriptor<strin
185
185
  * React context (and its browser globals) merely to name this Effect type. */
186
186
  export declare type AnyRuntime = ManagedRuntime.ManagedRuntime<never, never>;
187
187
 
188
+ /** The registry's read side, as other packages see it through the slot. */
189
+ export declare interface ApiConnectivity {
190
+ /**
191
+ * Is the transport up? With a name: that api's. Without: any mounted api's
192
+ * — the right default for a writer that does not say which api it talks to,
193
+ * because answering "down" while its own api is up would hold its queue
194
+ * shut. `undefined` when no api (of that name) is mounted: nothing is known.
195
+ */
196
+ readonly online: (apiName?: string) => boolean | undefined;
197
+ /** Called on every transport change of any api. Returns the unsubscribe. */
198
+ readonly subscribe: (listener: () => void) => () => void;
199
+ }
200
+
201
+ /** The read side — what `useApiOnline` and other packages consume. */
202
+ export declare const apiConnectivity: () => ApiConnectivity;
203
+
188
204
  export declare interface ApiHandle {
189
205
  readonly runtime: AnyRuntime;
190
206
  readonly cache: SubscriptionCache;
@@ -429,6 +445,16 @@ export declare interface BuildApiRuntimeOptions {
429
445
  * its concern.
430
446
  */
431
447
  readonly surfaceAudience?: 'client' | 'service';
448
+ /**
449
+ * Durable local mirror for this generation's subscription cache — the
450
+ * offline read half of local-first. Resolved once here, before the cache
451
+ * exists; see {@link SubscriptionMirrorSource} for why it is never swapped
452
+ * under a live cache.
453
+ */
454
+ readonly mirror?: SubscriptionMirrorSource | undefined;
455
+ /** The api's rpc descriptors. Handed to the mirror source, and each warm
456
+ * query's `source` routes queued writes' previews onto it. */
457
+ readonly descriptors?: Readonly<Record<string, ClientDescriptor>> | undefined;
432
458
  }
433
459
 
434
460
  export declare type BuildClient = (api: MountedApi, generation: number, onSocketOpen: () => void, onSocketIssue: (kind: SocketIssueKind) => void,
@@ -689,7 +715,7 @@ export declare interface ClientDiagnosticEvent {
689
715
  readonly fields: Readonly<Record<string, ClientDiagnosticValue>>;
690
716
  }
691
717
 
692
- export declare type ClientDiagnosticKind = 'runtime.build-started' | 'runtime.resolved' | 'runtime.failed' | 'runtime.capabilities' | 'runtime.surface-mismatch' | 'runtime.swapped' | 'runtime.disposed' | 'socket.created' | 'socket.raw-open' | 'socket.close' | 'socket.error' | 'socket.connect-timeout' | 'socket.retry-scheduled' | 'socket.frames' | 'protocol.ready' | 'subscription.transport-failed' | 'subscription.reissue-started' | 'subscription.reissue-skipped' | 'subscription.first-delivery' | 'subscription.recovery-stuck' | 'subscription.recovery-timer-late' | 'subscription.health-cleared' | 'event.gap' | 'connection.status' | 'recovery.state' | 'fault.transport-cut';
718
+ export declare type ClientDiagnosticKind = 'runtime.build-started' | 'runtime.resolved' | 'runtime.failed' | 'runtime.capabilities' | 'runtime.surface-mismatch' | 'runtime.mirror' | 'runtime.swapped' | 'runtime.disposed' | 'socket.created' | 'socket.raw-open' | 'socket.close' | 'socket.error' | 'socket.connect-timeout' | 'socket.retry-scheduled' | 'socket.frames' | 'protocol.ready' | 'subscription.transport-failed' | 'subscription.reissue-started' | 'subscription.reissue-skipped' | 'subscription.first-delivery' | 'subscription.recovery-stuck' | 'subscription.recovery-timer-late' | 'subscription.health-cleared' | 'event.gap' | 'connection.status' | 'recovery.state' | 'fault.transport-cut';
693
719
 
694
720
  export declare interface ClientDiagnosticsSnapshot {
695
721
  readonly version: 1;
@@ -1044,6 +1070,13 @@ export declare interface DeepLinkSource {
1044
1070
  readonly subscribe: (onUrl: (url: string) => void) => () => void;
1045
1071
  }
1046
1072
 
1073
+ /**
1074
+ * Exponential backoff from 1 s, capped at 30 s, jittered into the upper half of
1075
+ * each step — the same curve `@voltro/local-first`'s sync client uses for CRDT
1076
+ * writes, so the two queues of one device back off alike.
1077
+ */
1078
+ export declare const defaultOutboxRetryDelay: (attempts: number) => number;
1079
+
1047
1080
  /**
1048
1081
  * Declare a deep link.
1049
1082
  *
@@ -1174,7 +1207,7 @@ export declare const emptyRichTextDocument: RichTextDocument;
1174
1207
  */
1175
1208
  export declare const enableClientDiagnosticsPersistence: (storage: ClientDiagnosticsStorage) => void;
1176
1209
 
1177
- export declare const enqueueEntry: (queue: Outbox, id: string, tag: string, input: unknown) => Outbox;
1210
+ export declare const enqueueEntry: (queue: Outbox, id: string, tag: string, input: unknown, stamp?: string) => Outbox;
1178
1211
 
1179
1212
  /**
1180
1213
  * One operation of an entity's admin surface.
@@ -1862,6 +1895,15 @@ export declare class LoadingSubscriptionCache extends SubscriptionCache {
1862
1895
  };
1863
1896
  }
1864
1897
 
1898
+ export declare interface LocalQueryOptions<Row> {
1899
+ /** Keep the rows this returns `true` for. Omitted: every row. */
1900
+ readonly where?: (row: Row) => boolean;
1901
+ /** Sort: a column name (ascending), `[column, 'asc' | 'desc']`, or a comparator. */
1902
+ readonly orderBy?: (keyof Row & string) | readonly [keyof Row & string, 'asc' | 'desc'] | ((a: Row, b: Row) => number);
1903
+ /** At most this many rows, after sorting. */
1904
+ readonly limit?: number;
1905
+ }
1906
+
1865
1907
  export declare const makePreloadSeedBag: () => PreloadSeedBag;
1866
1908
 
1867
1909
  export declare const makeStoreSeedBag: () => StoreSeedBag;
@@ -1951,6 +1993,9 @@ export declare interface MountedApi {
1951
1993
  readonly wsUrl: string;
1952
1994
  readonly headers?: ResolvableHeaders | undefined;
1953
1995
  readonly recovery?: RecoveryOptions | undefined;
1996
+ /** Durable local mirror, resolved per transport generation — see
1997
+ * `BuildApiRuntimeOptions.mirror`. */
1998
+ readonly mirror?: SubscriptionMirrorSource | undefined;
1954
1999
  }
1955
2000
 
1956
2001
  export declare interface MutateOptions<Input, Output> {
@@ -2146,18 +2191,23 @@ export declare interface OutboxEntry {
2146
2191
  readonly status: OutboxStatus;
2147
2192
  readonly attempts: number;
2148
2193
  readonly error?: unknown;
2194
+ /** When the write was made, as the `stamp` option's clock reported it — a
2195
+ * hybrid logical clock stamp feeds conflict resolution a causal order
2196
+ * where wall clocks disagree. Absent without a `stamp` option. */
2197
+ readonly stamp?: string;
2149
2198
  }
2150
2199
 
2151
2200
  /**
2152
- * Durability seam for the outbox queue. `load` runs once on mount and returns
2153
- * the surviving entries (oldest first); `save` is called after every queue
2201
+ * Durability seam for the outbox queue. `load` runs on mount — and again after
2202
+ * a sign-in or tenant switch on an `api`-bound outbox — and returns the
2203
+ * surviving entries (oldest first); `save` is called after every queue
2154
2204
  * transition with the entries worth keeping (`sent` entries are compacted away
2155
2205
  * before the call — a delivered write needs no durability).
2156
2206
  *
2157
2207
  * The one real implementation is `outboxPersistence()` in
2158
2208
  * `@voltro/local-first`, which stores the entries through the same
2159
2209
  * `PersistenceAdapter` the sync engine uses — ONE durable queue for a device,
2160
- * whichever surface enqueued the write.
2210
+ * whichever surface enqueued the write — partitioned per signed-in subject.
2161
2211
  */
2162
2212
  export declare interface OutboxPersistence {
2163
2213
  readonly load: () => Promise<Outbox>;
@@ -2475,12 +2525,31 @@ export declare interface QueryFiltersState<Row> {
2475
2525
  readonly error: unknown | undefined;
2476
2526
  }
2477
2527
 
2478
- /* Excluded from this release type: queryOnce */
2528
+ /**
2529
+ * Resolve `tag(input)` once on the api behind `handleRef`: a query to the data
2530
+ * of its first snapshot, a mutation or action to its result.
2531
+ *
2532
+ * Waits out the client boot window like every other imperative seam, and
2533
+ * rejects the way the server loader's `query` does: with the declared error
2534
+ * itself, whether it arrived as an in-band `error` event or as a failed call —
2535
+ * the same value every hook hands over. Aborting `signal` interrupts the call.
2536
+ *
2537
+ * @public
2538
+ * @remarks
2539
+ * The cross-package browser half of `LoaderContext.query`, wired by
2540
+ * `@voltro/web`'s router. Apps read through `ctx.query`.
2541
+ */
2542
+ export declare const queryOnce: (handleRef: {
2543
+ readonly current: ResolvableHandle;
2544
+ }, apiName: string, tag: string, input: Record<string, unknown> | undefined, signal?: AbortSignal) => Promise<unknown>;
2479
2545
 
2480
2546
  declare type QueryTag<P extends ProcedureTypeMap> = TagsOfKind<P, 'query'>;
2481
2547
 
2482
2548
  export declare type RawTransportStatus = 'connected' | 'disconnected';
2483
2549
 
2550
+ /** The current answer, outside React. */
2551
+ export declare const readApiOnline: (apiName?: string) => boolean;
2552
+
2484
2553
  export { readPairing }
2485
2554
 
2486
2555
  /**
@@ -3290,6 +3359,9 @@ export declare type RpcSuccessListener = (event: RpcSuccess) => void;
3290
3359
  */
3291
3360
  export declare const runDeepLink: <Pattern extends string>(descriptor: DeepLinkDescriptor<Pattern>, path: string) => DeepLinkParams<Pattern> | null;
3292
3361
 
3362
+ /** The query itself, outside React — `rows` from `SubscriptionCache.rowsOf`. */
3363
+ export declare const runLocalQuery: <Row>(rows: ReadonlyArray<Row>, options?: LocalQueryOptions<Row>) => ReadonlyArray<Row>;
3364
+
3293
3365
  /**
3294
3366
  * Run a sequence. Resolves with a discriminated result rather than rejecting —
3295
3367
  * the same "handled" semantics `useMutation`/`useAction` use, so the call site
@@ -3765,6 +3837,9 @@ export declare interface StoreUseOptions<T> {
3765
3837
  readonly retain?: boolean;
3766
3838
  }
3767
3839
 
3840
+ /** Call `listener` whenever the answer may have changed. Returns the unsubscribe. */
3841
+ export declare const subscribeApiOnline: (listener: () => void) => (() => void);
3842
+
3768
3843
  export declare const subscribeClientDiagnostics: (listener: () => void) => (() => void);
3769
3844
 
3770
3845
  /** Subscribe to client errors. Returns an unsubscribe fn. */
@@ -3780,6 +3855,10 @@ export declare const subscribeStoreHistory: (listener: Listener) => (() => void)
3780
3855
 
3781
3856
  export declare class SubscriptionCache {
3782
3857
  private readonly entries;
3858
+ /** Standing optimistic intents, by mutation id — see `autoApply`. */
3859
+ private readonly intents;
3860
+ private readonly tableRows;
3861
+ private readonly anyListeners;
3783
3862
  private readonly refreshing;
3784
3863
  /**
3785
3864
  * Same-subject runtime replacement. A mutation may settle against the cache
@@ -3901,7 +3980,15 @@ export declare class SubscriptionCache {
3901
3980
  * these defaults. All patches are tagged with `mutationId` for atomic
3902
3981
  * revert.
3903
3982
  */
3904
- autoApply(targets: ReadonlyArray<AutoApplyTarget>, input: Record<string, unknown>, mutationId: string): void;
3983
+ autoApply(targets: ReadonlyArray<AutoApplyTarget>, input: Record<string, unknown>, mutationId: string, options?: {
3984
+ readonly standing?: boolean;
3985
+ }): void;
3986
+ /** Whether a standing intent for `mutationId` is still held (see
3987
+ * {@link SubscriptionCache.autoApply}). Carried to a same-subject
3988
+ * replacement cache, so a stager can tell "already staged" from "new". */
3989
+ hasIntent(mutationId: string): boolean;
3990
+ private applyIntent;
3991
+ private applyStandingIntents;
3905
3992
  /** Drop a specific patch by id. */
3906
3993
  private revertPatch;
3907
3994
  /**
@@ -4028,6 +4115,17 @@ export declare class SubscriptionCache {
4028
4115
  private freshState;
4029
4116
  private startFiber;
4030
4117
  private invalidate;
4118
+ /**
4119
+ * Every row of `table` this cache holds — the client's local replica of the
4120
+ * table: the union of the rows of every entry sourced on that table ALONE
4121
+ * (an entry over several tables holds joined shapes, not rows of one),
4122
+ * optimistic previews and mirror-seeded rows included, deduplicated by `id`.
4123
+ * Memoised per table until the next change, so the result is reference-stable
4124
+ * for `useSyncExternalStore`.
4125
+ */
4126
+ rowsOf(table: string): ReadonlyArray<Readonly<Record<string, unknown>>>;
4127
+ /** Call `listener` after any entry changed. Returns the unsubscribe. */
4128
+ subscribeAny(listener: () => void): () => void;
4031
4129
  private getSnapshot;
4032
4130
  private unsubscribe;
4033
4131
  /** Start (or restart) the inactive-TTL countdown for `entry`: unless
@@ -4189,8 +4287,42 @@ export declare interface SubscriptionMirror {
4189
4287
  readonly data: unknown;
4190
4288
  readonly revision: number;
4191
4289
  }) => Promise<void>;
4290
+ /**
4291
+ * Queries to keep subscribed for the whole connection generation, as
4292
+ * `[tag, input]` — so they are mirrored, and readable offline, before any
4293
+ * screen ever opened them. Offline coverage is otherwise "what the user
4294
+ * happened to visit"; this makes it a declaration.
4295
+ */
4296
+ readonly warm?: ReadonlyArray<readonly [tag: string, input: Readonly<Record<string, unknown>>]>;
4297
+ /**
4298
+ * Tags to keep warm with an EMPTY input — each one whose declared input
4299
+ * schema accepts `{}` (a list, a feed, a settings read). The runtime makes
4300
+ * that check against the descriptors; a tag that needs parameters is left
4301
+ * out rather than subscribed into an error.
4302
+ */
4303
+ readonly warmTags?: ReadonlyArray<string>;
4304
+ }
4305
+
4306
+ /** What a {@link SubscriptionMirrorSource} is told about the api it mirrors. */
4307
+ export declare interface SubscriptionMirrorContext {
4308
+ /** The api's mount name (`'app'`). */
4309
+ readonly apiName: string;
4310
+ /** The api's rpc descriptors — each query's `source` table(s) is how a source
4311
+ * derives which queries read local-first tables without being told. */
4312
+ readonly descriptors: Readonly<Record<string, ClientDescriptor>>;
4192
4313
  }
4193
4314
 
4315
+ /**
4316
+ * Where a runtime gets its {@link SubscriptionMirror}: called ONCE per
4317
+ * connection generation, before that generation's cache exists. The cache
4318
+ * keeps what it returned for its whole life, so a mirror is never swapped
4319
+ * under a live cache — a sign-in or tenant switch (`reconnect()`) builds a new
4320
+ * generation, and THAT call resolves the next subject's partition. Resolving
4321
+ * to `undefined` (nobody signed in, no durable storage) mirrors nothing.
4322
+ * `@voltro/local-first`'s `createMirrorSource` is the implementation.
4323
+ */
4324
+ export declare type SubscriptionMirrorSource = (context: SubscriptionMirrorContext) => SubscriptionMirror | undefined | Promise<SubscriptionMirror | undefined>;
4325
+
4194
4326
  /**
4195
4327
  * Subscribe to a streaming rpc by tag.
4196
4328
  *
@@ -4682,6 +4814,9 @@ export declare interface UseAgentChatOptions {
4682
4814
 
4683
4815
  export declare const useAgentStream: <E = unknown>(apiName: string, rpcTag: string) => AgentStreamControls<E>;
4684
4816
 
4817
+ /** Can a write reach `apiName` (or any mounted api) right now? */
4818
+ export declare const useApiOnline: (apiName?: string) => boolean;
4819
+
4685
4820
  export declare const useAsyncValidation: (apiName: string, queryTag: string, value: string, options: UseAsyncValidationOptions) => AsyncValidationResult;
4686
4821
 
4687
4822
  export declare interface UseAsyncValidationOptions {
@@ -4962,6 +5097,10 @@ export declare const useFrameworkApi: (apiName: string) => ApiHandle;
4962
5097
 
4963
5098
  export declare const useFrameworkRuntimes: () => FrameworkRuntimes;
4964
5099
 
5100
+ /** Query the local replica of `table` (see the module header). Re-renders when
5101
+ * any row of the api's cache changes. */
5102
+ export declare const useLocalQuery: <Row = Readonly<Record<string, unknown>>>(apiName: string, table: string, options?: LocalQueryOptions<Row>) => ReadonlyArray<Row>;
5103
+
4965
5104
  /**
4966
5105
  * Invoke a unary rpc by tag. The descriptor metadata (mounted via
4967
5106
  * `app.config.ts`'s `apis` → emitted by codegen as `appDescriptors`)
@@ -4978,17 +5117,42 @@ export declare const useOnRpcError: (apiName: string, listener: RpcErrorListener
4978
5117
  export declare const useOutbox: (options: UseOutboxOptions) => OutboxControls;
4979
5118
 
4980
5119
  export declare interface UseOutboxOptions {
4981
- /** Perform one queued write (the real mutation). Throw to fail. */
4982
- readonly send: (entry: OutboxEntry) => Promise<void>;
5120
+ /**
5121
+ * The api the queued writes go to, by its mount name (`'app'`). Bound, the
5122
+ * outbox is the framework's offline write lane:
5123
+ *
5124
+ * - `send` defaults to the api's own mutation for the entry's tag, with
5125
+ * the entry id as its idempotency key — a write the server committed
5126
+ * whose answer was lost is not applied twice when it is resent;
5127
+ * - every queued write PREVIEWS through the mutation's declared `targets`
5128
+ * on every query that reads its table — including queries opened later
5129
+ * and rows rendered from the durable mirror after a reload — until it is
5130
+ * sent (the server's echo then supersedes it) or conflicts (reverted);
5131
+ * - connectivity follows the api's transport, not just the browser;
5132
+ * - a sign-in or tenant switch drops the previous subject's queue from
5133
+ * memory and loads the next one's from `persistence`.
5134
+ */
5135
+ readonly api?: string;
5136
+ /** Perform one queued write (the real mutation). Throw to fail. Required
5137
+ * unless `api` is set, where it defaults to the api's mutation. */
5138
+ readonly send?: (entry: OutboxEntry) => Promise<void>;
4983
5139
  /** Durable backing (see {@link OutboxPersistence}). Omitted → in-memory only. */
4984
5140
  readonly persistence?: OutboxPersistence;
4985
- /** Online override (defaults to navigator.onLine + online/offline events). */
5141
+ /** Online override. Default: the browser's signal AND, with `api`, that
5142
+ * api's transport (`useApiOnline`). */
4986
5143
  readonly online?: boolean;
4987
5144
  /** Classify a send error as a conflict (blocks replay) vs a transient
4988
5145
  * failure (retried). Default: an error with `conflict === true` or the
4989
5146
  * undo concurrency tag. */
4990
5147
  readonly isConflict?: (error: unknown) => boolean;
4991
5148
  readonly idFor?: () => string;
5149
+ /** Milliseconds before a transiently failed write is retried, after
5150
+ * `attempts` failures. Default {@link defaultOutboxRetryDelay}. Going online
5151
+ * retries at once. */
5152
+ readonly retryDelay?: (attempts: number) => number;
5153
+ /** Stamp each enqueued write (`OutboxEntry.stamp`) — pass a hybrid logical
5154
+ * clock's `now` (`createHybridClock` in `@voltro/local-first`). */
5155
+ readonly stamp?: () => string;
4992
5156
  }
4993
5157
 
4994
5158
  /** The current subject's scopes (defaults to none if no provider). */