@voltro/client 0.70.0 → 0.71.1

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,1199 @@
1
+ import { ClientDescriptor } from '@voltro/protocol';
2
+ import { Effect } from 'effect';
3
+ import { Fiber } from 'effect';
4
+ import { ManagedRuntime } from 'effect';
5
+ import { Rpc } from '@effect/rpc';
6
+ import { RpcClient } from '@effect/rpc';
7
+ import { RpcClientError } from '@effect/rpc';
8
+ import { RpcGroup } from '@effect/rpc';
9
+ import * as Socket from '@effect/platform/Socket';
10
+ import { Stream } from 'effect';
11
+ import { SubscriptionEvent } from '@voltro/protocol';
12
+ import { TargetRelations } from '@voltro/protocol';
13
+
14
+ /** Erased per-api runtime boundary. Headless cache code must not import the
15
+ * React context (and its browser globals) merely to name this Effect type. */
16
+ export declare type AnyRuntime = ManagedRuntime.ManagedRuntime<never, never>;
17
+
18
+ export declare interface ApiHandle {
19
+ readonly runtime: AnyRuntime;
20
+ readonly cache: SubscriptionCache;
21
+ /** Resolved typed rpc client. Methods nest by tag (`todos.list` →
22
+ * `client.todos.list`). Hooks walk by tag-segment (see `resolveByTag`)
23
+ * to invoke, so the static type here is the erased `unknown`; the typed
24
+ * view comes from `useAppClient<T>(name)` at the call site. */
25
+ readonly client: unknown;
26
+ /** Per-rpc-tag descriptor metadata. Drives auto-optimistic and source-
27
+ * based cache routing. */
28
+ readonly descriptors: Readonly<Record<string, ClientDescriptor>>;
29
+ /**
30
+ * Base HTTP origin where the api's `/_voltro/inspect/*` endpoints
31
+ * live. Derived from `wsUrl` at mount time (`ws://host:port/ws` →
32
+ * `http://host:port`). DevTools and any inspect-consuming tooling
33
+ * use this for the metrics / subscriptions / events endpoints.
34
+ */
35
+ readonly inspectBaseUrl: string;
36
+ /** Per-api error bus. Mutations + subscription failures land here so
37
+ * app-level listeners can react to typed errors globally (auto-logout
38
+ * on `Unauthenticated`, network-error toasts, etc.). */
39
+ readonly errorBus: RpcErrorBus;
40
+ /** Stable UI/raw transport recovery state for this logical api. */
41
+ readonly recovery?: RecoveryCoordinator;
42
+ }
43
+
44
+ export declare interface AuthRefreshHandle {
45
+ /** Stop listening. */
46
+ readonly dispose: () => void;
47
+ /** Call when a request SUCCEEDS — it resets the consecutive counter, which is
48
+ * what tells "the refresh fixed it" from "we are looping against a refusal".
49
+ * Optional for correctness (the counter is a ceiling either way) and the
50
+ * difference between recovering three times a day and recovering three times
51
+ * ever. */
52
+ readonly noteSuccess: () => void;
53
+ }
54
+
55
+ export declare interface AuthRefreshOptions {
56
+ /** Minimum gap between two refreshes. Default 15s — comfortably longer than
57
+ * a reconnect + first snapshot, so one expiry produces one rebuild. */
58
+ readonly cooldownMs?: number;
59
+ /** Give up after this many refreshes with no successful call between them.
60
+ * Default 3. */
61
+ readonly maxConsecutive?: number;
62
+ /** Injected in tests. */
63
+ readonly now?: () => number;
64
+ }
65
+
66
+ /**
67
+ * Auto-apply target as seen from the client. Identical shape to the
68
+ * server's TargetSpec but with all schema generics erased (the client
69
+ * sees concrete row shapes at runtime, not Schema instances).
70
+ *
71
+ * Optional overrides:
72
+ * - `shape` for insert: build the row from input + optimistic id
73
+ * for update: build the patched row from (input, current)
74
+ * - `identify` for update/delete: extract the row id from input
75
+ * (defaults to `input.id`)
76
+ * - `order` for insert: 'prepend' (default) or 'append'
77
+ */
78
+ export declare interface AutoApplyTarget {
79
+ readonly table: string;
80
+ readonly op: 'insert' | 'update' | 'delete';
81
+ readonly order?: 'prepend' | 'append' | undefined;
82
+ readonly shape?: ((input: Record<string, unknown>, optimisticIdOrCurrent?: unknown) => Record<string, unknown>) | undefined;
83
+ readonly identify?: ((input: Record<string, unknown>) => string | ReadonlyArray<string>) | undefined;
84
+ /** Dot-path to a nested array WITHIN the query value (e.g.
85
+ * `'snapshot.projects'`). When set, the reducer patches that nested array at
86
+ * ITEM granularity instead of the top-level row array — for JSON array
87
+ * columns + computed/shaped query results. */
88
+ readonly path?: string | undefined;
89
+ /** Item key within the nested array (default `'id'`). Only with `path`. */
90
+ readonly by?: string | undefined;
91
+ /** Guard which cached entries to patch — only entries whose current (base)
92
+ * value satisfies this. Stops a patch bleeding across sibling subscriptions
93
+ * sharing a source table. */
94
+ readonly match?: ((value: unknown, input: Record<string, unknown>) => boolean) | undefined;
95
+ /** Nested-item shaper — the client uses this (not `shape`) to build/patch a
96
+ * nested-array item when `path` is set. Typed to the item, not the output.
97
+ * 2nd arg is the optimistic id (insert) or the current item (update). */
98
+ readonly shapeItem?: ((input: Record<string, unknown>, currentOrOptimisticId: unknown) => Record<string, unknown>) | undefined;
99
+ /** Declared many-to-many relations (`{ inputField: { junction, anchorColumn,
100
+ * targetColumn } }`). Drives JUNCTION auto-optimistic: entries sourced on the
101
+ * junction table get their link rows for this anchor reconciled against
102
+ * `input[inputField]` immediately, instead of waiting for the server delta
103
+ * while every scalar field of the same form has already flipped. */
104
+ readonly relations?: TargetRelations | undefined;
105
+ }
106
+
107
+ /**
108
+ * Build one api's runtime + rpc client + subscription cache over a WebSocket.
109
+ *
110
+ * The returned `runtime` owns the socket; dispose it (`runtime.dispose()`, after
111
+ * `cache.destroy(runtime)`) to tear the connection down. A fresh cache is bound
112
+ * per resolved runtime — cross-runtime cache reuse is unsafe (its fibers
113
+ * reference the old runtime). Carrying the previous cache's DATA forward is a
114
+ * different thing and is safe: see `SubscriptionCache.seedStaleFrom`, which
115
+ * copies rows (never fibers) and is gated by the caller to same-subject swaps.
116
+ *
117
+ * Resolving this function means the rpc client exists; it does NOT prove the
118
+ * background socket loop has opened. Active subscription fibers that fail
119
+ * before a later `open` are resumed by the cache after the rpc protocol has
120
+ * cleared the previous transport error and marked that socket send-capable.
121
+ * Construction failures still reject and are left to the caller's supervisor.
122
+ */
123
+ export declare const buildApiRuntime: (options: BuildApiRuntimeOptions) => Promise<BuiltApiRuntime>;
124
+
125
+ export declare interface BuildApiRuntimeOptions {
126
+ /** Stable api name — used only to tag the client's Context. */
127
+ readonly name: string;
128
+ /** Supervisor transport generation; 0 for a standalone runtime. */
129
+ readonly generation?: number;
130
+ /** WebSocket URL of the api (`ws(s)://host:port/ws`). */
131
+ readonly wsUrl: string;
132
+ /**
133
+ * The api's rpc group, as the ERASED `RpcGroup.Any`.
134
+ *
135
+ * `RpcGroup` is declared `in out` in @effect/rpc — invariant on purpose — so a
136
+ * CONCRETE group (the `appGroup` codegen emits) is not assignable to
137
+ * `RpcGroup<Rpc.Any>`, and a boundary typed that way rejects the only value
138
+ * anyone ever passes it. This mirrors what `ApiHandle.client` already does:
139
+ * erase at the handle boundary, restore the types at the call site via
140
+ * `createHooks<T>()` / `useAppClient<T>()`. The concrete rpc types are
141
+ * irrelevant to building a transport — they matter to the caller, not here.
142
+ */
143
+ readonly group: RpcGroup.Any;
144
+ /** Per-connection auth headers (see {@link ResolvableHeaders}). */
145
+ readonly headers?: ResolvableHeaders | undefined;
146
+ /** How to construct a WebSocket. Web wraps `globalThis.WebSocket` with
147
+ * tracking + a connect-timeout; RN passes a plain `globalThis.WebSocket`.
148
+ * Injected so this module touches no environment global directly. */
149
+ readonly webSocketConstructor: (url: string, protocols?: string | ReadonlyArray<string>) => globalThis.WebSocket;
150
+ /**
151
+ * Error channel owned by the logical api mount. A reconnect supervisor passes
152
+ * the SAME instance to every transport generation so a failure emitted by the
153
+ * outgoing socket can be cleared by a success from the replacement socket.
154
+ * Omit only when building a standalone, unsupervised runtime.
155
+ */
156
+ readonly errorBus?: RpcErrorBus;
157
+ readonly recovery?: RecoveryCoordinator;
158
+ }
159
+
160
+ export declare type BuildClient = (api: MountedApi, generation: number, onSocketOpen: () => void, onSocketIssue: (kind: SocketIssueKind) => void,
161
+ /** Stable for this logical api across every transport generation. */
162
+ errorBus?: RpcErrorBus, recovery?: RecoveryCoordinator) => Promise<ResolvedClient>;
163
+
164
+ /** The transport-level pieces of one api's client stack. Combined with the
165
+ * api's descriptor map + inspect base URL, this is an `ApiHandle`. */
166
+ export declare interface BuiltApiRuntime {
167
+ readonly runtime: AnyRuntime;
168
+ readonly cache: SubscriptionCache;
169
+ readonly client: RpcClient.RpcClient<Rpc.Any, RpcClientError.RpcClientError>;
170
+ readonly errorBus: RpcErrorBus;
171
+ readonly recovery: RecoveryCoordinator;
172
+ }
173
+
174
+ declare interface CacheEntry {
175
+ readonly key: string;
176
+ /** First element of the keyArr — the rpc tag (e.g. 'todos.list'). Used
177
+ * by `forTag()` so callers can patch every sub-key for a tag without
178
+ * knowing the inputs. Captured at create-time so updates without a
179
+ * prior subscribe still work (stub entries get tag too). */
180
+ readonly tag: string | undefined;
181
+ state: EntryState<unknown>;
182
+ /** Retired stream callbacks must not mutate the replacement generation. */
183
+ generation: number;
184
+ /** Coalesce same-tick mutation ACKs into one causal read per entry. */
185
+ reconciliationScheduled: boolean;
186
+ /** Once this entry has read its own write, reconnects must not downgrade to
187
+ * a lagging replica. Same-subject replacements carry this bit with rows. */
188
+ primaryReads: boolean;
189
+ /** Subscriber re-render callbacks. */
190
+ subscribers: Set<() => void>;
191
+ /** Fiber running the underlying stream. */
192
+ fiber: Fiber.RuntimeFiber<unknown, unknown> | null;
193
+ /** The last fiber ended because the rpc transport failed. A later socket
194
+ * `open` re-issues active entries with their last-known-good base intact. */
195
+ resumeAfterTransportOpen: boolean;
196
+ recoveryPhase: 'steady' | 'awaiting-protocol' | 'awaiting-delivery' | 'stuck';
197
+ recoveryAttempt: number;
198
+ lastTransportFailureAt: number | undefined;
199
+ lastReissueAt: number | undefined;
200
+ lastDeliveryAt: number | undefined;
201
+ recoveryBasePreserved: boolean;
202
+ recoveryTimer: ReturnType<typeof setTimeout> | null;
203
+ /** Pending eviction (last subscriber gone, TTL countdown). */
204
+ evictionTimer: NodeJS.Timeout | null;
205
+ /** Source table(s) this entry reads (from the rpc descriptor). Used by
206
+ * auto-optimistic to find which entries to patch when a mutation with
207
+ * a matching `target.table` is invoked — an array matches if the target is
208
+ * among the listed tables. May be undefined for queries whose source isn't
209
+ * expressed as table(s) (joins, aggregates). */
210
+ source: string | ReadonlyArray<string> | undefined;
211
+ /** True once a server snapshot reported this query as COMPUTED (handler
212
+ * returns a shaped value, not a table row-set). Auto-optimistic skips
213
+ * blind INSERTs into computed entries — the client can't evaluate the
214
+ * query's opaque server-side filter to know if a new row belongs, so it
215
+ * defers to the authoritative recompute push. UPDATE/DELETE (matched by
216
+ * id) still apply. Defaults false until the first snapshot resolves it. */
217
+ computed: boolean;
218
+ /** Saved `fetch` thunk from the first subscribe(). Used by `refreshAll()`
219
+ * to re-issue the WS subscription after a connection-subject re-bind
220
+ * (e.g. soft re-auth after login). Each subscriber's hook keeps its
221
+ * own fetch closure, but only the first one's identity matters — the
222
+ * server-side subscription is one per cache-entry key, not per
223
+ * subscriber. */
224
+ fetch: (() => Stream.Stream<SubscriptionEvent<unknown>, unknown, never>) | null;
225
+ /** The runtime the saved `fetch` was forked against. Stored so a SINGLE entry
226
+ * can be re-issued without the whole-cache `refreshAll(runtime)` — the
227
+ * confirmed-patch resync needs exactly one, and threading a runtime down
228
+ * from a `setTimeout` is not available to it. */
229
+ runtime: AnyRuntime | null;
230
+ /** W3C trace id of the live stream, captured when the fiber starts.
231
+ * Shared with the server (the subscription span propagates it) and
232
+ * attached to error-bus events so a failure points at the right
233
+ * `voltro logs --trace <id>`. */
234
+ traceId?: string;
235
+ }
236
+
237
+ /** Plain-data snapshot of a single cache entry for devtools / test
238
+ * introspection. Doesn't carry the live fiber or React-subscriber
239
+ * set — those are kept private. */
240
+ export declare interface CacheEntrySnapshot {
241
+ readonly key: string;
242
+ readonly tag: string | undefined;
243
+ readonly source: string | ReadonlyArray<string> | undefined;
244
+ readonly subscriberCount: number;
245
+ /** True while the underlying stream's fiber is running. */
246
+ readonly hasFiber: boolean;
247
+ /** True after the last subscriber left and the eviction TTL is
248
+ * counting down — a quick remount within the window resurrects. */
249
+ readonly evicting: boolean;
250
+ /** Recovery of a transport-terminal stream, without exposing its input. */
251
+ readonly recovery: {
252
+ readonly phase: 'steady' | 'awaiting-protocol' | 'awaiting-delivery' | 'stuck';
253
+ readonly attempt: number;
254
+ readonly lastTransportFailureAt: number | undefined;
255
+ readonly lastReissueAt: number | undefined;
256
+ readonly lastDeliveryAt: number | undefined;
257
+ readonly basePreserved: boolean;
258
+ };
259
+ readonly snapshot: CacheSnapshot<unknown>;
260
+ }
261
+
262
+ export declare interface CacheSnapshot<T> {
263
+ /** Current visible data = base + all live patches applied in order. */
264
+ readonly data: T | undefined;
265
+ /** Most recent revision the server delivered. -1 if no snapshot yet. */
266
+ readonly revision: number;
267
+ /** Wall-clock ms when the most recent server delta was emitted; undefined for snapshots. */
268
+ readonly emittedAt: number | undefined;
269
+ /** Error from the underlying stream (if no snapshot has ever arrived). */
270
+ readonly error: unknown | undefined;
271
+ /** Number of live optimistic patches currently applied. */
272
+ readonly pendingPatches: number;
273
+ }
274
+
275
+ export declare const clearClientDiagnostics: () => void;
276
+
277
+ /**
278
+ * Per-rpc-tag metadata the client uses to route cache updates: what kind of
279
+ * procedure a tag is, which query it reads from, and which tables a mutation
280
+ * targets (driving auto-optimistic updates). Produced by codegen.
281
+ *
282
+ * It is the CANONICAL `ClientDescriptor` from `@voltro/protocol`, not a
283
+ * structural copy of it. The copy that used to live here narrowed `source` to a
284
+ * single string while the real descriptor allows several — so a generated
285
+ * `appDescriptors` did not fit the type the client declared for it. Nothing
286
+ * caught that: the only place the two meet is a GENERATED entry, and no harness
287
+ * typechecks a generated entry.
288
+ */
289
+ export declare type ClientDescriptorMap = Readonly<Record<string, ClientDescriptor>>;
290
+
291
+ export declare interface ClientDiagnosticEvent {
292
+ readonly sequence: number;
293
+ readonly at: number;
294
+ readonly elapsedMs: number;
295
+ readonly api: string;
296
+ readonly kind: ClientDiagnosticKind;
297
+ readonly fields: Readonly<Record<string, ClientDiagnosticValue>>;
298
+ }
299
+
300
+ 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';
301
+
302
+ export declare interface ClientDiagnosticsSnapshot {
303
+ readonly version: 1;
304
+ readonly generatedAt: number;
305
+ readonly sessionStartedAt: number;
306
+ readonly persisted: boolean;
307
+ readonly dropped: number;
308
+ readonly events: ReadonlyArray<ClientDiagnosticEvent>;
309
+ /**
310
+ * Per api, the fields of its last `runtime.resolved` — `scheduler`,
311
+ * `generation` — kept OUTSIDE the ring. That event is recorded when the
312
+ * runtime is built, which makes it one of the first of a session, and the
313
+ * first events are exactly what a `clear()` before a measurement or the
314
+ * ring's eviction removes: an export taken after either carried every
315
+ * reconnect event and no statement about which scheduler produced them. This
316
+ * describes the runtime, not the timeline, so `clear()` leaves it in place.
317
+ */
318
+ readonly runtime: Readonly<Record<string, Readonly<Record<string, ClientDiagnosticValue>>>>;
319
+ }
320
+
321
+ export declare const clientDiagnosticsSnapshot: (api?: string) => ClientDiagnosticsSnapshot;
322
+
323
+ export declare type ClientDiagnosticValue = string | number | boolean | null;
324
+
325
+ export declare interface ClientErrorEvent {
326
+ /** The thrown value (Error | anything). */
327
+ readonly error: unknown;
328
+ /**
329
+ * Where it came from.
330
+ *
331
+ * `route` — caught by the framework's route ErrorBoundary (render OR loader).
332
+ * `manual` — app called a capture helper.
333
+ * `rpc.*` — a call that failed in the CLIENT, forwarded from the rpc error
334
+ * bus. Kept as three separate labels rather than one `rpc`, because they are
335
+ * different incidents to whoever reads the report: a failed mutation is a
336
+ * write the user watched fail, while a failed subscription is a screen that
337
+ * silently never filled — `data: undefined`, `loading: false`, an empty list
338
+ * that reads as "there is nothing here". Collapsing them makes the second
339
+ * unfindable, and the second is the expensive one.
340
+ */
341
+ readonly source: 'route' | 'manual' | 'rpc.mutation' | 'rpc.action' | 'rpc.subscription';
342
+ /** React component stack, when the route boundary caught a render error. */
343
+ readonly componentStack?: string;
344
+ /** Active pathname at the time, for context. */
345
+ readonly pathname?: string;
346
+ /** Optional caller-supplied extra context (manual captures). */
347
+ readonly context?: Record<string, unknown>;
348
+ }
349
+
350
+ declare type ClientErrorListener = (event: ClientErrorEvent) => void;
351
+
352
+ export declare interface ClientTraceEvent {
353
+ /** W3C trace id (32 hex) of the call the client just started. */
354
+ readonly traceId: string;
355
+ /** W3C span id (16 hex) of the client span — the parent the server
356
+ * continues from. Lets a vendor integration correlate browser work to the
357
+ * server trace without changing the browser span's page-owned parent. */
358
+ readonly spanId: string;
359
+ /** `'mutation'` | `'action'` | `'subscription'` — which surface started it. */
360
+ readonly source: 'mutation' | 'action' | 'subscription';
361
+ /** RPC tag (e.g. `'todos.create'`). */
362
+ readonly tag: string;
363
+ }
364
+
365
+ declare type ClientTraceListener = (event: ClientTraceEvent) => void;
366
+
367
+ /** One physical socket attempt inside one runtime, including in-place retries. */
368
+ declare interface ConnectionAttempt {
369
+ readonly open: () => ConnectionLease | undefined;
370
+ readonly close: () => void;
371
+ }
372
+
373
+ /** Local lifetime, never a server connection id or an authorization grant. */
374
+ declare interface ConnectionLease {
375
+ readonly signal: AbortSignal;
376
+ }
377
+
378
+ /**
379
+ * A runtime can exist before its socket opens, and can reopen without being
380
+ * replaced. Only the protocol-ready callback grants a lease; leaving runRaw
381
+ * revokes it on success, failure, or interruption. A logical API's health is
382
+ * deliberately not an input: outgoing and replacement runtimes share health.
383
+ */
384
+ declare class ConnectionScope {
385
+ #private;
386
+ readonly getSnapshot: () => ConnectionLease | undefined;
387
+ readonly subscribe: (listener: () => void) => (() => void);
388
+ begin(): ConnectionAttempt;
389
+ }
390
+
391
+ declare interface EntryState<T> {
392
+ /** Last server-delivered data (base for patches). */
393
+ base: T | undefined;
394
+ baseRevision: number;
395
+ baseEmittedAt: number | undefined;
396
+ baseError: unknown | undefined;
397
+ patches: Array<OptimisticPatch<T>>;
398
+ /** Cached optimistic snapshot — invalidated on every state change so
399
+ * `getSnapshot` returns a stable reference between mutations. */
400
+ cachedSnapshot: CacheSnapshot<T> | null;
401
+ }
402
+
403
+ export declare interface FrameworkRuntimes {
404
+ /** Look up an api handle (runtime + cache) by name. Throws if no such api was mounted. */
405
+ readonly get: (name: string) => ApiHandle;
406
+ /** Enumerate the names of currently-installed apis (for debug). */
407
+ readonly names: ReadonlyArray<string>;
408
+ /**
409
+ * "Something in this tree needs `apiName`."
410
+ *
411
+ * Under `web.api.connect: 'lazy'` the provider does not open a socket until
412
+ * this is called, so a page that reads no data never opens one. Under the
413
+ * default `'eager'` it is a no-op — every api connects at mount, as before.
414
+ *
415
+ * It exists because the alternative was worse in a specific, measured way:
416
+ * `interactive: 'full'` is the DEFAULT render mode, and the client opened a
417
+ * WebSocket on every such page whether or not it subscribed. A pre-rendered
418
+ * documentation page with no data at all opened one (measured in a real
419
+ * browser: 0 sockets on `interactive: 'none'` / `'islands'`, one on `'full'`).
420
+ * And an open socket keeps a dormancy-managed instance awake — `isIdleNow`
421
+ * returns false while `connectedClients() > 0` — so one browser tab on a
422
+ * pricing page prevented scale-to-zero indefinitely.
423
+ *
424
+ * Optional so a foreign host embedding `FrameworkRuntimesContext` by hand
425
+ * keeps working; absent means "already connected", which is the safe reading.
426
+ */
427
+ readonly demand?: (apiName: string) => void;
428
+ }
429
+
430
+ /**
431
+ * The snapshot a coordinator has at construction, frozen and shared.
432
+ *
433
+ * This is what `useSyncExternalStore` must hand back as the SERVER snapshot, and
434
+ * the reason is a defect the browser checks caught the first time they ran: the
435
+ * hook passed `getSnapshot` for both arguments, so the server rendered whatever
436
+ * the LIVE coordinator held at that instant while the client's hydration render
437
+ * read a coordinator that had already progressed. React reports that as
438
+ * "server rendered text didn't match the client" — a console error in a browser
439
+ * and nowhere else, on any SSR page rendering a connection status.
440
+ *
441
+ * One frozen object rather than a factory: `getServerSnapshot` must return a
442
+ * stable REFERENCE or React re-renders forever looking for a fixed point.
443
+ */
444
+ export declare const INITIAL_RECOVERY_SNAPSHOT: RecoverySnapshot;
445
+
446
+ /** Is this the framework's `Unauthenticated`? Matched on `_tag`, the wire
447
+ * contract, rather than on an instance — the error crosses a package boundary
448
+ * and may be re-created by the decoder. */
449
+ export declare const isUnauthenticated: (error: unknown) => boolean;
450
+
451
+ /**
452
+ * Non-fetching cache used as a LOADING baseline:
453
+ * - during SSR (no runtime / no provider), and
454
+ * - on the client's first render(s) before the api supervisor has
455
+ * resolved a configured api's runtime + client.
456
+ *
457
+ * It subclasses the real cache so it carries the FULL method surface
458
+ * (`peek` / `peekAll` / `update` / `forTag` / `refreshAll` / …) — a
459
+ * hand-rolled partial stub broke the moment a deployment (e.g. devtools)
460
+ * called a method it didn't implement. The ONLY override is `subscribe`:
461
+ * it must NOT open a real stream, because the supplied runtime is a stub
462
+ * that can't fork fibers. It hands back an empty snapshot so the component
463
+ * renders its loading state; when the real client resolves, FrameworkBoot
464
+ * swaps in the real cache and the component re-subscribes for live data.
465
+ * Every other inherited method operates on an always-empty entry map, so
466
+ * they're inherently safe no-ops.
467
+ */
468
+ export declare class LoadingSubscriptionCache extends SubscriptionCache {
469
+ subscribe(keyArr: ReadonlyArray<unknown>, _fetch: () => Stream.Stream<SubscriptionEvent<unknown>, unknown, never>, _runtime: AnyRuntime, _onChange: () => void, _options?: {
470
+ readonly source?: string | ReadonlyArray<string>;
471
+ }): {
472
+ readonly getSnapshot: () => CacheSnapshot<unknown>;
473
+ readonly unsubscribe: () => void;
474
+ };
475
+ }
476
+
477
+ /**
478
+ * One api the client is mounted against: its name, its typed rpc surface, its
479
+ * descriptor map and where to connect.
480
+ *
481
+ * `headers` are sent in the per-request MESSAGE frame, NOT the WebSocket
482
+ * upgrade — a browser cannot set upgrade headers — so the server's
483
+ * AuthMiddleware sees them on every call, which is what lets a cross-origin api
484
+ * authenticate WS subscriptions. A thunk is resolved per runtime build;
485
+ * refreshAuth() rebuilds after token rotation. Socket retries within that
486
+ * runtime retain the current headers.
487
+ */
488
+ export declare interface MountedApi {
489
+ readonly name: string;
490
+ /** Erased — see `BuildApiRuntimeOptions.group` for why an invariant
491
+ * `RpcGroup<Rpc.Any>` cannot hold a generated `appGroup`. */
492
+ readonly group: RpcGroup.Any;
493
+ readonly descriptors: ClientDescriptorMap;
494
+ readonly wsUrl: string;
495
+ readonly headers?: ResolvableHeaders | undefined;
496
+ readonly recovery?: RecoveryOptions | undefined;
497
+ }
498
+
499
+ export declare interface MutationReplayReservation {
500
+ /** Re-check immediately before sending: identity, capability and transport may have changed while waiting. */
501
+ readonly isValid: () => boolean;
502
+ /** Release the bounded pending slot. Safe to call more than once. */
503
+ readonly release: () => void;
504
+ }
505
+
506
+ declare interface OptimisticPatch<T = unknown> {
507
+ readonly id: string;
508
+ readonly mutationId: string;
509
+ readonly reducer: (current: T) => T;
510
+ /** A successful write stays previewed until a matching post-ACK primary
511
+ * snapshot supersedes it. A different write's delta proves nothing. */
512
+ confirmed?: boolean;
513
+ }
514
+
515
+ /** Publish a client error. Cheap + sync; a broken listener can't break the caller. */
516
+ export declare const publishClientError: (event: ClientErrorEvent) => void;
517
+
518
+ /** Publish a started client trace. Cheap + sync; safe on the hot path. */
519
+ export declare const publishClientTrace: (event: ClientTraceEvent) => void;
520
+
521
+ export declare type RawTransportStatus = 'connected' | 'disconnected';
522
+
523
+ /** Record one payload-free transition. Safe to call on every production path. */
524
+ export declare const recordClientDiagnostic: (api: string, kind: ClientDiagnosticKind, fields?: Readonly<Record<string, ClientDiagnosticValue | undefined>>) => ClientDiagnosticEvent;
525
+
526
+ /**
527
+ * State owned by one logical API, not by one socket or one React hook.
528
+ *
529
+ * Raw listeners (`RpcErrorBus.on`) still receive every failure immediately.
530
+ * Presentation listeners receive non-transport failures immediately, but at
531
+ * most one transport failure per outage and only after the grace window. A
532
+ * fully healed gap therefore leaves no toast/banner flash while diagnostics
533
+ * retain the complete sequence.
534
+ */
535
+ export declare class RecoveryCoordinator {
536
+ #private;
537
+ constructor(apiName: string, options?: RecoveryOptions, scheduler?: Partial<RecoveryScheduler>);
538
+ get options(): ResolvedRecoveryOptions;
539
+ /** Ends on login/logout, tenant change or API disposal, not ordinary reconnect. */
540
+ get subjectSignal(): AbortSignal;
541
+ getSnapshot: () => RecoverySnapshot;
542
+ /** The SSR / hydration snapshot — see INITIAL_RECOVERY_SNAPSHOT. Stable by
543
+ * reference, so both renders agree and React swaps to the live one after. */
544
+ getServerSnapshot: () => RecoverySnapshot;
545
+ subscribe: (listener: () => void) => (() => void);
546
+ onVisibleError(listener: RpcErrorListener): () => void;
547
+ /** Called from the socket seam before request fibers report their errors. */
548
+ transportIssue(): void;
549
+ /** Called only after the rpc protocol has cleared its previous transport error. */
550
+ protocolReady(): void;
551
+ observeError(error: RpcError): void;
552
+ observeSuccess(success: RpcSuccess): void;
553
+ reportExternalSuccess(): void;
554
+ /** Discard every stale row/replay/health fact at the subject boundary. */
555
+ resetForSubjectChange(minimumCapabilityGeneration?: number): void;
556
+ setMutationReplaySupported(supported: boolean, generation?: number): void;
557
+ /**
558
+ * Wait for the capability probe when transport fails during initial boot.
559
+ * Unknown is never permission: the wait is bounded by the replay window and
560
+ * resolves false if the server never proves that idempotency is active.
561
+ */
562
+ /** What is left of the replay window for a mutation that started at `startedAt`. */
563
+ replayWindowRemaining(startedAt: number): number;
564
+ waitForMutationReplaySupport(startedAt: number): Promise<boolean>;
565
+ /**
566
+ * Reserve one bounded waiting/replay slot; caller MUST release the returned
567
+ * reservation. An unknown capability may reserve while its probe is in flight,
568
+ * otherwise that short boot window would permit an unbounded waiter set.
569
+ * Disabled is final for the current generation and refuses immediately.
570
+ */
571
+ reserveMutationReplay(startedAt: number): MutationReplayReservation | undefined;
572
+ waitForProtocolReady(startedAt: number): Promise<boolean>;
573
+ dispose(): void;
574
+ }
575
+
576
+ /** Stable fallback for hand-built ApiHandles that provide only an error bus. */
577
+ export declare const recoveryCoordinatorFor: (errorBus: RpcErrorBus, apiName: string, options?: RecoveryOptions) => RecoveryCoordinator;
578
+
579
+ export declare interface RecoveryOptions {
580
+ /** Hide a transport gap from the UI while recovery is still plausible. */
581
+ readonly graceMs?: number;
582
+ /** Socket reconnect timing, independent of the presentation grace window. */
583
+ readonly retry?: RecoveryRetryOptions;
584
+ /** Maximum mutations allowed to wait for one safe replay at once. */
585
+ readonly maxPendingMutations?: number;
586
+ /** Maximum age of a mutation before an automatic replay is refused. */
587
+ readonly replayWindowMs?: number;
588
+ /**
589
+ * Explicit HTTP endpoint for runtime capability discovery. Usually omitted:
590
+ * the client derives a sibling of the WebSocket path. Set this only when an
591
+ * edge routes the WebSocket and ordinary HTTP through unrelated paths.
592
+ */
593
+ readonly capabilitiesUrl?: string;
594
+ }
595
+
596
+ export declare type RecoveryPresentationStatus = 'connected' | 'recovering' | 'degraded';
597
+
598
+ /** Delays after failed socket attempts; the first connection is always immediate. */
599
+ export declare interface RecoveryRetryOptions {
600
+ /** First retry delay in ms (default 0). Clamped to 0–maxMs. */
601
+ readonly initialMs?: number;
602
+ /** Second retry delay in ms (default 500). Clamped to 50–maxMs. */
603
+ readonly thenMs?: number;
604
+ /** Multiplier after the second retry (default 1.5). Clamped to 1–10. */
605
+ readonly factor?: number;
606
+ /** Maximum retry delay in ms (default 5000). Clamped to 50–60000. */
607
+ readonly maxMs?: number;
608
+ }
609
+
610
+ declare interface RecoveryScheduler {
611
+ readonly now: () => number;
612
+ readonly setTimeout: (callback: () => void, ms: number) => unknown;
613
+ readonly clearTimeout: (handle: unknown) => void;
614
+ }
615
+
616
+ export declare interface RecoverySnapshot {
617
+ readonly rawTransport: RawTransportStatus;
618
+ readonly status: RecoveryPresentationStatus;
619
+ readonly failureCount: number;
620
+ readonly lastFailureAt: number | undefined;
621
+ readonly failedSubscriptions: ReadonlyArray<string>;
622
+ readonly pendingMutationReplays: number;
623
+ readonly mutationReplay: 'unknown' | 'enabled' | 'disabled';
624
+ }
625
+
626
+ /** Keep cause-channel evidence beside an error without mutating the public
627
+ * value. `runRpcPromise` uses this before throwing a squashed Cause so the hook
628
+ * can distinguish a declared failure from an opaque defect. */
629
+ export declare const rememberRpcErrorKind: (error: unknown, kind: RpcErrorKind) => unknown;
630
+
631
+ /** Report an error to every subscribed reporter (e.g. Sentry). Safe no-op
632
+ * when nothing is subscribed. The ergonomic manual-capture entry point —
633
+ * call it from a try/catch in an event handler, an async effect, anywhere
634
+ * the route boundary won't catch the throw. */
635
+ export declare const reportClientError: (error: unknown, context?: Record<string, unknown>) => void;
636
+
637
+ /** Auth headers attached to every rpc MESSAGE frame, resolved per runtime
638
+ * build. In-place socket retries retain them; call refreshAuth() to rebuild
639
+ * after rotating a token, or reconnect() when the subject changes. */
640
+ export declare type ResolvableHeaders = Readonly<Record<string, string>> | (() => Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>);
641
+
642
+ export declare const resolveByTag: (client: unknown, tag: string) => unknown;
643
+
644
+ export declare interface ResolvedClient {
645
+ readonly runtime: AnyRuntime;
646
+ readonly cache: SubscriptionCache;
647
+ readonly client: RpcClient.RpcClient<Rpc.Any, RpcClientError.RpcClientError>;
648
+ readonly errorBus?: RpcErrorBus;
649
+ readonly recovery?: RecoveryCoordinator;
650
+ }
651
+
652
+ export declare interface ResolvedRecoveryOptions {
653
+ readonly graceMs: number;
654
+ readonly retry: Required<RecoveryRetryOptions>;
655
+ readonly maxPendingMutations: number;
656
+ readonly replayWindowMs: number;
657
+ readonly capabilitiesUrl: string | undefined;
658
+ }
659
+
660
+ export declare const resolveRecoveryOptions: (options?: RecoveryOptions) => ResolvedRecoveryOptions;
661
+
662
+ /** What the client can prove about a unary call's server-side result. */
663
+ export declare type RpcCallOutcome = 'not-applicable' | 'not-started' | 'known' | 'unknown';
664
+
665
+ export declare interface RpcError {
666
+ /** Source — `'mutation'` for transactional unary calls, `'action'` for
667
+ * non-transactional unary calls, `'subscription'` for streams. */
668
+ readonly source: 'mutation' | 'action' | 'subscription';
669
+ /** RPC tag (e.g. `'orgs.create'`, `'projects.list'`). */
670
+ readonly tag: string;
671
+ /** The raw error value. May be a Schema.TaggedError instance, a plain
672
+ * Error, an unknown thrown value. Pattern-match on `_tag` for typed errors. */
673
+ readonly error: unknown;
674
+ /** Failure origin. Use `transport` for connection-level UX; `handler` means
675
+ * the rpc returned a declared failure; `client` is framework work that
676
+ * failed locally; `unknown` is deliberately unclassified. */
677
+ readonly kind: RpcErrorKind;
678
+ /** False when the native caller proves this transport failure belongs to an
679
+ * ended physical attempt. The call still failed (and may have committed),
680
+ * but it must not mark the replacement socket down. Omitted preserves the
681
+ * conservative fallback for emitters without native lifetime evidence. */
682
+ readonly affectsTransport?: boolean;
683
+ /** A transport failure after a unary request started is `unknown`: the
684
+ * server may have committed before the response disappeared. */
685
+ readonly outcome?: RpcCallOutcome;
686
+ /** Trace id of the CLIENT call span. When the server accepted the request,
687
+ * @effect/rpc propagates this same id into its span. A transport failure may
688
+ * happen before that, so the id is not proof that server logs exist. Present
689
+ * only when a client span was active. */
690
+ readonly traceId?: string;
691
+ }
692
+
693
+ export declare class RpcErrorBus {
694
+ #private;
695
+ /** Subscribe. Returns an unsubscribe function. */
696
+ on(listener: RpcErrorListener): () => void;
697
+ /** Emit. Pipeline code (useMutation / subscriptionCache) calls this. */
698
+ emit(event: RpcError): void;
699
+ /**
700
+ * Subscribe to SUCCESSES — the channel that makes a consecutive-failure
701
+ * ceiling mean what it says.
702
+ *
703
+ * ── Why the bus grew a second channel ──────────────────────────────────
704
+ *
705
+ * `wireAuthRefresh` bounds how often it may rebuild the transport on
706
+ * `Unauthenticated`, and `maxConsecutive` bounds the TOTAL — after that many
707
+ * refreshes *with no successful call in between*, it stops and leaves the
708
+ * error to the app, because at that point the credential is not stale, it is
709
+ * refused. "With no successful call in between" was carried by
710
+ * `AuthRefreshHandle.noteSuccess()`, a method the HOST had to remember to
711
+ * call, and the only host never called it.
712
+ *
713
+ * What that turns the ceiling into is the part worth writing down: not a
714
+ * loop, but a LIFETIME budget. A tab that rotates its token three times over
715
+ * a few hours exhausts it and then never refreshes again for as long as it
716
+ * stays open — every later expiry rejects every subscription it opens, each
717
+ * rejected entry is terminal for its transport, and the screen waits on a
718
+ * spinner that has nothing left to wait for.
719
+ *
720
+ * A host that must remember something will eventually not, which is the
721
+ * shape this repo keeps meeting. So the signal comes from the pipeline that
722
+ * already knows — the same one that emits the errors — and no host has to
723
+ * wire anything. `noteSuccess()` stays for a host with a better signal of its
724
+ * own; it is no longer what the policy depends on.
725
+ */
726
+ onSuccess(listener: RpcSuccessListener): () => void;
727
+ /** Emit a success. Called by the same pipeline code that calls `emit`. */
728
+ emitSuccess(event: RpcSuccess): void;
729
+ }
730
+
731
+ /** Where the failure originated, classified only as far as the client can
732
+ * prove. In particular, `transport` does NOT mean the server definitely saw
733
+ * nothing: a connection can disappear after a request was accepted but before
734
+ * its response reached the browser. */
735
+ export declare type RpcErrorKind = 'transport' | 'handler' | 'client' | 'unknown';
736
+
737
+ /**
738
+ * Classify an error whose pipeline location is already known.
739
+ *
740
+ * `RpcClientError` is @effect/rpc's transport failure value. Detect it through
741
+ * its global TypeId instead of `instanceof`: a browser bundle can contain more
742
+ * than one physical package copy, while the `Symbol.for` marker remains stable.
743
+ * Everything else keeps the caller's evidence-based fallback — this helper
744
+ * never guesses whether an opaque error came from a handler or local client
745
+ * work.
746
+ */
747
+ export declare const rpcErrorKind: (error: unknown, fallback: Exclude<RpcErrorKind, "transport">) => RpcErrorKind;
748
+
749
+ export declare type RpcErrorListener = (event: RpcError) => void;
750
+
751
+ /** A call that SUCCEEDED. Carries only its source and tag — there is no payload
752
+ * here on purpose: this channel exists so cross-cutting policy can tell
753
+ * "working again" from "still broken", not so listeners can read data. */
754
+ export declare interface RpcSuccess {
755
+ readonly source: 'mutation' | 'action' | 'subscription';
756
+ readonly tag: string;
757
+ }
758
+
759
+ export declare type RpcSuccessListener = (event: RpcSuccess) => void;
760
+
761
+ /**
762
+ * Run an rpc effect on an api's runtime and resolve it to a promise that
763
+ * rejects with the FAILURE VALUE ITSELF — the typed error the server declared
764
+ * — instead of Effect's `FiberFailure` wrapper.
765
+ *
766
+ * Every write-side hook (`useMutation`, `useAction`, `useWorkflow`,
767
+ * `useUpload`) goes through here, so `err._tag` means the same thing on both
768
+ * sides of the client.
769
+ */
770
+ export declare const runRpcPromise: <A>(runtime: AnyRuntime, effect: Effect.Effect<A, unknown, never>) => Promise<A>;
771
+
772
+ export declare type SocketIssueKind = 'close' | 'error' | 'connect-timeout';
773
+
774
+ /**
775
+ * Stable, deterministic string for an arbitrary key array. Object keys
776
+ * sort recursively so `{a:1,b:2}` and `{b:2,a:1}` map to the same string.
777
+ * Arrays preserve order (it matters). Used as the cache's `Map` key.
778
+ */
779
+ export declare const stableKey: (key: ReadonlyArray<unknown>) => string;
780
+
781
+ /**
782
+ * Spawn the per-api connect + reconnect supervisor.
783
+ *
784
+ * Returns a handle whose `dispose()` cancels everything pending and
785
+ * disposes every live ResolvedClient. Calling dispose() twice is safe.
786
+ */
787
+ export declare const startApiSupervisor: (options: SupervisorOptions) => SupervisorHandle;
788
+
789
+ export declare const subscribeClientDiagnostics: (listener: () => void) => (() => void);
790
+
791
+ /** Subscribe to client errors. Returns an unsubscribe fn. */
792
+ export declare const subscribeClientErrors: (listener: ClientErrorListener) => (() => void);
793
+
794
+ /** Subscribe to started client traces. Returns an unsubscribe fn. */
795
+ export declare const subscribeClientTraces: (listener: ClientTraceListener) => () => void;
796
+
797
+ export declare class SubscriptionCache {
798
+ private readonly entries;
799
+ private readonly refreshing;
800
+ /**
801
+ * Same-subject runtime replacement. A mutation may settle against the cache
802
+ * it started on after React has already switched to the replacement cache.
803
+ * Keep this link one-way so staging and settlement follow the visible data
804
+ * without retaining an old cache from the new runtime.
805
+ */
806
+ private successor;
807
+ private readonly inactiveTtlMs;
808
+ private readonly onChangeHook;
809
+ private readonly errorBus;
810
+ private readonly mirror;
811
+ private readonly mergeCell;
812
+ private readonly apiName;
813
+ private readonly recoveryStuckMs;
814
+ constructor(options?: SubscriptionCacheOptions);
815
+ private diagnose;
816
+ /**
817
+ * Register a subscriber. The cache forks the underlying fiber on the
818
+ * first subscriber and re-uses it for the rest. Returns the snapshot
819
+ * getter, the per-subscriber notify-on-change hook, and an unsubscribe
820
+ * function.
821
+ *
822
+ * `fetch` is invoked once per live stream attempt (it builds the Effect
823
+ * Stream against the runtime). Concurrent subscribers piggy-back on that
824
+ * stream; a transport recovery may invoke it again to replace the terminal
825
+ * fiber left by the failed socket.
826
+ */
827
+ subscribe(keyArr: ReadonlyArray<unknown>, fetch: () => Stream.Stream<SubscriptionEvent<unknown>, unknown, never>, runtime: AnyRuntime, onChange: () => void, options?: {
828
+ readonly source?: string | ReadonlyArray<string>;
829
+ }): {
830
+ readonly getSnapshot: () => CacheSnapshot<unknown>;
831
+ readonly unsubscribe: () => void;
832
+ };
833
+ /**
834
+ * Stage an optimistic patch against `keyArr`. Subscribers see the
835
+ * patched value on the next snapshot read. Returns a handle for manual
836
+ * revert (the canonical revert is via `revertByMutation` once the
837
+ * mutation resolves).
838
+ *
839
+ * If the entry doesn't exist yet (mutation fires before its
840
+ * subscription mounts — uncommon but possible), we create a stub entry
841
+ * with no fiber. When a subscription later mounts for the same key,
842
+ * the patch is preserved and the fiber is forked normally.
843
+ */
844
+ update<T>(keyArr: ReadonlyArray<unknown>, reducer: (current: T) => T, mutationId: string): {
845
+ readonly revert: () => void;
846
+ readonly patchId: string;
847
+ };
848
+ /**
849
+ * Patch every cached entry whose rpc tag matches `tag`, regardless of
850
+ * the input the subscription was opened with. The escape hatch for
851
+ * sourceless queries — joins, aggregates, custom-projection routes —
852
+ * that the auto-optimistic source-router can't reach.
853
+ *
854
+ * Usage from `.withOptimistic`:
855
+ *
856
+ * create.withOptimistic((cache, input) => {
857
+ * cache.forTag('todos.summary', (current) => ({
858
+ * ...(current as { count: number }),
859
+ * count: (current as { count: number }).count + 1,
860
+ * }))
861
+ * })
862
+ *
863
+ * Returns the number of entries that were patched, so callers can warn
864
+ * if zero entries matched (probably means the tag is misspelt).
865
+ */
866
+ forTag<T>(tag: string, reducer: (current: T) => T, mutationId: string): {
867
+ readonly patchedCount: number;
868
+ };
869
+ /** Drop every patch owned by `mutationId` from EVERY entry. */
870
+ revertByMutation(mutationId: string): void;
871
+ /**
872
+ * Mark a SUCCEEDED mutation's optimistic patches as confirmed. Unlike
873
+ * `revertByMutation` (used on failure), this does NOT drop them — they stay
874
+ * visible until a matching post-ACK primary snapshot replaces `base`.
875
+ * This removes the on→off→on flash where dropping the patch on mutation
876
+ * resolve briefly exposes a stale base before the server delta lands.
877
+ */
878
+ confirmByMutation(mutationId: string): void;
879
+ /**
880
+ * The confirmed-patch window expired: a committed write never got its
881
+ * superseding server event. Re-issue the affected subscriptions instead of
882
+ * discarding the write's preview.
883
+ *
884
+ * Three things are load-bearing, and each was a way to reintroduce the bug:
885
+ *
886
+ * - **The patch is KEPT across the resync.** `refreshAll` already
887
+ * establishes that shape ("the new base snapshot will land on top of
888
+ * them"). Clearing it here would be the revert again, wearing a longer
889
+ * word.
890
+ * - **A stub entry — no `fetch`, no `runtime` — is left ALONE.** There is
891
+ * nothing to re-issue, and the only other option is to show a base the
892
+ * client knows is stale. Keeping the patch is the honest state.
893
+ * - **It is LOUD.** The reporter found the jump only by reading minified
894
+ * source, because in the UI it is indistinguishable from "the server did
895
+ * not save it" — and that is the false trail they followed first. This
896
+ * goes to the error bus, so it reaches `voltro logs` rather than only a
897
+ * console nobody has open.
898
+ *
899
+ * No second timer is armed: this runs once per mutation, from the one
900
+ * `confirmByMutation` scheduled it, so a server that never echoes cannot put
901
+ * the client into a resync loop.
902
+ */
903
+ private resyncUnechoedMutation;
904
+ /**
905
+ * Auto-derive optimistic patches from a mutation's declared target(s).
906
+ * Iterates every cache entry whose `source` table matches a target's
907
+ * table; applies the canonical patch for the op:
908
+ *
909
+ * - insert : prepend (or append) a row derived from input + an
910
+ * `optimistic: true` flag + a generated id.
911
+ * - update : replace the row whose id matches `input.id` (or the
912
+ * custom identify fn from the spec) by merging input
913
+ * fields on top of the current row.
914
+ * - delete : filter out the row whose id matches `input.id`.
915
+ *
916
+ * Specs with a custom `shape`/`identify`/`order` function override
917
+ * these defaults. All patches are tagged with `mutationId` for atomic
918
+ * revert.
919
+ */
920
+ autoApply(targets: ReadonlyArray<AutoApplyTarget>, input: Record<string, unknown>, mutationId: string): void;
921
+ /** Drop a specific patch by id. */
922
+ private revertPatch;
923
+ /**
924
+ * Read the current snapshot for a key WITHOUT subscribing. If the
925
+ * entry doesn't exist, returns the "empty" snapshot (data=undefined,
926
+ * revision=-1, no patches). Safe to call from `useSyncExternalStore`'s
927
+ * getSnapshot, which is invoked many times during a single render.
928
+ */
929
+ peek(keyArr: ReadonlyArray<unknown>): CacheSnapshot<unknown>;
930
+ /** Test / debug helper. */
931
+ getEntry(keyArr: ReadonlyArray<unknown>): CacheEntry | undefined;
932
+ /** Test / debug helper. */
933
+ size(): number;
934
+ /**
935
+ * Devtools introspection: snapshot every cache entry's wire state +
936
+ * metadata. Returns plain data (no live references) so consumers can
937
+ * render without worrying about React state-equality.
938
+ *
939
+ * The map is keyed by the cache's stable-key string (same one the
940
+ * fan-out invalidation uses). Entries appear in insertion order;
941
+ * sort at the call site if order matters.
942
+ */
943
+ peekAll(): ReadonlyArray<CacheEntrySnapshot>;
944
+ /** Tear down every entry (used on runtime dispose). */
945
+ destroy(runtime: AnyRuntime): void;
946
+ /**
947
+ * Re-issue every active subscription against the runtime. Used after
948
+ * a soft re-auth (login on the same WebSocket connection) so the
949
+ * server resolves the new subject for each subscription's tenant
950
+ * scope — without dropping the connection.
951
+ *
952
+ * For each entry with a saved fetch:
953
+ * - interrupt the current fiber (stops the old WS subscription)
954
+ * - clear the base state so the next snapshot fully replaces it
955
+ * - re-fork via the saved fetch (new WS subscription with the
956
+ * server's now-current subject for this connection)
957
+ *
958
+ * Subscribers' `onChange` callbacks fire when the new snapshot
959
+ * lands, prompting React to re-render with the post-reauth data.
960
+ *
961
+ * Stub entries (no fetch saved yet) are left alone — they'll
962
+ * promote naturally on their next subscriber.
963
+ */
964
+ refreshAll(runtime: AnyRuntime): void;
965
+ /** Refresh one active query without clearing its visible data or optimistic
966
+ * patches. Coalesce refreshes until that request answers or fails; never
967
+ * interrupt an initial read merely because another refresh was requested. */
968
+ refresh(key: ReadonlyArray<unknown>): boolean;
969
+ /* Excluded from this release type: resumeTransportFailures */
970
+ /**
971
+ * The stall watchdog for one re-issued entry: `recoveryStuckMs` after the
972
+ * re-issue with neither snapshot nor delta, the entry is reported stuck and
973
+ * its subscribers are notified.
974
+ *
975
+ * That is a finding only if the watchdog itself ran on time. A browser
976
+ * throttles timers in a hidden tab — to a one-second grid, then a one-minute
977
+ * grid — so a timer there fires whenever the tab next wakes, and it used to
978
+ * report the interval it was ARMED with as the interval waited. A delivery
979
+ * queued behind the same throttling then arrived a moment after the warning
980
+ * and the invalidation, under the same attempt: the watchdog had measured
981
+ * its own delay and called it a stall.
982
+ *
983
+ * So the watchdog compares its due time with its fire time. Late beyond the
984
+ * tolerance, or firing in a hidden tab, it does not judge: it records ONE
985
+ * `recovery-timer-late` for the attempt (with how late, and whether hidden)
986
+ * and re-arms. The first on-time fire in a visible tab decides — which gives
987
+ * a delivery `recoveryStuckMs` of unthrottled time once the tab is looked at
988
+ * again, and reports a real stall within that.
989
+ */
990
+ private armRecoveryWatchdog;
991
+ /**
992
+ * Re-issue ONE entry's subscription: interrupt the fiber, reset the base,
993
+ * re-fork through the saved `fetch`.
994
+ *
995
+ * Extracted so `refreshAll` and the confirmed-patch resync cannot disagree
996
+ * about it — and the thing they must agree on is that **optimistic patches
997
+ * survive**. For a re-auth they belong to in-flight mutations; for the resync
998
+ * they describe a write the server has already committed. Dropping them here
999
+ * would be a revert with a longer name, which is the defect the resync exists
1000
+ * to remove.
1001
+ */
1002
+ private reissue;
1003
+ /**
1004
+ * Seed this (fresh) cache with the last-known-good rows held by the cache it
1005
+ * REPLACES, so a transport rebuild degrades to STALE DATA rather than to
1006
+ * skeletons.
1007
+ *
1008
+ * A reconnect builds an entirely new client stack — new runtime, new socket,
1009
+ * new cache — and the new cache starts empty, so every live `useSubscription`
1010
+ * went `data: undefined` → `loading: true` and the whole app blanked until
1011
+ * each stream's first snapshot round-tripped. Carrying the previous `base`
1012
+ * over is the same trick `initialSnapshot` plays for SSR: render real (if
1013
+ * momentarily old) data now, let the first server snapshot replace it.
1014
+ *
1015
+ * What is carried and what is NOT:
1016
+ *
1017
+ * - Only entries that actually HOLD server data (`base !== undefined`).
1018
+ * A pending or cold-start-failed entry has nothing better than the
1019
+ * loading state it is already in.
1020
+ * - `baseError` is dropped: the new transport gets to re-establish the
1021
+ * truth, and a stale error banner over live data is worse than neither.
1022
+ * - Optimistic patches are carried. A transport failure has an UNKNOWN
1023
+ * unary outcome, not a proven failure, and removing the preview before a
1024
+ * safe replay settles would flash stale data. The old cache links to this
1025
+ * one so later stage/confirm/revert operations reach the visible copy.
1026
+ * - Seeded entries carry no fiber and no fetch, exactly like the stub
1027
+ * entries a pre-mount optimistic patch creates. The first `subscribe()`
1028
+ * promotes one: it saves the fetch and forks the stream, with the seeded
1029
+ * `base` still in place, so the component never sees `undefined`.
1030
+ *
1031
+ * **Caller contract — this must only be used for a SAME-SUBJECT swap.** The
1032
+ * caller (the api supervisor) gates it on the rebuild being transport-driven.
1033
+ * A rebuild that exists to re-resolve WHO the connection is (login, logout,
1034
+ * tenant switch) must NOT seed: the next subject may be entitled to strictly
1035
+ * less, and painting the previous subject's rows into their screens is a data
1036
+ * exposure, not a UX win. That is also why `refreshAll` above clears `base`
1037
+ * outright — same reasoning, same boundary.
1038
+ *
1039
+ * Returns the number of entries seeded (diagnostics / tests).
1040
+ */
1041
+ seedStaleFrom(previous: SubscriptionCache): number;
1042
+ private create;
1043
+ private createStub;
1044
+ private freshState;
1045
+ private startFiber;
1046
+ private invalidate;
1047
+ private getSnapshot;
1048
+ private unsubscribe;
1049
+ /** Start (or restart) the inactive-TTL countdown for `entry`: unless
1050
+ * something subscribes first, interrupt its fiber and drop it. Shared by
1051
+ * the last-subscriber-out path and by `seedStaleFrom`'s unclaimed seeds. */
1052
+ private scheduleEviction;
1053
+ }
1054
+
1055
+ export declare interface SubscriptionCacheOptions {
1056
+ /** Durable local mirror (see {@link SubscriptionMirror}). */
1057
+ readonly mirror?: SubscriptionMirror;
1058
+ /**
1059
+ * CRDT cell merger for the downstream lane (plan 18): folds a
1060
+ * `mergeCells` delta op's incremental update into the held cell. The one
1061
+ * real implementation is `crdtMergeCell` from `@voltro/local-first` (this
1062
+ * package stays CRDT-library-free). Absent → a mergeCells op replaces the
1063
+ * cell (the producer only emits them when the app declares CRDT tables,
1064
+ * so an app without the binding never sees one).
1065
+ */
1066
+ readonly mergeCell?: (column: string, prevValue: unknown, update: unknown) => unknown;
1067
+ /** Milliseconds to keep an entry alive after the last subscriber leaves.
1068
+ * Lets back-button / quick remount reuse the warm subscription. */
1069
+ readonly inactiveTtlMs?: number;
1070
+ /** Debug hook fired on every cache state change. */
1071
+ readonly onChange?: (key: string) => void;
1072
+ /** Optional error bus — when a subscription stream errors out, the
1073
+ * cache reports it to the bus so global listeners (e.g. auto-logout
1074
+ * on Unauthenticated) can react. */
1075
+ readonly errorBus?: RpcErrorBus;
1076
+ /** Logical api name for payload-free diagnostics. Omit for standalone caches. */
1077
+ readonly apiName?: string;
1078
+ /** Time after a transport reissue with no delivery before one stuck event. */
1079
+ readonly recoveryStuckMs?: number;
1080
+ }
1081
+
1082
+ /**
1083
+ * Durable local mirror seam (plan 02 — local-first). `save` fires after every
1084
+ * server event that moved an entry's base (snapshot or delta) with the rows
1085
+ * AND the revision; `load` runs once for a COLD entry (no server data yet)
1086
+ * and, when it resolves first, seeds the entry so the UI renders mirrored
1087
+ * rows offline — and the NEXT (re)subscribe presents the mirrored revision as
1088
+ * `voltro-resume-from`, composing with delta-resume. The implementation
1089
+ * (`@voltro/local-first`'s query mirror) owns partitioning, encrypted-column
1090
+ * stripping and which tags mirror at all — the cache calls it for every
1091
+ * entry and a foreign tag is the mirror's no-op.
1092
+ */
1093
+ export declare interface SubscriptionMirror {
1094
+ readonly load: (key: string) => Promise<{
1095
+ readonly data: unknown;
1096
+ readonly revision: number;
1097
+ } | undefined>;
1098
+ readonly save: (key: string, snap: {
1099
+ readonly tag: string | undefined;
1100
+ readonly data: unknown;
1101
+ readonly revision: number;
1102
+ }) => Promise<void>;
1103
+ }
1104
+
1105
+ /**
1106
+ * The matching token proves this snapshot was read after the covered ACKs.
1107
+ * Contents need not equal the preview: server normalisation, no-op writes and
1108
+ * later remote writes are legitimate. Conversely, a changed value or a higher
1109
+ * revision on an ordinary stream does not prove it contains OUR write.
1110
+ */
1111
+ export declare const supersedesConfirmedPatches: (event: SubscriptionEvent<unknown>, reconciliationToken: string | undefined) => boolean;
1112
+
1113
+ export declare interface SupervisorHandle {
1114
+ readonly dispose: () => void;
1115
+ /** Force a fresh ws connect for every api (carrying the browser's current
1116
+ * cookies) so a cookie-based login re-resolves the authenticated Subject
1117
+ * in place, without a page reload. No-op for UI-only (no-api) apps. */
1118
+ readonly reconnect: () => void;
1119
+ /** Re-resolve `authHeaders` and rebuild the transport, SAME subject — for a
1120
+ * rotated token on a long-lived tab. Unlike `reconnect()` this seeds the new
1121
+ * cache from the old one, because nobody's entitlement changed. */
1122
+ readonly refreshAuth: () => void;
1123
+ }
1124
+
1125
+ export declare interface SupervisorOptions {
1126
+ readonly apis: ReadonlyArray<MountedApi>;
1127
+ readonly buildClient: BuildClient;
1128
+ /**
1129
+ * Resolve the bus owned by an api mount. Hosts whose supervisor can be
1130
+ * recreated while the provider stays mounted supply a provider-scoped bus;
1131
+ * otherwise the supervisor creates one bus per api slot.
1132
+ */
1133
+ readonly errorBusFor?: (apiName: string) => RpcErrorBus;
1134
+ /** Provider-scoped coordinator counterpart of {@link errorBusFor}. */
1135
+ readonly recoveryFor?: (apiName: string, options?: RecoveryOptions) => RecoveryCoordinator;
1136
+ /**
1137
+ * Called whenever the resolved-clients map changes (initial resolve,
1138
+ * reconnect swap, api removed). The React layer mirrors this into
1139
+ * setState so the component tree sees the latest clients.
1140
+ */
1141
+ readonly onChange: (clients: ReadonlyMap<string, ResolvedClient>, initialized: boolean) => void;
1142
+ /**
1143
+ * Override delays for failed runtime CONSTRUCTION. Defaults to the API's
1144
+ * recovery.retry policy. Socket retries belong to the rpc protocol and
1145
+ * always use recovery.retry; this callback does not override them.
1146
+ */
1147
+ readonly retryDelayMs?: (attempt: number) => number;
1148
+ /**
1149
+ * Override the stable-connection window (default 5s). When the
1150
+ * elapsed time since `onSocketOpen` exceeds this AND `failureCount`
1151
+ * hasn't moved, the connection is treated as stable and the count
1152
+ * resets to zero so the next failure starts fresh at attempt=1.
1153
+ */
1154
+ readonly stableWindowMs?: number;
1155
+ /**
1156
+ * Indirection for the JS scheduler. Production uses globalThis's
1157
+ * `setTimeout`/`clearTimeout`/`queueMicrotask`; tests inject fake
1158
+ * versions to step time deterministically.
1159
+ */
1160
+ readonly scheduler?: {
1161
+ readonly setTimeout: (cb: () => void, ms: number) => unknown;
1162
+ readonly clearTimeout: (handle: unknown) => void;
1163
+ readonly queueMicrotask: (cb: () => void) => void;
1164
+ };
1165
+ /**
1166
+ * Called when an api enters the reconnecting state, and again — via the
1167
+ * returned dispose — when it reconnects or the supervisor is torn down.
1168
+ * Exactly one entry per api per disconnect cycle: repeated retries within one
1169
+ * cycle do NOT call this again, so a status surface cannot stack duplicates.
1170
+ *
1171
+ * The web passes its devtools status bus. RN omits it.
1172
+ */
1173
+ readonly onReconnecting?: (apiName: string) => () => void;
1174
+ /**
1175
+ * Recovery for a socket that never re-opens (see the note above `ApiSlot`).
1176
+ * `arm` is called once, for an api that HAD been healthy, after
1177
+ * `afterFailures` consecutive failed reconnects; its returned stop function
1178
+ * runs on the next successful open or on dispose. What arming DOES is the
1179
+ * caller's: the web polls the page origin and hard-reloads when it answers.
1180
+ */
1181
+ readonly wedgeBackstop?: {
1182
+ readonly afterFailures: number;
1183
+ readonly arm: (apiName: string) => () => void;
1184
+ };
1185
+ }
1186
+
1187
+ /**
1188
+ * Refresh the credential when the server says it was rejected.
1189
+ *
1190
+ * `refreshAuth` is the supervisor's SAME-SUBJECT rebuild — it re-resolves
1191
+ * `authHeaders` and keeps the cache, because a rotated token is the same person.
1192
+ * Do not pass `reconnect()` here: that one exists for a login / logout / tenant
1193
+ * switch and deliberately drops the cache.
1194
+ */
1195
+ export declare const wireAuthRefresh: (bus: RpcErrorBus, refreshAuth: () => void, options?: AuthRefreshOptions) => AuthRefreshHandle;
1196
+
1197
+ /* Excluded from this release type: withProtocolOpenRecovery */
1198
+
1199
+ export { }