@voltro/client 0.84.0 → 0.86.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +1215 -0
  2. package/THIRD-PARTY-NOTICES.md +5 -89
  3. package/dist/analyticsCatalog.js +47 -0
  4. package/dist/apiConnectivity.js +33 -0
  5. package/dist/apiRuntime.js +135 -0
  6. package/dist/apiSupervisor.js +125 -0
  7. package/dist/authRefresh.js +20 -0
  8. package/dist/awaitResolvedApi.js +23 -0
  9. package/dist/bootstrap.d.ts +1144 -0
  10. package/dist/bootstrap.js +8 -0
  11. package/dist/cellMerger.js +6 -0
  12. package/dist/clientDiagnostics.js +94 -0
  13. package/dist/clientErrorBus.js +16 -0
  14. package/dist/clientScheduler.js +31 -0
  15. package/dist/connectionPrerequisite.js +70 -0
  16. package/dist/connectionScope.js +35 -0
  17. package/dist/connectionSetupController.js +206 -0
  18. package/dist/createHooks.js +15 -0
  19. package/dist/deepLink.js +69 -0
  20. package/dist/filters.js +58 -0
  21. package/dist/form.d.ts +8 -11
  22. package/dist/form.js +5 -2
  23. package/dist/formBinding.js +325 -0
  24. package/dist/formData.js +65 -0
  25. package/dist/formFlashId.js +4 -0
  26. package/dist/frameworkRuntimesContext.js +8 -0
  27. package/dist/globalContext.js +10 -0
  28. package/dist/index.d.ts +285 -279
  29. package/dist/index.js +83 -3686
  30. package/dist/liveRowSort.js +66 -0
  31. package/dist/mutationConnectionSetup.js +16 -0
  32. package/dist/mutationIdentity.js +10 -0
  33. package/dist/mutationSerialExecution.js +53 -0
  34. package/dist/mutationsBus.js +40 -0
  35. package/dist/onlineSource.js +13 -0
  36. package/dist/outbox.js +213 -0
  37. package/dist/outboxHttp.js +104 -0
  38. package/dist/outboxState.js +43 -0
  39. package/dist/permissions.js +20 -0
  40. package/dist/platform.js +121 -0
  41. package/dist/preloadSeed.js +47 -0
  42. package/dist/provider.js +22 -0
  43. package/dist/query.js +12 -2
  44. package/dist/recoveryCoordinator.js +195 -0
  45. package/dist/recoveryRetry.js +24 -0
  46. package/dist/richText.js +176 -0
  47. package/dist/rpcErrorBus.js +39 -0
  48. package/dist/rpcErrorKind.js +13 -0
  49. package/dist/runRpc.js +12 -0
  50. package/dist/runtime.d.ts +79 -15
  51. package/dist/runtime.js +16 -129
  52. package/dist/runtimeCapabilities.js +44 -0
  53. package/dist/runtimeContext.js +49 -0
  54. package/dist/schemaFields.js +219 -0
  55. package/dist/scopeMembership.js +12 -0
  56. package/dist/seedResolvers.js +7 -0
  57. package/dist/sequence.js +65 -0
  58. package/dist/serverRequest.js +24 -0
  59. package/dist/serviceClient.js +128 -0
  60. package/dist/squashRpcCause.js +8 -0
  61. package/dist/stableKey.js +21 -0
  62. package/dist/store.js +288 -0
  63. package/dist/storeStorage.js +28 -0
  64. package/dist/subscriptionCache.js +724 -0
  65. package/dist/tagWalk.js +23 -0
  66. package/dist/traceBus.js +10 -0
  67. package/dist/tracking.js +40 -0
  68. package/dist/uploadProgress.js +21 -0
  69. package/dist/useAction.js +101 -0
  70. package/dist/useAgent.js +53 -0
  71. package/dist/useAgentChat.js +43 -0
  72. package/dist/useAgentStream.js +64 -0
  73. package/dist/useApiOnline.js +14 -0
  74. package/dist/useCapabilityManifest.js +101 -0
  75. package/dist/useConnectionSetup.js +28 -0
  76. package/dist/useConnectionStatus.js +38 -0
  77. package/dist/useConnections.js +107 -0
  78. package/dist/useDataCopilot.js +24 -0
  79. package/dist/useDataTable.js +34 -0
  80. package/dist/useDerived.js +22 -0
  81. package/dist/useEvent.js +88 -0
  82. package/dist/useFormBinding.js +476 -0
  83. package/dist/useLocalQuery.js +59 -0
  84. package/dist/useMutation.js +214 -0
  85. package/dist/useOnRpcError.js +13 -0
  86. package/dist/usePreloadedSubscription.js +18 -0
  87. package/dist/usePreview.js +14 -0
  88. package/dist/useProvenance.js +51 -0
  89. package/dist/useQueryField.js +34 -0
  90. package/dist/useRecord.js +12 -0
  91. package/dist/useRefreshSubscriptions.js +22 -0
  92. package/dist/useResourceCan.js +18 -0
  93. package/dist/useResumableAgentStream.js +75 -0
  94. package/dist/useSequence.js +25 -0
  95. package/dist/useSkeleton.js +13 -0
  96. package/dist/useSubscription.js +89 -0
  97. package/dist/useSubscriptionHealth.js +32 -0
  98. package/dist/useTranscription.js +51 -0
  99. package/dist/useUndo.js +33 -0
  100. package/dist/useUndoLog.js +44 -0
  101. package/dist/useUpload.js +296 -0
  102. package/dist/useWindowedSubscription.js +65 -0
  103. package/dist/useWorkflow.js +284 -0
  104. package/dist/useWorkflowRunState.js +93 -0
  105. package/dist/validation.js +39 -0
  106. package/dist/validationMessages.js +5 -0
  107. package/package.json +8 -5
  108. package/dist/authRefresh-C4Ow8HH7.js +0 -346
  109. package/dist/formData-dGz5aoUR.js +0 -649
  110. package/dist/queryOnce-CvdopzOj.js +0 -55
  111. package/dist/runRpc-DvHpFZAZ.js +0 -1034
@@ -0,0 +1,1144 @@
1
+ import { ClientDescriptor } from '@voltro/protocol';
2
+ import { Context } from 'react';
3
+ import { createRowPatchApplier } from '@voltro/protocol';
4
+ import { Fiber } from 'effect';
5
+ import { ManagedRuntime } from 'effect';
6
+ import { ReactNode } from 'react';
7
+ import type * as Socket from 'effect/socket/Socket';
8
+ import { Stream } from 'effect';
9
+ import { SubscriptionEvent } from '@voltro/protocol';
10
+ import { TargetRelations } from '@voltro/protocol';
11
+
12
+ /** Erased per-api runtime boundary. Headless cache code must not import the
13
+ * React context (and its browser globals) merely to name this Effect type. */
14
+ declare type AnyRuntime = ManagedRuntime.ManagedRuntime<never, never>;
15
+
16
+ export declare interface ApiHandle {
17
+ readonly runtime: AnyRuntime;
18
+ readonly cache: SubscriptionCache;
19
+ /** Resolved typed rpc client. Methods nest by tag (`todos.list` →
20
+ * `client.todos.list`). Hooks walk by tag-segment (see `resolveByTag`)
21
+ * to invoke, so the static type here is the erased `unknown`; the typed
22
+ * view comes from `useAppClient<T>(name)` at the call site. */
23
+ readonly client: unknown;
24
+ /** Per-rpc-tag descriptor metadata. Drives auto-optimistic and source-
25
+ * based cache routing. */
26
+ readonly descriptors: Readonly<Record<string, ClientDescriptor>>;
27
+ /**
28
+ * Base HTTP origin where the api's `/_voltro/inspect/*` endpoints
29
+ * live. Derived from `wsUrl` at mount time (`ws://host:port/ws` →
30
+ * `http://host:port`). DevTools and any inspect-consuming tooling
31
+ * use this for the metrics / subscriptions / events endpoints.
32
+ */
33
+ readonly inspectBaseUrl: string;
34
+ /** Per-api error bus. Mutations + subscription failures land here so
35
+ * app-level listeners can react to typed errors globally (auto-logout
36
+ * on `Unauthenticated`, network-error toasts, etc.). */
37
+ readonly errorBus: RpcErrorBus;
38
+ /** Stable UI/raw transport recovery state for this logical api. */
39
+ readonly recovery?: RecoveryCoordinator;
40
+ }
41
+
42
+ /**
43
+ * Apply preload seeds from the hydration payload, BEFORE the first client
44
+ * render. Idempotent (a Map upsert) so a re-hydration or a repeated key is
45
+ * harmless — last write wins, matching the store-seed rule.
46
+ */
47
+ export declare const applyPreloadSeeds: (seeds: ReadonlyArray<PreloadSeed> | undefined) => void;
48
+
49
+ /**
50
+ * Apply seeds from the hydration payload, BEFORE the first client render.
51
+ *
52
+ * Unknown store names are skipped rather than throwing: a payload can outlive a
53
+ * deploy (a cached document, a user with a stale tab), and refusing to boot the
54
+ * app over a store somebody deleted would turn a cosmetic staleness into a
55
+ * blank page.
56
+ */
57
+ export declare const applyStoreSeeds: (seeds: ReadonlyArray<StoreSeed> | undefined) => void;
58
+
59
+ /**
60
+ * Auto-apply target as seen from the client. Identical shape to the
61
+ * server's TargetSpec but with all schema generics erased (the client
62
+ * sees concrete row shapes at runtime, not Schema instances).
63
+ *
64
+ * Optional overrides:
65
+ * - `shape` for insert: build the row from input + optimistic id
66
+ * for update: build the patched row from (input, current)
67
+ * - `identify` for update/delete: extract the row id from input
68
+ * (defaults to `input.id`)
69
+ * - `order` for insert: 'prepend' (default) or 'append'
70
+ */
71
+ declare interface AutoApplyTarget {
72
+ readonly table: string;
73
+ readonly op: 'insert' | 'update' | 'delete';
74
+ readonly order?: 'prepend' | 'append' | undefined;
75
+ readonly shape?: ((input: Record<string, unknown>, optimisticIdOrCurrent?: unknown) => Record<string, unknown>) | undefined;
76
+ readonly identify?: ((input: Record<string, unknown>) => string | ReadonlyArray<string>) | undefined;
77
+ /** Dot-path to a nested array WITHIN the query value (e.g.
78
+ * `'snapshot.projects'`). When set, the reducer patches that nested array at
79
+ * ITEM granularity instead of the top-level row array — for JSON array
80
+ * columns + computed/shaped query results. */
81
+ readonly path?: string | undefined;
82
+ /** Item key within the nested array (default `'id'`). Only with `path`. */
83
+ readonly by?: string | undefined;
84
+ /** Guard which cached entries to patch — only entries whose current (base)
85
+ * value satisfies this. Stops a patch bleeding across sibling subscriptions
86
+ * sharing a source table. */
87
+ readonly match?: ((value: unknown, input: Record<string, unknown>) => boolean) | undefined;
88
+ /** Nested-item shaper — the client uses this (not `shape`) to build/patch a
89
+ * nested-array item when `path` is set. Typed to the item, not the output.
90
+ * 2nd arg is the optimistic id (insert) or the current item (update). */
91
+ readonly shapeItem?: ((input: Record<string, unknown>, currentOrOptimisticId: unknown) => Record<string, unknown>) | undefined;
92
+ /** Declared many-to-many relations (`{ inputField: { junction, anchorColumn,
93
+ * targetColumn } }`). Drives JUNCTION auto-optimistic: entries sourced on the
94
+ * junction table get their link rows for this anchor reconciled against
95
+ * `input[inputField]` immediately, instead of waiting for the server delta
96
+ * while every scalar field of the same form has already flipped. */
97
+ readonly relations?: TargetRelations | undefined;
98
+ }
99
+
100
+ declare interface BiometricSource {
101
+ readonly available: () => Promise<boolean>;
102
+ readonly authenticate: (reason: string) => Promise<boolean>;
103
+ }
104
+
105
+ /**
106
+ * The browser adapter. `@voltro/web` installs it at mount; it is also the
107
+ * lazy default so hooks answer sensibly in a tab that never called
108
+ * `installPlatform` (and under jsdom, where the shell reads as `'test'`).
109
+ */
110
+ export declare const browserPlatform: (overrides?: Partial<PlatformAdapterInput>) => PlatformAdapter;
111
+
112
+ declare interface CacheEntry {
113
+ rowPatchApplier?: ReturnType<typeof createRowPatchApplier>;
114
+ readonly key: string;
115
+ /** First element of the keyArr — the rpc tag (e.g. 'todos.list'). Used
116
+ * by `forTag()` so callers can patch every sub-key for a tag without
117
+ * knowing the inputs. Captured at create-time so updates without a
118
+ * prior subscribe still work (stub entries get tag too). */
119
+ readonly tag: string | undefined;
120
+ state: EntryState<unknown>;
121
+ /** Retired stream callbacks must not mutate the replacement generation. */
122
+ generation: number;
123
+ /** Coalesce same-tick mutation ACKs into one causal read per entry. */
124
+ reconciliationScheduled: boolean;
125
+ /** Once this entry has read its own write, reconnects must not downgrade to
126
+ * a lagging replica. Same-subject replacements carry this bit with rows. */
127
+ primaryReads: boolean;
128
+ /** Subscriber re-render callbacks. */
129
+ subscribers: Set<() => void>;
130
+ /** Fiber running the underlying stream. */
131
+ fiber: Fiber.Fiber<unknown, unknown> | null;
132
+ /** The last fiber ended because the rpc transport failed. A later socket
133
+ * `open` re-issues active entries with their last-known-good base intact. */
134
+ resumeAfterTransportOpen: boolean;
135
+ recoveryPhase: 'steady' | 'awaiting-protocol' | 'awaiting-delivery' | 'stuck';
136
+ recoveryAttempt: number;
137
+ lastTransportFailureAt: number | undefined;
138
+ lastReissueAt: number | undefined;
139
+ lastDeliveryAt: number | undefined;
140
+ recoveryBasePreserved: boolean;
141
+ recoveryTimer: ReturnType<typeof setTimeout> | null;
142
+ /** Pending eviction (last subscriber gone, TTL countdown). */
143
+ evictionTimer: NodeJS.Timeout | null;
144
+ /** Source table(s) this entry reads (from the rpc descriptor). Used by
145
+ * auto-optimistic to find which entries to patch when a mutation with
146
+ * a matching `target.table` is invoked — an array matches if the target is
147
+ * among the listed tables. May be undefined for queries whose source isn't
148
+ * expressed as table(s) (joins, aggregates). */
149
+ source: string | ReadonlyArray<string> | undefined;
150
+ /** True once a server snapshot reported this query as COMPUTED (handler
151
+ * returns a shaped value, not a table row-set). Auto-optimistic skips
152
+ * blind INSERTs into computed entries — the client can't evaluate the
153
+ * query's opaque server-side filter to know if a new row belongs, so it
154
+ * defers to the authoritative recompute push. UPDATE/DELETE (matched by
155
+ * id) still apply. Defaults false until the first snapshot resolves it. */
156
+ computed: boolean;
157
+ /** Saved `fetch` thunk from the first subscribe(). Used by `refreshAll()`
158
+ * to re-issue the WS subscription after a connection-subject re-bind
159
+ * (e.g. soft re-auth after login). Each subscriber's hook keeps its
160
+ * own fetch closure, but only the first one's identity matters — the
161
+ * server-side subscription is one per cache-entry key, not per
162
+ * subscriber. */
163
+ fetch: (() => Stream.Stream<SubscriptionEvent<unknown>, unknown, never>) | null;
164
+ /** The runtime the saved `fetch` was forked against. Stored so a SINGLE entry
165
+ * can be re-issued without the whole-cache `refreshAll(runtime)` — the
166
+ * confirmed-patch resync needs exactly one, and threading a runtime down
167
+ * from a `setTimeout` is not available to it. */
168
+ runtime: AnyRuntime | null;
169
+ /** W3C trace id of the live stream, captured when the fiber starts.
170
+ * Shared with the server (the subscription span propagates it) and
171
+ * attached to error-bus events so a failure points at the right
172
+ * `voltro logs --trace <id>`. */
173
+ traceId?: string;
174
+ }
175
+
176
+ /** Plain-data snapshot of a single cache entry for devtools / test
177
+ * introspection. Doesn't carry the live fiber or React-subscriber
178
+ * set — those are kept private. */
179
+ declare interface CacheEntrySnapshot {
180
+ readonly key: string;
181
+ readonly tag: string | undefined;
182
+ readonly source: string | ReadonlyArray<string> | undefined;
183
+ readonly subscriberCount: number;
184
+ /** True while the underlying stream's fiber is running. */
185
+ readonly hasFiber: boolean;
186
+ /** True after the last subscriber left and the eviction TTL is
187
+ * counting down — a quick remount within the window resurrects. */
188
+ readonly evicting: boolean;
189
+ /** Recovery of a transport-terminal stream, without exposing its input. */
190
+ readonly recovery: {
191
+ readonly phase: 'steady' | 'awaiting-protocol' | 'awaiting-delivery' | 'stuck';
192
+ readonly attempt: number;
193
+ readonly lastTransportFailureAt: number | undefined;
194
+ readonly lastReissueAt: number | undefined;
195
+ readonly lastDeliveryAt: number | undefined;
196
+ readonly basePreserved: boolean;
197
+ };
198
+ readonly snapshot: CacheSnapshot<unknown>;
199
+ }
200
+
201
+ declare interface CacheSnapshot<T> {
202
+ /** Current visible data = base + all live patches applied in order. */
203
+ readonly data: T | undefined;
204
+ /** Most recent revision the server delivered. -1 if no snapshot yet. */
205
+ readonly revision: number;
206
+ /** Wall-clock ms when the most recent server delta was emitted; undefined for snapshots. */
207
+ readonly emittedAt: number | undefined;
208
+ /** Why the stream failed, if no snapshot has ever arrived — the value the
209
+ * api's error bus carries in `RpcError.error` for the same failure: the
210
+ * declared error itself (match on `_tag`), an `RpcClientError` for a
211
+ * transport failure, or the defect. Never an Effect `Cause`. */
212
+ readonly error: unknown | undefined;
213
+ /** Number of live optimistic patches currently applied. */
214
+ readonly pendingPatches: number;
215
+ }
216
+
217
+ /** The installed adapter, or the lazily-built browser default. */
218
+ export declare const currentPlatform: () => PlatformAdapter;
219
+
220
+ /** Inbound URLs: the one the app was opened with, and the ones that arrive
221
+ * while it runs (universal links, custom schemes, protocol handlers). */
222
+ declare interface DeepLinkSource {
223
+ readonly initialUrl: () => Promise<string | null>;
224
+ readonly subscribe: (onUrl: (url: string) => void) => () => void;
225
+ }
226
+
227
+ declare interface EntryState<T> {
228
+ /** Last server-delivered data (base for patches). */
229
+ base: T | undefined;
230
+ baseRevision: number;
231
+ baseEmittedAt: number | undefined;
232
+ baseError: unknown | undefined;
233
+ patches: Array<OptimisticPatch<T>>;
234
+ /** Cached optimistic snapshot — invalidated on every state change so
235
+ * `getSnapshot` returns a stable reference between mutations. */
236
+ cachedSnapshot: CacheSnapshot<T> | null;
237
+ previewPrefix?: {
238
+ readonly base: T;
239
+ readonly count: number;
240
+ readonly data: T;
241
+ };
242
+ previewBase?: {
243
+ readonly base: T;
244
+ readonly eligible: boolean;
245
+ };
246
+ }
247
+
248
+ /**
249
+ * The error/values payload a failed no-JS form POST carries back into the
250
+ * 422 re-render. Keyed by `formKey` so a page with several forms re-fills
251
+ * only the one that was submitted. The SSR render passes it through the
252
+ * server-request context; the client reads the same payload back off the
253
+ * `#__voltro_form_flash__` JSON script, so a late-hydrating page shows the
254
+ * identical state (no mismatch, no vanished errors).
255
+ */
256
+ declare interface FormFlashPayload {
257
+ /** The submitted form's key — `<AutoForm formKey>` or its mutation tag. */
258
+ readonly formKey: string;
259
+ /** The mapped input values as posted (pre-decode), to re-fill the fields. */
260
+ readonly values: Readonly<Record<string, unknown>>;
261
+ /** First error per field — the `validateFields` shape. */
262
+ readonly errors: Readonly<Record<string, string>>;
263
+ /** A non-field error (the RPC refused after valid input: guard, server). */
264
+ readonly formError?: string;
265
+ }
266
+
267
+ export declare interface FrameworkRuntimes {
268
+ /** Look up an api handle (runtime + cache) by name. Throws if no such api was mounted. */
269
+ readonly get: (name: string) => ApiHandle;
270
+ /** Enumerate the names of currently-installed apis (for debug). */
271
+ readonly names: ReadonlyArray<string>;
272
+ /**
273
+ * "Something in this tree needs `apiName`."
274
+ *
275
+ * Under `web.api.connect: 'lazy'` the provider does not open a socket until
276
+ * this is called, so a page that reads no data never opens one. Under the
277
+ * default `'eager'` it is a no-op — every api connects at mount, as before.
278
+ *
279
+ * It exists because the alternative was worse in a specific, measured way:
280
+ * `interactive: 'full'` is the DEFAULT render mode, and the client opened a
281
+ * WebSocket on every such page whether or not it subscribed. A pre-rendered
282
+ * documentation page with no data at all opened one (measured in a real
283
+ * browser: 0 sockets on `interactive: 'none'` / `'islands'`, one on `'full'`).
284
+ * And an open socket keeps a dormancy-managed instance awake — `isIdleNow`
285
+ * returns false while `connectedClients() > 0` — so one browser tab on a
286
+ * pricing page prevented scale-to-zero indefinitely.
287
+ *
288
+ * Optional so a foreign host embedding `FrameworkRuntimesContext` by hand
289
+ * keeps working; absent means "already connected", which is the safe reading.
290
+ */
291
+ readonly demand?: (apiName: string) => void;
292
+ /**
293
+ * One read through an api's client — the browser half of a loader's
294
+ * `ctx.query`. Supplied by the host that builds the rpc runtime
295
+ * (`VoltroRuntimeProvider`), not by this context: the read reaches the rpc
296
+ * client and with it the Effect runtime, and an app that mounts no api must
297
+ * not load either just because its router can ask. Absent → `ctx.query` is
298
+ * `undefined` in the browser, as it is for an app without apis.
299
+ */
300
+ readonly queryOnce?: QueryOnce;
301
+ /**
302
+ * Resolves once the rpc runtime behind these apis is loaded. A host that
303
+ * loads it on demand (the web boot keeps it out of an app's first load and
304
+ * fetches it with the first route that reads data) supplies it; absent means
305
+ * the runtime is already there.
306
+ */
307
+ readonly ready?: () => Promise<void>;
308
+ }
309
+
310
+ export declare const FrameworkRuntimesContext: Context<FrameworkRuntimes | null>;
311
+
312
+ export declare const FrameworkRuntimesProvider: ({ apis, children, demand, queryOnce, }: FrameworkRuntimesProviderProps) => ReactNode;
313
+
314
+ export declare interface FrameworkRuntimesProviderProps {
315
+ readonly apis: ReadonlyMap<string, ApiHandle>;
316
+ readonly children: ReactNode;
317
+ /** Passed straight through to the context so `useFrameworkApi` can say that
318
+ * something in the tree needs an api. The web boot supplies it under
319
+ * `web.api.connect: 'lazy'`; a foreign host may omit it, which reads as
320
+ * "already connected". */
321
+ readonly demand?: (apiName: string) => void;
322
+ /** Passed straight through to the context for loader reads in the browser —
323
+ * see `FrameworkRuntimes.queryOnce`. The web boot supplies `queryOnce`. */
324
+ readonly queryOnce?: QueryOnce;
325
+ }
326
+
327
+ /**
328
+ * A process-wide singleton React context, pinned on the global symbol registry.
329
+ *
330
+ * WHY this exists: the SSG prerender (`voltro build`) loads the framework
331
+ * through TWO separate module instances — the renderer comes in via Vite's
332
+ * `ssrLoadModule('@voltro/web/ssr')` (Vite-transformed) while a page's own
333
+ * framework import is externalised to Node — so a plain `createContext()`
334
+ * in a shared module is evaluated twice and yields two DISTINCT context
335
+ * objects. The `<Router>` provider then holds one while the page's
336
+ * `useLocation()` reads the other, which throws "Router hooks must be used
337
+ * inside <Router>." The same duplicate-instance hazard shows up wherever a
338
+ * deployment ends up with two copies of a package (the classic dual-package
339
+ * hazard, monorepo hoisting quirks, separate SSR vs client bundles).
340
+ *
341
+ * Resolving every context through `Symbol.for(...)` on `globalThis` makes all
342
+ * module copies share ONE instance, so provider and consumer can never diverge.
343
+ * A duplicated copy of THIS helper is harmless — both copies hit the same
344
+ * global registry entry.
345
+ *
346
+ * Lives in @voltro/client (the lowest React-carrying package) so both
347
+ * @voltro/web and @voltro/ui reach it without a cycle; the key prefix keeps
348
+ * its historical spelling on purpose — a mixed dist/src world must resolve
349
+ * to the same registry entries.
350
+ */
351
+ export declare const globalContext: <T>(key: string, initial: T) => Context<T>;
352
+
353
+ /**
354
+ * Install the platform adapter. Call it once, before the first render — on
355
+ * React Native after the persistence adapter has hydrated, because this also
356
+ * installs the adapter's `storage` as the persisted-store backing.
357
+ */
358
+ export declare const installPlatform: (adapter: PlatformAdapter) => void;
359
+
360
+ /** Is an adapter installed (as opposed to the lazy browser default)? */
361
+ export declare const isPlatformInstalled: () => boolean;
362
+
363
+ /** Foreground/background transitions — `AppState` on React Native,
364
+ * `visibilitychange` in a browser, window focus in a desktop shell. */
365
+ declare interface LifecycleSource {
366
+ readonly read: () => LifecycleState;
367
+ readonly subscribe: (onChange: (state: LifecycleState) => void) => () => void;
368
+ }
369
+
370
+ declare type LifecycleState = 'active' | 'inactive' | 'background';
371
+
372
+ declare interface MutationReplayReservation {
373
+ /** Re-check immediately before sending: identity, capability and transport may have changed while waiting. */
374
+ readonly isValid: () => boolean;
375
+ /** Release the bounded pending slot. Safe to call more than once. */
376
+ readonly release: () => void;
377
+ }
378
+
379
+ declare type NotificationPermission_2 = 'granted' | 'denied' | 'prompt';
380
+
381
+ declare interface NotificationSurface {
382
+ readonly permission: () => Promise<NotificationPermission_2>;
383
+ readonly requestPermission: () => Promise<NotificationPermission_2>;
384
+ /** The push token/subscription to register with the server — present only
385
+ * where the shell has a push channel (Expo push token, Web Push). */
386
+ readonly pushToken?: () => Promise<string | null>;
387
+ /** Show a local/system notification — present where the shell can. */
388
+ readonly show?: (notification: {
389
+ readonly title: string;
390
+ readonly body?: string;
391
+ readonly data?: Readonly<Record<string, unknown>>;
392
+ }) => Promise<void>;
393
+ }
394
+
395
+ /** A reachability signal: a synchronous read plus change notifications. */
396
+ declare interface OnlineSource {
397
+ readonly read: () => boolean;
398
+ readonly subscribe: (onChange: (online: boolean) => void) => () => void;
399
+ }
400
+
401
+ declare interface OptimisticPatch<T = unknown> {
402
+ readonly id: string;
403
+ readonly mutationId: string;
404
+ readonly reducer: (current: T) => T;
405
+ /** A successful write stays previewed until a matching post-ACK primary
406
+ * snapshot supersedes it. A different write's delta proves nothing. */
407
+ confirmed?: boolean;
408
+ /** Only framework-owned reducers with an unchanged input can reuse a prefix. */
409
+ readonly canReuse?: (() => boolean) | undefined;
410
+ }
411
+
412
+ declare interface PlatformAdapter {
413
+ readonly platform: PlatformInfo;
414
+ readonly capabilities: PlatformCapabilities;
415
+ /** The WebSocket the api runtime opens — `buildApiRuntime`'s constructor. */
416
+ readonly webSocket: (url: string, options?: Socket.WebSocketConstructorOptions) => WebSocket;
417
+ /** Backing store for `defineStore({ persist })`; installed via `setStoreStorage`. */
418
+ readonly storage: StoreStorageProvider;
419
+ readonly secureStorage: TokenStore;
420
+ readonly online: OnlineSource;
421
+ readonly lifecycle: LifecycleSource;
422
+ readonly links: DeepLinkSource;
423
+ readonly notifications?: NotificationSurface;
424
+ readonly updates?: UpdateChannel;
425
+ readonly biometrics?: BiometricSource;
426
+ readonly clock: {
427
+ readonly now: () => number;
428
+ };
429
+ /** Shell-specific surfaces, keyed by shell (`tauri`, `electron`, `expo`).
430
+ * See `useShellExtension`. */
431
+ readonly extensions?: Readonly<Record<string, unknown>>;
432
+ }
433
+
434
+ /** The adapter minus what `definePlatform` derives. */
435
+ declare type PlatformAdapterInput = Omit<PlatformAdapter, 'capabilities'> & {
436
+ readonly capabilities?: Partial<PlatformCapabilities>;
437
+ };
438
+
439
+ /** What the running shell can do. Derived from the ports an adapter fills in
440
+ * (`capabilitiesOf`); an adapter may narrow a derived `true` it cannot honour. */
441
+ declare interface PlatformCapabilities {
442
+ readonly offlineStart: boolean;
443
+ readonly secureTokenStorage: boolean;
444
+ readonly push: boolean;
445
+ readonly localNotifications: boolean;
446
+ readonly updates: boolean;
447
+ readonly deepLinks: boolean;
448
+ readonly biometrics: boolean;
449
+ readonly backgroundSync: boolean;
450
+ readonly installPrompt: boolean;
451
+ }
452
+
453
+ declare interface PlatformInfo {
454
+ readonly kind: PlatformKind;
455
+ readonly shell: ShellKind;
456
+ /** True when running as an installed app (a PWA in standalone mode, any
457
+ * native shell); false in a browser tab. */
458
+ readonly installed: boolean;
459
+ /** The app's own version, where the shell knows it (a store build, a
460
+ * desktop release). Undefined in a browser tab. */
461
+ readonly appVersion?: string;
462
+ /** The build the running code came from — what an update feed compares. */
463
+ readonly buildId?: string;
464
+ }
465
+
466
+ declare type PlatformKind = 'web' | 'pwa' | 'ios' | 'android' | 'macos' | 'windows' | 'linux' | 'unknown';
467
+
468
+ /** One preloaded subscription snapshot, as it travels in the hydration payload. */
469
+ declare interface PreloadSeed {
470
+ /** The api mount name the subscription reads from (first arg of `useSubscription`). */
471
+ readonly api: string;
472
+ /** `stableKey([rpcTag, input])` — identical to the SubscriptionCache's own key,
473
+ * so the seed and the live subscription address the same entry. */
474
+ readonly key: string;
475
+ /** The server-fetched snapshot value. `undefined` when `failed`. */
476
+ readonly value: unknown;
477
+ /**
478
+ * The server ATTEMPTED this preload and it failed.
479
+ *
480
+ * Reported from a real deployment whose SSR seeds all failed at once (an expired
481
+ * session token — the api answered every preload with a scope error): the
482
+ * page rendered a skeleton title and an empty table, and the ONLY record of
483
+ * it was a `preload seed failed` WARN in the server log. The client could not
484
+ * tell that state from "this page declares no preload", because both arrive
485
+ * as the absence of a seed. So an app cannot distinguish "still loading" from
486
+ * "actually empty" without inventing its own convention — which the reporting
487
+ * consumer then did, page by page.
488
+ *
489
+ * NOTHING about the cause travels. A boolean is the whole contract: the
490
+ * server's failure text is for the server's log, and a reason string here
491
+ * would be an error message from a refused call rendered into a browser.
492
+ */
493
+ readonly failed?: true;
494
+ }
495
+
496
+ /** `queryOnce`'s shape, declared here so this module stays free of it. */
497
+ declare type QueryOnce = (handleRef: {
498
+ readonly current: {
499
+ readonly runtime: unknown;
500
+ readonly client: unknown;
501
+ };
502
+ }, apiName: string, tag: string, input: Record<string, unknown> | undefined, signal?: AbortSignal) => Promise<unknown>;
503
+
504
+ declare type RawTransportStatus = 'connected' | 'disconnected';
505
+
506
+ /**
507
+ * State owned by one logical API, not by one socket or one React hook.
508
+ *
509
+ * Raw listeners (`RpcErrorBus.on`) still receive every failure immediately.
510
+ * Presentation listeners receive non-transport failures immediately, but at
511
+ * most one transport failure per outage and only after the grace window. A
512
+ * fully healed gap therefore leaves no toast/banner flash while diagnostics
513
+ * retain the complete sequence.
514
+ */
515
+ declare class RecoveryCoordinator {
516
+ #private;
517
+ constructor(apiName: string, options?: RecoveryOptions, scheduler?: Partial<RecoveryScheduler>);
518
+ get options(): ResolvedRecoveryOptions;
519
+ /** Ends on login/logout, tenant change or API disposal, not ordinary reconnect. */
520
+ get subjectSignal(): AbortSignal;
521
+ /** Hydration values belong to the initial subject only. Once identity may
522
+ * have changed, a later generation/remount must obtain its own snapshot.
523
+ * Ordinary transport recovery does not cross this boundary. */
524
+ getPreloadSeedPermission: () => boolean;
525
+ /** A whole-cache resnapshot can follow same-socket re-authentication. Its
526
+ * replacement reads must not reuse the original server-rendered values. */
527
+ invalidatePreloadSeeds(): void;
528
+ getSnapshot: () => RecoverySnapshot;
529
+ /** The SSR / hydration snapshot — see INITIAL_RECOVERY_SNAPSHOT. Stable by
530
+ * reference, so both renders agree and React swaps to the live one after. */
531
+ getServerSnapshot: () => RecoverySnapshot;
532
+ subscribe: (listener: () => void) => (() => void);
533
+ onVisibleError(listener: RpcErrorListener): () => void;
534
+ /** Called from the socket seam before request fibers report their errors. */
535
+ transportIssue(): void;
536
+ /** Called only after the rpc protocol has cleared its previous transport error. */
537
+ protocolReady(): void;
538
+ observeError(error: RpcError): void;
539
+ observeSuccess(success: RpcSuccess): void;
540
+ reportExternalSuccess(): void;
541
+ /** Discard every stale row/replay/health fact at the subject boundary. */
542
+ resetForSubjectChange(minimumCapabilityGeneration?: number): void;
543
+ setMutationReplaySupported(supported: boolean, generation?: number): void;
544
+ /**
545
+ * Wait for the capability probe when transport fails during initial boot.
546
+ * Unknown is never permission: the wait is bounded by the replay window and
547
+ * resolves false if the server never proves that idempotency is active.
548
+ */
549
+ /** What is left of the replay window for a mutation that started at `startedAt`. */
550
+ replayWindowRemaining(startedAt: number): number;
551
+ waitForMutationReplaySupport(startedAt: number): Promise<boolean>;
552
+ /**
553
+ * Reserve one bounded waiting/replay slot; caller MUST release the returned
554
+ * reservation. An unknown capability may reserve while its probe is in flight,
555
+ * otherwise that short boot window would permit an unbounded waiter set.
556
+ * Disabled is final for the current generation and refuses immediately.
557
+ */
558
+ reserveMutationReplay(startedAt: number): MutationReplayReservation | undefined;
559
+ waitForProtocolReady(startedAt: number, signal?: AbortSignal): Promise<boolean>;
560
+ dispose(): void;
561
+ }
562
+
563
+ declare interface RecoveryOptions {
564
+ /** Hide a transport gap from the UI while recovery is still plausible. */
565
+ readonly graceMs?: number;
566
+ /** Socket reconnect timing, independent of the presentation grace window. */
567
+ readonly retry?: RecoveryRetryOptions;
568
+ /** Maximum mutations allowed to wait for one safe replay at once. */
569
+ readonly maxPendingMutations?: number;
570
+ /** Maximum age of a mutation before an automatic replay is refused. */
571
+ readonly replayWindowMs?: number;
572
+ /**
573
+ * Explicit HTTP endpoint for runtime capability discovery. Usually omitted:
574
+ * the client derives a sibling of the WebSocket path. Set this only when an
575
+ * edge routes the WebSocket and ordinary HTTP through unrelated paths.
576
+ */
577
+ readonly capabilitiesUrl?: string;
578
+ }
579
+
580
+ declare type RecoveryPresentationStatus = 'connected' | 'recovering' | 'degraded';
581
+
582
+ /** Delays after failed socket attempts; the first connection is always immediate. */
583
+ declare interface RecoveryRetryOptions {
584
+ /** First retry delay in ms (default 0). Clamped to 0–maxMs. */
585
+ readonly initialMs?: number;
586
+ /** Second retry delay in ms (default 500). Clamped to 50–maxMs. */
587
+ readonly thenMs?: number;
588
+ /** Multiplier after the second retry (default 1.5). Clamped to 1–10. */
589
+ readonly factor?: number;
590
+ /** Maximum retry delay in ms (default 5000). Clamped to 50–60000. */
591
+ readonly maxMs?: number;
592
+ }
593
+
594
+ declare interface RecoveryScheduler {
595
+ readonly now: () => number;
596
+ readonly setTimeout: (callback: () => void, ms: number) => unknown;
597
+ readonly clearTimeout: (handle: unknown) => void;
598
+ }
599
+
600
+ declare interface RecoverySnapshot {
601
+ readonly rawTransport: RawTransportStatus;
602
+ readonly status: RecoveryPresentationStatus;
603
+ readonly failureCount: number;
604
+ readonly lastFailureAt: number | undefined;
605
+ readonly failedSubscriptions: ReadonlyArray<string>;
606
+ readonly pendingMutationReplays: number;
607
+ readonly mutationReplay: 'unknown' | 'enabled' | 'disabled';
608
+ }
609
+
610
+ declare interface ResolvedRecoveryOptions {
611
+ readonly graceMs: number;
612
+ readonly retry: Required<RecoveryRetryOptions>;
613
+ readonly maxPendingMutations: number;
614
+ readonly replayWindowMs: number;
615
+ readonly capabilitiesUrl: string | undefined;
616
+ }
617
+
618
+ /** What the client can prove about a unary call's server-side result. */
619
+ declare type RpcCallOutcome = 'not-applicable' | 'not-started' | 'known' | 'unknown';
620
+
621
+ declare interface RpcError {
622
+ /** Source — `'mutation'` for transactional unary calls, `'action'` for
623
+ * non-transactional unary calls, `'subscription'` for streams. */
624
+ readonly source: 'mutation' | 'action' | 'subscription';
625
+ /** RPC tag (e.g. `'orgs.create'`, `'projects.list'`). */
626
+ readonly tag: string;
627
+ /** The raw error value. May be a Schema.TaggedError instance, a plain
628
+ * Error, an unknown thrown value. Pattern-match on `_tag` for typed errors. */
629
+ readonly error: unknown;
630
+ /** Failure origin. Use `transport` for connection-level UX; `handler` means
631
+ * the rpc returned a declared failure; `client` is framework work that
632
+ * failed locally; `unknown` is deliberately unclassified. */
633
+ readonly kind: RpcErrorKind;
634
+ /** False when the native caller proves this transport failure belongs to an
635
+ * ended physical attempt. The call still failed (and may have committed),
636
+ * but it must not mark the replacement socket down. Omitted preserves the
637
+ * conservative fallback for emitters without native lifetime evidence. */
638
+ readonly affectsTransport?: boolean;
639
+ /** A transport failure after a unary request started is `unknown`: the
640
+ * server may have committed before the response disappeared. */
641
+ readonly outcome?: RpcCallOutcome;
642
+ /** Trace id of the CLIENT call span. When the server accepted the request,
643
+ * effect/rpc propagates this same id into its span. A transport failure may
644
+ * happen before that, so the id is not proof that server logs exist. Present
645
+ * only when a client span was active. */
646
+ readonly traceId?: string;
647
+ }
648
+
649
+ declare class RpcErrorBus {
650
+ #private;
651
+ /** Subscribe. Returns an unsubscribe function. */
652
+ on(listener: RpcErrorListener): () => void;
653
+ /** Emit. Pipeline code (useMutation / subscriptionCache) calls this. */
654
+ emit(event: RpcError): void;
655
+ /**
656
+ * Subscribe to SUCCESSES — the channel that makes a consecutive-failure
657
+ * ceiling mean what it says.
658
+ *
659
+ * ── Why the bus grew a second channel ──────────────────────────────────
660
+ *
661
+ * `wireAuthRefresh` bounds how often it may rebuild the transport on
662
+ * `Unauthenticated`, and `maxConsecutive` bounds the TOTAL — after that many
663
+ * refreshes *with no successful call in between*, it stops and leaves the
664
+ * error to the app, because at that point the credential is not stale, it is
665
+ * refused. "With no successful call in between" was carried by
666
+ * `AuthRefreshHandle.noteSuccess()`, a method the HOST had to remember to
667
+ * call, and the only host never called it.
668
+ *
669
+ * What that turns the ceiling into is the part worth writing down: not a
670
+ * loop, but a LIFETIME budget. A tab that rotates its token three times over
671
+ * a few hours exhausts it and then never refreshes again for as long as it
672
+ * stays open — every later expiry rejects every subscription it opens, each
673
+ * rejected entry is terminal for its transport, and the screen waits on a
674
+ * spinner that has nothing left to wait for.
675
+ *
676
+ * A host that must remember something will eventually not, which is the
677
+ * shape this repo keeps meeting. So the signal comes from the pipeline that
678
+ * already knows — the same one that emits the errors — and no host has to
679
+ * wire anything. `noteSuccess()` stays for a host with a better signal of its
680
+ * own; it is no longer what the policy depends on.
681
+ */
682
+ onSuccess(listener: RpcSuccessListener): () => void;
683
+ /** Emit a success. Called by the same pipeline code that calls `emit`. */
684
+ emitSuccess(event: RpcSuccess): void;
685
+ }
686
+
687
+ /** Where the failure originated, classified only as far as the client can
688
+ * prove. In particular, `transport` does NOT mean the server definitely saw
689
+ * nothing: a connection can disappear after a request was accepted but before
690
+ * its response reached the browser. */
691
+ declare type RpcErrorKind = 'transport' | 'handler' | 'client' | 'unknown';
692
+
693
+ declare type RpcErrorListener = (event: RpcError) => void;
694
+
695
+ /** A call that SUCCEEDED. Carries only its source and tag — there is no payload
696
+ * here on purpose: this channel exists so cross-cutting policy can tell
697
+ * "working again" from "still broken", not so listeners can read data. */
698
+ declare interface RpcSuccess {
699
+ readonly source: 'mutation' | 'action' | 'subscription';
700
+ readonly tag: string;
701
+ }
702
+
703
+ declare type RpcSuccessListener = (event: RpcSuccess) => void;
704
+
705
+ declare interface ServerRequestContextValue {
706
+ readonly cookies: Readonly<Record<string, string>>;
707
+ readonly headers: Readonly<Record<string, string>>;
708
+ /** Raw request URL as it came off the wire (path + query). Useful
709
+ * for SSR pages that need to read `?q=…` style search params
710
+ * without touching anything client-only. Empty string for build-
711
+ * time SSG renders where there is no incoming request. */
712
+ readonly url: string;
713
+ /** Present ONLY on the 422 re-render of a failed no-JS form POST:
714
+ * the submitted values + field errors, keyed by formKey. Travels on
715
+ * the EXISTING request context deliberately — a dedicated provider
716
+ * would add a fiber fork the client boot does not have, and every
717
+ * ancestor arity difference shifts every useId in the app. */
718
+ readonly formFlash?: FormFlashPayload;
719
+ }
720
+
721
+ declare type ShellKind = 'browser' | 'expo' | 'tauri' | 'electron' | 'node' | 'test';
722
+
723
+ /** One seeded value, as it travels in the hydration payload. */
724
+ declare interface StoreSeed {
725
+ readonly store: string;
726
+ readonly key?: string;
727
+ readonly value: unknown;
728
+ }
729
+
730
+ /** The synchronous subset of the DOM `Storage` interface a persisted store
731
+ * needs. `removeItem` is optional — nothing in the store layer clears keys. */
732
+ declare interface StoreStorage {
733
+ readonly getItem: (key: string) => string | null;
734
+ readonly setItem: (key: string, value: string) => void;
735
+ readonly removeItem?: (key: string) => void;
736
+ }
737
+
738
+ /** Which area a store asked for. Platforms without a session/local split map
739
+ * both onto one backing store; that is expected, not a downgrade. */
740
+ declare type StoreStorageArea = 'local' | 'session';
741
+
742
+ /** A backing store provider: given the requested area, return the storage to
743
+ * use, or `null` for "there is none here" (the store then does not persist). */
744
+ declare type StoreStorageProvider = (area: StoreStorageArea) => StoreStorage | null;
745
+
746
+ declare class SubscriptionCache {
747
+ private readonly entries;
748
+ private readonly entriesByTable;
749
+ private readonly entriesByTag;
750
+ private readonly entriesByMutation;
751
+ private readonly patchMemberships;
752
+ private readonly entryOrder;
753
+ private orderedMemberships;
754
+ private nextEntryOrder;
755
+ /** Standing optimistic intents, by mutation id — see `autoApply`. */
756
+ private readonly intents;
757
+ private readonly tableRows;
758
+ private readonly anyListeners;
759
+ private readonly tableListeners;
760
+ private readonly refreshing;
761
+ /**
762
+ * Same-subject runtime replacement. A mutation may settle against the cache
763
+ * it started on after React has already switched to the replacement cache.
764
+ * Keep this link one-way so staging and settlement follow the visible data
765
+ * without retaining an old cache from the new runtime.
766
+ */
767
+ private successor;
768
+ private readonly inactiveTtlMs;
769
+ private readonly onChangeHook;
770
+ private readonly errorBus;
771
+ private readonly mirror;
772
+ private readonly mergeCell;
773
+ private readonly apiName;
774
+ private readonly recoveryStuckMs;
775
+ constructor(options?: SubscriptionCacheOptions);
776
+ private diagnose;
777
+ /**
778
+ * Register a subscriber. The cache forks the underlying fiber on the
779
+ * first subscriber and re-uses it for the rest. Returns the snapshot
780
+ * getter, the per-subscriber notify-on-change hook, and an unsubscribe
781
+ * function.
782
+ *
783
+ * `fetch` is invoked once per live stream attempt (it builds the Effect
784
+ * Stream against the runtime). Concurrent subscribers piggy-back on that
785
+ * stream; a transport recovery may invoke it again to replace the terminal
786
+ * fiber left by the failed socket.
787
+ */
788
+ subscribe(keyArr: ReadonlyArray<unknown>, fetch: () => Stream.Stream<SubscriptionEvent<unknown>, unknown, never>, runtime: AnyRuntime, onChange: () => void, options?: {
789
+ readonly source?: string | ReadonlyArray<string>;
790
+ }): {
791
+ readonly getSnapshot: () => CacheSnapshot<unknown>;
792
+ readonly unsubscribe: () => void;
793
+ };
794
+ /**
795
+ * Stage an optimistic patch against `keyArr`. Subscribers see the
796
+ * patched value on the next snapshot read. Returns a handle for manual
797
+ * revert (the canonical revert is via `revertByMutation` once the
798
+ * mutation resolves).
799
+ *
800
+ * If the entry doesn't exist yet (mutation fires before its
801
+ * subscription mounts — uncommon but possible), we create a stub entry
802
+ * with no fiber. When a subscription later mounts for the same key,
803
+ * the patch is preserved and the fiber is forked normally.
804
+ */
805
+ update<T>(keyArr: ReadonlyArray<unknown>, reducer: (current: T) => T, mutationId: string): {
806
+ readonly revert: () => void;
807
+ readonly patchId: string;
808
+ };
809
+ /**
810
+ * Patch every cached entry whose rpc tag matches `tag`, regardless of
811
+ * the input the subscription was opened with. The escape hatch for
812
+ * sourceless queries — joins, aggregates, custom-projection routes —
813
+ * that the auto-optimistic source-router can't reach.
814
+ *
815
+ * Usage from `.withOptimistic`:
816
+ *
817
+ * create.withOptimistic((cache, input) => {
818
+ * cache.forTag('todos.summary', (current) => ({
819
+ * ...(current as { count: number }),
820
+ * count: (current as { count: number }).count + 1,
821
+ * }))
822
+ * })
823
+ *
824
+ * Returns the number of entries that were patched, so callers can warn
825
+ * if zero entries matched (probably means the tag is misspelt).
826
+ */
827
+ forTag<T>(tag: string, reducer: (current: T) => T, mutationId: string): {
828
+ readonly patchedCount: number;
829
+ };
830
+ /** Drop every patch owned by `mutationId` from EVERY entry. */
831
+ revertByMutation(mutationId: string): void;
832
+ /**
833
+ * Mark a SUCCEEDED mutation's optimistic patches as confirmed. Unlike
834
+ * `revertByMutation` (used on failure), this does NOT drop them — they stay
835
+ * visible until a matching post-ACK primary snapshot replaces `base`.
836
+ * This removes the on→off→on flash where dropping the patch on mutation
837
+ * resolve briefly exposes a stale base before the server delta lands.
838
+ */
839
+ confirmByMutation(mutationId: string): void;
840
+ /**
841
+ * The confirmed-patch window expired: a committed write never got its
842
+ * superseding server event. Re-issue the affected subscriptions instead of
843
+ * discarding the write's preview.
844
+ *
845
+ * Three things are load-bearing, and each was a way to reintroduce the bug:
846
+ *
847
+ * - **The patch is KEPT across the resync.** `refreshAll` already
848
+ * establishes that shape ("the new base snapshot will land on top of
849
+ * them"). Clearing it here would be the revert again, wearing a longer
850
+ * word.
851
+ * - **A stub entry — no `fetch`, no `runtime` — is left ALONE.** There is
852
+ * nothing to re-issue, and the only other option is to show a base the
853
+ * client knows is stale. Keeping the patch is the honest state.
854
+ * - **It is LOUD.** The reporter found the jump only by reading minified
855
+ * source, because in the UI it is indistinguishable from "the server did
856
+ * not save it" — and that is the false trail they followed first. This
857
+ * goes to the error bus, so it reaches `voltro logs` rather than only a
858
+ * console nobody has open.
859
+ *
860
+ * No second timer is armed: this runs once per mutation, from the one
861
+ * `confirmByMutation` scheduled it, so a server that never echoes cannot put
862
+ * the client into a resync loop.
863
+ */
864
+ private resyncUnechoedMutation;
865
+ /**
866
+ * Auto-derive optimistic patches from a mutation's declared target(s).
867
+ * Iterates every cache entry whose `source` table matches a target's
868
+ * table; applies the canonical patch for the op:
869
+ *
870
+ * - insert : prepend (or append) a row derived from input + an
871
+ * `optimistic: true` flag + a generated id.
872
+ * - update : replace the row whose id matches `input.id` (or the
873
+ * custom identify fn from the spec) by merging input
874
+ * fields on top of the current row.
875
+ * - delete : filter out the row whose id matches `input.id`.
876
+ *
877
+ * Specs with a custom `shape`/`identify`/`order` function override
878
+ * these defaults. All patches are tagged with `mutationId` for atomic
879
+ * revert.
880
+ */
881
+ autoApply(targets: ReadonlyArray<AutoApplyTarget>, input: Record<string, unknown>, mutationId: string, options?: {
882
+ readonly standing?: boolean;
883
+ }): void;
884
+ /** Whether a standing intent for `mutationId` is still held (see
885
+ * {@link SubscriptionCache.autoApply}). Carried to a same-subject
886
+ * replacement cache, so a stager can tell "already staged" from "new". */
887
+ hasIntent(mutationId: string): boolean;
888
+ private applyIntent;
889
+ private applyStandingIntents;
890
+ /** Drop a specific patch by id. */
891
+ private revertPatch;
892
+ /**
893
+ * Read the current snapshot for a key WITHOUT subscribing. If the
894
+ * entry doesn't exist, returns the "empty" snapshot (data=undefined,
895
+ * revision=-1, no patches). Safe to call from `useSyncExternalStore`'s
896
+ * getSnapshot, which is invoked many times during a single render.
897
+ */
898
+ peek(keyArr: ReadonlyArray<unknown>): CacheSnapshot<unknown>;
899
+ /** Test / debug helper. */
900
+ getEntry(keyArr: ReadonlyArray<unknown>): CacheEntry | undefined;
901
+ /** Test / debug helper. */
902
+ size(): number;
903
+ /**
904
+ * Devtools introspection: snapshot every cache entry's wire state +
905
+ * metadata. Returns plain data (no live references) so consumers can
906
+ * render without worrying about React state-equality.
907
+ *
908
+ * The map is keyed by the cache's stable-key string (same one the
909
+ * fan-out invalidation uses). Entries appear in insertion order;
910
+ * sort at the call site if order matters.
911
+ */
912
+ peekAll(): ReadonlyArray<CacheEntrySnapshot>;
913
+ /** Tear down every entry (used on runtime dispose). */
914
+ destroy(runtime: AnyRuntime): void;
915
+ /**
916
+ * Re-issue every active subscription against the runtime. Used after
917
+ * a soft re-auth (login on the same WebSocket connection) so the
918
+ * server resolves the new subject for each subscription's tenant
919
+ * scope — without dropping the connection.
920
+ *
921
+ * For each entry with a saved fetch:
922
+ * - interrupt the current fiber (stops the old WS subscription)
923
+ * - clear the base state so the next snapshot fully replaces it
924
+ * - re-fork via the saved fetch (new WS subscription with the
925
+ * server's now-current subject for this connection)
926
+ *
927
+ * Subscribers' `onChange` callbacks fire when the new snapshot
928
+ * lands, prompting React to re-render with the post-reauth data.
929
+ *
930
+ * Stub entries (no fetch saved yet) are left alone — they'll
931
+ * promote naturally on their next subscriber.
932
+ */
933
+ refreshAll(runtime: AnyRuntime): void;
934
+ /** Refresh one active query without clearing its visible data or optimistic
935
+ * patches. Coalesce refreshes until that request answers or fails; never
936
+ * interrupt an initial read merely because another refresh was requested. */
937
+ refresh(key: ReadonlyArray<unknown>): boolean;
938
+ /* Excluded from this release type: resumeTransportFailures */
939
+ /**
940
+ * The stall watchdog for one re-issued entry: `recoveryStuckMs` after the
941
+ * re-issue with neither snapshot nor delta, the entry is reported stuck and
942
+ * its subscribers are notified.
943
+ *
944
+ * That is a finding only if the watchdog itself ran on time. A browser
945
+ * throttles timers in a hidden tab — to a one-second grid, then a one-minute
946
+ * grid — so a timer there fires whenever the tab next wakes, and it used to
947
+ * report the interval it was ARMED with as the interval waited. A delivery
948
+ * queued behind the same throttling then arrived a moment after the warning
949
+ * and the invalidation, under the same attempt: the watchdog had measured
950
+ * its own delay and called it a stall.
951
+ *
952
+ * So the watchdog compares its due time with its fire time. Late beyond the
953
+ * tolerance, or firing in a hidden tab, it does not judge: it records ONE
954
+ * `recovery-timer-late` for the attempt (with how late, and whether hidden)
955
+ * and re-arms. The first on-time fire in a visible tab decides — which gives
956
+ * a delivery `recoveryStuckMs` of unthrottled time once the tab is looked at
957
+ * again, and reports a real stall within that.
958
+ */
959
+ private armRecoveryWatchdog;
960
+ /**
961
+ * Re-issue ONE entry's subscription: interrupt the fiber, reset the base,
962
+ * re-fork through the saved `fetch`.
963
+ *
964
+ * Extracted so `refreshAll` and the confirmed-patch resync cannot disagree
965
+ * about it — and the thing they must agree on is that **optimistic patches
966
+ * survive**. For a re-auth they belong to in-flight mutations; for the resync
967
+ * they describe a write the server has already committed. Dropping them here
968
+ * would be a revert with a longer name, which is the defect the resync exists
969
+ * to remove.
970
+ */
971
+ private reissue;
972
+ /**
973
+ * Seed this (fresh) cache with the last-known-good rows held by the cache it
974
+ * REPLACES, so a transport rebuild degrades to STALE DATA rather than to
975
+ * skeletons.
976
+ *
977
+ * A reconnect builds an entirely new client stack — new runtime, new socket,
978
+ * new cache — and the new cache starts empty, so every live `useSubscription`
979
+ * went `data: undefined` → `loading: true` and the whole app blanked until
980
+ * each stream's first snapshot round-tripped. Carrying the previous `base`
981
+ * over is the same trick `initialSnapshot` plays for SSR: render real (if
982
+ * momentarily old) data now, let the first server snapshot replace it.
983
+ *
984
+ * What is carried and what is NOT:
985
+ *
986
+ * - Only entries that actually HOLD server data (`base !== undefined`).
987
+ * A pending or cold-start-failed entry has nothing better than the
988
+ * loading state it is already in.
989
+ * - `baseError` is dropped: the new transport gets to re-establish the
990
+ * truth, and a stale error banner over live data is worse than neither.
991
+ * - Optimistic patches are carried. A transport failure has an UNKNOWN
992
+ * unary outcome, not a proven failure, and removing the preview before a
993
+ * safe replay settles would flash stale data. The old cache links to this
994
+ * one so later stage/confirm/revert operations reach the visible copy.
995
+ * - Seeded entries carry no fiber and no fetch, exactly like the stub
996
+ * entries a pre-mount optimistic patch creates. The first `subscribe()`
997
+ * promotes one: it saves the fetch and forks the stream, with the seeded
998
+ * `base` still in place, so the component never sees `undefined`.
999
+ *
1000
+ * **Caller contract — this must only be used for a SAME-SUBJECT swap.** The
1001
+ * caller (the api supervisor) gates it on the rebuild being transport-driven.
1002
+ * A rebuild that exists to re-resolve WHO the connection is (login, logout,
1003
+ * tenant switch) must NOT seed: the next subject may be entitled to strictly
1004
+ * less, and painting the previous subject's rows into their screens is a data
1005
+ * exposure, not a UX win. That is also why `refreshAll` above clears `base`
1006
+ * outright — same reasoning, same boundary.
1007
+ *
1008
+ * Returns the number of entries seeded (diagnostics / tests).
1009
+ */
1010
+ seedStaleFrom(previous: SubscriptionCache): number;
1011
+ private create;
1012
+ private createStub;
1013
+ private freshState;
1014
+ private startFiber;
1015
+ private sourceTables;
1016
+ private addIndex;
1017
+ private removeIndex;
1018
+ private orderedEntries;
1019
+ private indexSource;
1020
+ private appendPatch;
1021
+ private replacePatches;
1022
+ private indexPatches;
1023
+ private registerEntry;
1024
+ private unindexEntry;
1025
+ private invalidate;
1026
+ /**
1027
+ * Every row of `table` this cache holds — the client's local replica of the
1028
+ * table: the union of the rows of every entry sourced on that table ALONE
1029
+ * (an entry over several tables holds joined shapes, not rows of one),
1030
+ * optimistic previews and mirror-seeded rows included, deduplicated by `id`.
1031
+ * Memoised per table until the next change, so the result is reference-stable
1032
+ * for `useSyncExternalStore`.
1033
+ */
1034
+ rowsOf(table: string): ReadonlyArray<Readonly<Record<string, unknown>>>;
1035
+ /** Subscribe to cache changes affecting this source table only. */
1036
+ subscribeTable(table: string, listener: () => void): () => void;
1037
+ /** Call `listener` after any entry changed. Returns the unsubscribe. */
1038
+ subscribeAny(listener: () => void): () => void;
1039
+ private getSnapshot;
1040
+ private unsubscribe;
1041
+ /** Start (or restart) the inactive-TTL countdown for `entry`: unless
1042
+ * something subscribes first, interrupt its fiber and drop it. Shared by
1043
+ * the last-subscriber-out path and by `seedStaleFrom`'s unclaimed seeds. */
1044
+ private scheduleEviction;
1045
+ }
1046
+
1047
+ declare interface SubscriptionCacheOptions {
1048
+ /** Durable local mirror (see {@link SubscriptionMirror}). */
1049
+ readonly mirror?: SubscriptionMirror;
1050
+ /**
1051
+ * CRDT cell merger for the downstream lane (plan 18): folds a
1052
+ * `mergeCells` delta op's incremental update into the held cell. The one
1053
+ * real implementation is `crdtMergeCell` from `@voltro/local-first` (this
1054
+ * package stays CRDT-library-free). Absent → the merger registered with
1055
+ * `registerCellMerger` (`@voltro/local-first` registers `crdtMergeCell` on
1056
+ * import); with none at all, a mergeCells op replaces the cell.
1057
+ */
1058
+ readonly mergeCell?: (column: string, prevValue: unknown, update: unknown) => unknown;
1059
+ /** Milliseconds to keep an entry alive after the last subscriber leaves.
1060
+ * Lets back-button / quick remount reuse the warm subscription. */
1061
+ readonly inactiveTtlMs?: number;
1062
+ /** Debug hook fired on every cache state change. */
1063
+ readonly onChange?: (key: string) => void;
1064
+ /** Optional error bus — when a subscription stream errors out, the
1065
+ * cache reports it to the bus so global listeners (e.g. auto-logout
1066
+ * on Unauthenticated) can react. */
1067
+ readonly errorBus?: RpcErrorBus;
1068
+ /** Logical api name for payload-free diagnostics. Omit for standalone caches. */
1069
+ readonly apiName?: string;
1070
+ /** Time after a transport reissue with no delivery before one stuck event. */
1071
+ readonly recoveryStuckMs?: number;
1072
+ }
1073
+
1074
+ /**
1075
+ * Durable local mirror seam (plan 02 — local-first). `save` fires after every
1076
+ * server event that moved an entry's base (snapshot or delta) with the rows
1077
+ * AND the revision; `load` runs once for a COLD entry (no server data yet)
1078
+ * and, when it resolves first, seeds the entry so the UI renders mirrored
1079
+ * rows offline — and the NEXT (re)subscribe presents the mirrored revision as
1080
+ * `voltro-resume-from`, composing with delta-resume. The implementation
1081
+ * (`@voltro/local-first`'s query mirror) owns partitioning, encrypted-column
1082
+ * stripping and which tags mirror at all — the cache calls it for every
1083
+ * entry and a foreign tag is the mirror's no-op.
1084
+ */
1085
+ declare interface SubscriptionMirror {
1086
+ readonly load: (key: string) => Promise<{
1087
+ readonly data: unknown;
1088
+ readonly revision: number;
1089
+ } | undefined>;
1090
+ readonly save: (key: string, snap: {
1091
+ readonly tag: string | undefined;
1092
+ readonly data: unknown;
1093
+ readonly revision: number;
1094
+ }) => Promise<void>;
1095
+ /**
1096
+ * Queries to keep subscribed for the whole connection generation, as
1097
+ * `[tag, input]` — so they are mirrored, and readable offline, before any
1098
+ * screen ever opened them. Offline coverage is otherwise "what the user
1099
+ * happened to visit"; this makes it a declaration.
1100
+ */
1101
+ readonly warm?: ReadonlyArray<readonly [tag: string, input: Readonly<Record<string, unknown>>]>;
1102
+ /**
1103
+ * Tags to keep warm with an EMPTY input — each one whose declared input
1104
+ * schema accepts `{}` (a list, a feed, a settings read). The runtime makes
1105
+ * that check against the descriptors; a tag that needs parameters is left
1106
+ * out rather than subscribed into an error.
1107
+ */
1108
+ readonly warmTags?: ReadonlyArray<string>;
1109
+ }
1110
+
1111
+ /**
1112
+ * Where a credential lives. `kind` says how it is protected; a store that
1113
+ * cannot protect anything says so (`'none'`) and refuses to write, rather
1114
+ * than falling back to plain storage — a session token in a key-value store
1115
+ * is the defect this port exists to make impossible.
1116
+ */
1117
+ declare interface TokenStore {
1118
+ readonly kind: 'keychain' | 'keystore' | 'credential-manager' | 'stronghold' | 'memory' | 'none';
1119
+ readonly get: (key: string) => Promise<string | null>;
1120
+ readonly set: (key: string, value: string) => Promise<void>;
1121
+ readonly delete: (key: string) => Promise<void>;
1122
+ }
1123
+
1124
+ /** How the running code gets replaced: a service worker, a desktop updater,
1125
+ * an OTA bundle. `apply` is the restart/reload; callers gate it on an empty
1126
+ * outbox. */
1127
+ export declare interface UpdateChannel {
1128
+ readonly check: () => Promise<UpdateInfo | null>;
1129
+ readonly apply: () => Promise<void>;
1130
+ readonly subscribe?: (onAvailable: (update: UpdateInfo) => void) => () => void;
1131
+ }
1132
+
1133
+ export declare interface UpdateInfo {
1134
+ readonly version: string;
1135
+ readonly notes?: string;
1136
+ }
1137
+
1138
+ /** The running platform: info, capabilities and ports. Re-renders when an
1139
+ * adapter is installed after mount. */
1140
+ export declare const usePlatform: () => PlatformAdapter;
1141
+
1142
+ export declare const useServerRequest: () => ServerRequestContextValue | null;
1143
+
1144
+ export { }