@lunora/client 1.0.0-alpha.3 → 1.0.0-alpha.300

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 (100) hide show
  1. package/LICENSE.md +207 -104
  2. package/README.md +24 -7
  3. package/dist/admin/index.d.mts +689 -0
  4. package/dist/admin/index.d.ts +689 -0
  5. package/dist/admin/index.mjs +1 -0
  6. package/dist/auth/index.d.mts +174 -13
  7. package/dist/auth/index.d.ts +174 -13
  8. package/dist/auth/index.mjs +1 -60
  9. package/dist/index.d.mts +1121 -190
  10. package/dist/index.d.ts +1121 -190
  11. package/dist/index.mjs +1 -14
  12. package/dist/packem_shared/ADMIN_AUTH_DEFAULT_PAGE_SIZE-aKbm8N1z.mjs +1 -0
  13. package/dist/packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs +1 -0
  14. package/dist/packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs +1 -0
  15. package/dist/packem_shared/LunoraAdminClient-ClQxFDiy.mjs +1 -0
  16. package/dist/packem_shared/LunoraClient-D8eDGCKr.mjs +1 -0
  17. package/dist/packem_shared/OfflineQueue-BGkx7pBL.mjs +1 -0
  18. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  19. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  20. package/dist/packem_shared/SubscriptionRegistry-DjFfxba2.mjs +1 -0
  21. package/dist/packem_shared/TabCoordinator-DIySdaRV.mjs +1 -0
  22. package/dist/packem_shared/applyDelta-CaudNj2C.mjs +1 -0
  23. package/dist/packem_shared/base64-849R7V-V.mjs +1 -0
  24. package/dist/packem_shared/client-tuning-C10B2KCO.mjs +1 -0
  25. package/dist/packem_shared/client-urls-BHLUjjcG.mjs +1 -0
  26. package/dist/packem_shared/connectLiveStream-BdjsWP1-.mjs +1 -0
  27. package/dist/packem_shared/createAsyncStoragePersistence-BgfdvLwe.mjs +1 -0
  28. package/dist/packem_shared/createAsyncStorageQueryCache-6Y94ocbQ.mjs +1 -0
  29. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  30. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  31. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  32. package/dist/packem_shared/createInMemoryPersistence-C-IzNVbg.mjs +1 -0
  33. package/dist/packem_shared/createInMemoryQueryCache-DR6AorA2.mjs +1 -0
  34. package/dist/packem_shared/createLocalStore-WKNHD1ca.mjs +1 -0
  35. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  36. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  37. package/dist/packem_shared/createServerClient-CcH_sS6i.mjs +1 -0
  38. package/dist/packem_shared/createSnapshotPrecondition-BXP1NPBW.mjs +1 -0
  39. package/dist/packem_shared/delta-merge-C6OqMEPH.mjs +1 -0
  40. package/dist/packem_shared/deserializePreloaded-DxozvweR.mjs +1 -0
  41. package/dist/packem_shared/frame-hint-D-NK691z.mjs +1 -0
  42. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  43. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  44. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  45. package/dist/packem_shared/httpStream-DN3D9WqW.mjs +7 -0
  46. package/dist/packem_shared/idb-utility-BS7xvou1.mjs +1 -0
  47. package/dist/packem_shared/live-stream-DBKgZlnb.mjs +10 -0
  48. package/dist/packem_shared/liveTopicSubscription-DQtKMFKw.mjs +1 -0
  49. package/dist/packem_shared/lunora-client-BC2DJGwq.mjs +1 -0
  50. package/dist/packem_shared/lunora-client.d-BswMNnv7.d.mts +5060 -0
  51. package/dist/packem_shared/lunora-client.d-TchceUzJ.d.ts +5060 -0
  52. package/dist/packem_shared/lunoraQueryKey-CucWmxnx.mjs +1 -0
  53. package/dist/packem_shared/offline-queue-HwrYARIL.mjs +1 -0
  54. package/dist/packem_shared/optimistic-layers-BI61YTO3.mjs +1 -0
  55. package/dist/packem_shared/preload.d-BKdXfr3n.d.ts +21 -0
  56. package/dist/packem_shared/preload.d-qY64gg1w.d.mts +21 -0
  57. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  58. package/dist/packem_shared/setAuthTokenProvider-DhBppDiZ.mjs +1 -0
  59. package/dist/packem_shared/single-blob-store-DeaYPBSS.mjs +1 -0
  60. package/dist/packem_shared/snapshot-precondition-BEtcSbWr.mjs +1 -0
  61. package/dist/packem_shared/stream-idle-C7CsIT_m.mjs +1 -0
  62. package/dist/packem_shared/wire-errors-BDckSTKZ.mjs +1 -0
  63. package/dist/pagination/index.d.mts +72 -43
  64. package/dist/pagination/index.d.ts +72 -43
  65. package/dist/pagination/index.mjs +1 -61
  66. package/dist/query/index.d.mts +183 -44
  67. package/dist/query/index.d.ts +183 -44
  68. package/dist/query/index.mjs +1 -1
  69. package/dist/service.d.mts +49 -0
  70. package/dist/service.d.ts +49 -0
  71. package/dist/service.mjs +1 -0
  72. package/dist/ssr/index.d.mts +109 -80
  73. package/dist/ssr/index.d.ts +109 -80
  74. package/dist/ssr/index.mjs +1 -4
  75. package/dist/upload.d.mts +49 -0
  76. package/dist/upload.d.ts +49 -0
  77. package/dist/upload.mjs +1 -0
  78. package/package.json +22 -2
  79. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  80. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  81. package/dist/packem_shared/LunoraClient-UiULzH_1.mjs +0 -2165
  82. package/dist/packem_shared/OfflineQueue-D5p_QgF_.mjs +0 -127
  83. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  84. package/dist/packem_shared/SubscriptionRegistry-B-Qx_Gux.mjs +0 -26
  85. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  86. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  87. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  88. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +0 -105
  89. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +0 -138
  90. package/dist/packem_shared/createLocalStore-DSUfoLqY.mjs +0 -36
  91. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  92. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  93. package/dist/packem_shared/createServerClient-BjZc3gD8.mjs +0 -11
  94. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  95. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  96. package/dist/packem_shared/lunora-client.d-DGvyuJ_p.d.mts +0 -1597
  97. package/dist/packem_shared/lunora-client.d-DGvyuJ_p.d.ts +0 -1597
  98. package/dist/packem_shared/preload.d-BoDmFqSG.d.ts +0 -20
  99. package/dist/packem_shared/preload.d-dSaRMuhL.d.mts +0 -20
  100. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
package/dist/index.d.ts CHANGED
@@ -1,13 +1,199 @@
1
- import { c as PersistenceAdapter, B as BookmarkStorage, F as FunctionReference, A as ArgsOf, M as MutationCallOptions, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, d as ReconnectOptions } from "./packem_shared/lunora-client.d-DGvyuJ_p.js";
2
- export { type C as CachedQuery, type e as ClientMessage, type f as ConnectionStatus, D as DEFAULT_MAX_BUFFER, type g as FunctionArgumentDescriptor, type h as FunctionDescriptor, type G as GlobalFacetResult, type i as GlobalFacetValue, type j as GlobalFilterClause, type k as GlobalTableInfo, type l as GlobalTablePage, L as LunoraClient, type m as LunoraClientOptions, type n as OptimisticLocalStore, type o as OptimisticUpdate, type p as PersistedMutation, type P as Preloaded, type q as RpcEnvelope, type r as RpcResponseBody, type s as ScheduleRecord, type t as SchedulerPoolStatus, type u as SchedulerStatus, type v as ServerMessage, type w as ShardTrafficEntry, type x as ShardTrafficResult, type y as StorageListPage, type z as StorageObject, type E as StreamHandle, type H as StreamIterable, type I as SubscriptionCallback, type S as SubscriptionError, type b as SubscriptionErrorCallback, J as SubscriptionRegistry, type K as SubscriptionState, type a as Unsubscribe, type U as User, type W as WorkflowInstanceAction, type N as WorkflowInstanceDetail, type T as WorkflowInstancePage, type V as WorkflowInstanceStatus, type X as WorkflowInstanceSummary, type Y as WorkflowStepDetail, Z as createLocalStore, _ as createStream } from "./packem_shared/lunora-client.d-DGvyuJ_p.js";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-BoDmFqSG.js";
4
- export type { AuthCapabilities, AuthImpersonation, AuthPage, AuthSession, AuthUser, CronJobInfo, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
5
- /**
6
- * The slice of React Native's `AsyncStorage` (or any async key/value store —
7
- * Expo `SecureStore`, a wrapped `localForage`, an in-memory map in tests) this
8
- * adapter needs. Matches `@react-native-async-storage/async-storage`'s core
9
- * surface, so you can pass the module straight in.
10
- */
1
+ import { R as ReconnectOptions, c as PersistenceAdapter, Q as QueryCacheAdapter, L as LunoraClient, a as Unsubscribe, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions } from "./packem_shared/lunora-client.d-TchceUzJ.js";
2
+ export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, type p as CronRunInFlight, type q as CronRunRecord, type r as CronRunStatus, type s as CronRunsResult, D as DEFAULT_MAX_BUFFER, type t as DeploymentPauseStatus, type F as FunctionArgumentDescriptor, type u as FunctionDescriptor, type G as GlobalFacetResult, type v as GlobalFacetValue, type w as GlobalFilterClause, type x as GlobalTableInfo, type y as GlobalTablePage, type z as HttpStreamCallArgs, type E as LunoraClientError, type I as LunoraClientOptions, type M as MutationCallOptions, type J as MutationSettledEvent, type K as OnlineOnlyOption, type N as OptimisticLocalStore, type T as OptimisticUpdate, type V as OutboxMutation, type W as OutboxSink, type X as PersistedMutation, type P as Preloaded, type Y as ReplayCredential, type Z as ReplayIdentityVerdict, type _ as RoomRef, type $ as RowOp, type a0 as RpcEnvelope, type a1 as RpcResponseBody, type a2 as ScheduleRecord, type a3 as ScheduleRetryPolicy, type a4 as ScheduledHistoryPage, type a5 as ScheduledJobState, type a6 as ScheduledJobView, type a7 as SchedulerPoolStatus, type a8 as SchedulerStatus, type a9 as ServerMessage, type aa as ServerPokeEndMessage, type ab as ServerPokePartMessage, type ac as ServerPokeStartMessage, type ad as ShardTrafficEntry, type ae as ShardTrafficResult, type af as StorageListPage, type ag as StorageObject, type ah as StoredQuery, type ai as StreamHandle, type aj as SubscriptionCallback, type b as SubscriptionErrorCallback, ak as SubscriptionRegistry, type al as SubscriptionState, type am as SyncStatus, type an as SyncWatermark, type U as User, type ao as WorkflowInstanceAction, type ap as WorkflowInstanceCreated, type aq as WorkflowInstanceDetail, type ar as WorkflowInstancePage, type as as WorkflowInstanceStatus, type at as WorkflowInstanceSummary, type au as WorkflowStepDetail, type av as WsTokenProvider, aw as createClientQuery, ax as createLocalStore, ay as createStream } from "./packem_shared/lunora-client.d-TchceUzJ.js";
3
+ import { LunoraError, LunoraErrorCode } from '@lunora/errors';
4
+ export type { LunoraErrorCode } from '@lunora/errors';
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-BKdXfr3n.js";
6
+ import { F as FunctionReference } from "./packem_shared/function-reference.d-Br_hsKje.js";
7
+ export type { A as ArgsOf, R as ReturnOf } from "./packem_shared/function-reference.d-Br_hsKje.js";
8
+ export type { AdminTokenSummary, AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CreatedAdminToken, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
9
+ /**
10
+ * A failure the SERVER reached no verdict on: the response carried no
11
+ * `{ error }` envelope at all — no `fetch` implementation, a non-JSON body from
12
+ * a proxy, a bare 5xx gateway page.
13
+ *
14
+ * The distinction matters because a durable write must be re-queued rather than
15
+ * dropped, and `code` cannot carry it: these arrive as `INTERNAL`, which is also
16
+ * what a server that DID reach a verdict sends. It used to be a `Symbol` stamped
17
+ * on with `Object.assign` and read back through a `Record<symbol, unknown>`
18
+ * cast, so the one classifier that knew the convention was the only reader that
19
+ * could ever see it. As a kind, every reader can: `error instanceof
20
+ * TransportError`.
21
+ *
22
+ * Still `INTERNAL` on the wire, so nothing that switches on `code` changes.
23
+ *
24
+ * `data` carries the structured payload such an error can still have — the
25
+ * `{ retryAfterMs }` a `Retry-After` on the unreadable response named, which
26
+ * {@link getRetryAfterMs} reads back and the outbox paces its retry on.
27
+ */
28
+ declare class TransportError extends LunoraError {
29
+ constructor(message: string, data?: unknown);
30
+ }
31
+ /** Error code the server uses for optimistic-concurrency conflicts (HTTP 409). */
32
+ declare const CONFLICT_ERROR_CODE = "CONFLICT";
33
+ /**
34
+ * Whether an unknown rejection is an optimistic-concurrency conflict — the
35
+ * server lost a write race and the caller should refetch and retry (or surface
36
+ * the conflict). Structural check on the `code` property the client attaches
37
+ * when decoding the worker's `{ error: { code, message } }` envelope.
38
+ */
39
+ declare const isConflictError: (error: unknown) => error is Error & {
40
+ code: "CONFLICT";
41
+ };
42
+ /**
43
+ * Whether a rejection is an RLS/policy denial (`FORBIDDEN`, HTTP 403) — the
44
+ * caller is authenticated but not permitted to read/write the row. The most
45
+ * common per-call error a UI must handle in an RLS-first app.
46
+ */
47
+ declare const isForbiddenError: (error: unknown) => error is Error & {
48
+ code: "FORBIDDEN";
49
+ };
50
+ /** Whether a rejection is an authentication failure (`UNAUTHORIZED`, HTTP 401) — no/invalid identity. */
51
+ declare const isUnauthorizedError: (error: unknown) => error is Error & {
52
+ code: "UNAUTHORIZED";
53
+ };
54
+ /**
55
+ * Whether a rejection is a rate-limit denial (`TOO_MANY_REQUESTS`, HTTP 429).
56
+ * The retry hint (if the server sent one) is read with {@link getRetryAfterMs}.
57
+ */
58
+ declare const isRateLimitedError: (error: unknown) => error is Error & {
59
+ code: "TOO_MANY_REQUESTS";
60
+ };
61
+ /**
62
+ * Read the server's machine-readable `code` off a rejection, narrowed to the
63
+ * known {@link LunoraErrorCode} union. Returns `undefined` for a non-`Error`, a
64
+ * missing code, or a code string absent from the catalog (an app-minted code
65
+ * passed to `LunoraError` reads as `undefined` here rather than being falsely
66
+ * narrowed).
67
+ */
68
+ declare const getErrorCode: (error: unknown) => LunoraErrorCode | undefined;
69
+ /**
70
+ * Read the rate-limit retry hint (`data.retryAfterMs`) off a
71
+ * `TOO_MANY_REQUESTS` rejection without hand-casting the `unknown` `data`
72
+ * payload. Returns the finite millisecond value the server sent, or `undefined`
73
+ * when absent/non-numeric. Pair with {@link isRateLimitedError}.
74
+ */
75
+ declare const getRetryAfterMs: (error: unknown) => number | undefined;
76
+ /**
77
+ * Whether a durable replay's failure refused the credential rather than the
78
+ * write (see {@link AUTH_REPLAY_ERROR_CODES}) — a durable outbox holds such a
79
+ * write for the next attempt instead of dropping it.
80
+ */
81
+ declare const isAuthReplayFailure: (error: unknown) => boolean;
82
+ /**
83
+ * Exponential backoff calculator with optional jitter.
84
+ *
85
+ * `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
86
+ * enabled the returned value is randomized in `[delay/2, delay]` so a fleet
87
+ * of clients reconnecting at the same time spread out their retries.
88
+ */
89
+ interface ReconnectCalculator {
90
+ /** Returns the delay to wait before the next reconnect attempt. */
91
+ next: () => number;
92
+ /** Resets the backoff to the initial delay (call on successful reconnect). */
93
+ reset: () => void;
94
+ }
95
+ declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
96
+ /**
97
+ * Optimistic-reconcile logic shared by every `@lunora/*` framework adapter's
98
+ * agent-chat surface (`@lunora/react` `useAgentChat`, plus the `@lunora/vue`,
99
+ * `@lunora/solid`, `@lunora/svelte`, and `@lunora/angular` counterparts). The
100
+ * adapters keep only their framework-specific state plumbing
101
+ * (`useState` / `.value` / `.set()` / a store) and delegate the pure merge decision
102
+ * here, so the heuristic lives — and is tested — in exactly one place.
103
+ */
104
+ /**
105
+ * The durable-message shape the reconcile reads: a structural subset of each
106
+ * adapter's `AgentChatMessage` (itself a client-safe mirror of `@lunora/agent`'s
107
+ * `AgentMessageRow`). Only `content`, `role`, and the per-thread-monotonic `seq` are
108
+ * consulted; adapters pass their fuller row type, which is assignable to this.
109
+ */
110
+ interface ReconcileDurableMessage {
111
+ content: string;
112
+ role: "assistant" | "system" | "tool" | "user";
113
+ seq: number;
114
+ }
115
+ /**
116
+ * A local optimistic user turn awaiting server acknowledgement. `id` is a
117
+ * client-generated handle the adapter uses to roll the row back on a failed send;
118
+ * the reconcile itself reads only `content` and `maxDurableSeqAtSend`.
119
+ */
120
+ interface OptimisticMessage {
121
+ content: string;
122
+ id: number;
123
+ /**
124
+ * The highest durable `seq` present when this row was sent. The reconcile
125
+ * retires the row when a durable `user` row with matching `content` lands at a
126
+ * STRICTLY GREATER `seq` (i.e. after the send) — window-independent because
127
+ * `seq` is monotonic, not a positional count. Also the age baseline for the
128
+ * {@link RETIRE_AFTER_DURABLE_SEQ_ADVANCE} fallback.
129
+ *
130
+ * `seq` is monotonic PER THREAD, not globally (`@lunora/agent` assigns it from
131
+ * the thread's own message count), so a baseline captured in one thread is
132
+ * meaningless in another: an optimistic row carried across a thread switch can
133
+ * never be retired by the new thread's history until its `seq` happens to pass
134
+ * the old thread's. Adapters therefore drop their optimistic rows whenever the
135
+ * resolved thread key changes.
136
+ */
137
+ maxDurableSeqAtSend: number;
138
+ }
139
+ /**
140
+ * The highest `seq` across `messages`, or `-1` when empty. Used both to capture an
141
+ * optimistic row's `maxDurableSeqAtSend` at send time and to base the synthetic
142
+ * seqs of rendered optimistic rows above the highest real durable seq (not just
143
+ * `messages.length`, which under-counts when durable rows have gaps), so a
144
+ * placeholder seq never collides with a real one.
145
+ */
146
+ declare const maxSeq: (messages: ReadonlyArray<{
147
+ seq: number;
148
+ }>) => number;
149
+ /**
150
+ * Secondary, windowed fallback: retire a pending optimistic row once the durable
151
+ * history's highest `seq` has advanced at least this far past the value seen at
152
+ * send, even though no matching-content user row is currently visible to claim it.
153
+ * This covers the pathological "identical content already present at send time"
154
+ * case, where no user row with a STRICTLY GREATER `seq` than the send-time max will
155
+ * ever appear for the primary content match to consume (e.g. the acknowledging row
156
+ * was evicted by a bounded `limit` before reconcile could see it). `seq` is monotonic
157
+ * within the thread, so it keeps climbing even when the visible user-row COUNT does not.
158
+ *
159
+ * The `2` is a heuristic threshold, NOT an invariant about turn shape. It is
160
+ * tempting to read it as "one turn == a user row and an assistant row (+2)", but
161
+ * `@lunora/agent`'s tool-loop turns can persist MANY rows, and an ERRORED turn
162
+ * persists only the user row (+1). Those non-(+2) turns are retired by the PRIMARY
163
+ * seq-based content match below (which sees the user row land at a greater `seq`),
164
+ * never by this count-based fallback. The fully robust fix is a server-echoed
165
+ * correlation id on each persisted user row (deferred; no plan filed).
166
+ *
167
+ * KNOWN LIMITATION (inherent to a client-only heuristic): on an ownerless /
168
+ * `instanceId`-less thread a FOREIGN writer that advances `seq` by >= 2 between this
169
+ * row's send and its own acknowledgement can trip this fallback and retire the row a
170
+ * beat early. The correlation id closes that gap; until then it is the accepted
171
+ * residual edge.
172
+ */
173
+ declare const RETIRE_AFTER_DURABLE_SEQ_ADVANCE = 2;
174
+ /**
175
+ * Drop the optimistic user turns the durable history has now caught up on. Pure —
176
+ * it reads only the two arrays plus values captured on each pending row at send
177
+ * time (no clock, no state mutation), so it is safe to run in render.
178
+ *
179
+ * The primary retire condition: a durable `user` row with the same `content` exists
180
+ * whose `seq` is STRICTLY GREATER than the row's `maxDurableSeqAtSend` — i.e. a user
181
+ * row that landed AFTER the send. This is window-independent (it matches on monotonic
182
+ * `seq`, not a positional count), so it retires the normal turn AND an errored
183
+ * single-row (+1) turn even under a saturated, sliding `limit`. Each durable row is
184
+ * consumed at most once (the `consumed` set), so repeated identical prompts sent
185
+ * back-to-back each wait for their OWN durable row instead of collapsing onto one.
186
+ *
187
+ * Failing that, the {@link RETIRE_AFTER_DURABLE_SEQ_ADVANCE} windowed fallback fires
188
+ * (see its doc) for the "identical content already present" pathological case.
189
+ */
190
+ declare const reconcileOptimistic: (optimistic: ReadonlyArray<OptimisticMessage>, durable: ReadonlyArray<ReconcileDurableMessage>) => OptimisticMessage[];
191
+ /**
192
+ * The slice of React Native's `AsyncStorage` (or any async key/value store —
193
+ * Expo `SecureStore`, a wrapped `localForage`, an in-memory map in tests) this
194
+ * adapter needs. Matches `@react-native-async-storage/async-storage`'s core
195
+ * surface, so you can pass the module straight in.
196
+ */
11
197
  interface AsyncStorageLike {
12
198
  getItem: (key: string) => Promise<string | null>;
13
199
  removeItem: (key: string) => Promise<void>;
@@ -20,132 +206,714 @@ interface AsyncStoragePersistenceOptions {
20
206
  storage: AsyncStorageLike;
21
207
  }
22
208
  /**
23
- * Builds a {@link PersistenceAdapter} over an async key/value store — the React
24
- * Native / Expo counterpart to the IndexedDB adapter (`createIndexedDbPersistence`).
25
- * The whole FIFO mutation log is serialized to JSON under a single key (`key`),
26
- * so enqueue order is preserved and `load()` returns freshly-parsed records that
27
- * callers can't alias.
28
- *
29
- * AsyncStorage has no transactions, so every read-modify-write is funnelled
30
- * through a single promise chain — concurrent `append`/`remove` calls run one at
31
- * a time and can't clobber each other's writes.
32
- */
209
+ * Builds a {@link PersistenceAdapter} over an async key/value store — the React
210
+ * Native / Expo counterpart to the IndexedDB adapter (`createIndexedDbPersistence`).
211
+ * The whole FIFO mutation log is stored under a single key (`key`), so enqueue
212
+ * order is preserved and `load()` returns freshly-parsed records that callers
213
+ * can't alias.
214
+ *
215
+ * Records round-trip through {@link singleBlobStore}'s wire codec. Args it
216
+ * cannot carry (a `RegExp`, a class instance) reject at `append`/`replace` — the
217
+ * flush path rejects them terminally anyway. A blob that exists but can't be
218
+ * decoded loads as empty, and every write rejects rather than overwrite it and
219
+ * lose the queued writes it may still hold; `clear()` discards it.
220
+ *
221
+ * AsyncStorage has no transactions, so every read-modify-write runs through
222
+ * {@link singleBlobStore}'s serialized chain — concurrent `append`/`remove`
223
+ * calls run one at a time and can't clobber each other's writes.
224
+ */
33
225
  declare const createAsyncStoragePersistence: (options: AsyncStoragePersistenceOptions) => PersistenceAdapter;
226
+ interface AsyncStorageQueryCacheOptions {
227
+ /** Storage key the cache is serialized under; defaults to `"lunora:query-cache"`. */
228
+ key?: string;
229
+ /** LRU row cap; defaults to 50 (see {@link DEFAULT_MAX_ENTRIES}). Must be a positive integer. The oldest rows by `ts` are pruned on `put` once exceeded. */
230
+ maxEntries?: number;
231
+ /** The async key/value store the cache is read from and written to (e.g. React Native `AsyncStorage`). */
232
+ storage: AsyncStorageLike;
233
+ }
234
+ /**
235
+ * Builds a {@link QueryCacheAdapter} over an async key/value store — the React
236
+ * Native / Expo counterpart to `createIndexedDbQueryCache`. The whole cache is
237
+ * serialized under a single key (`key`).
238
+ *
239
+ * Values round-trip through {@link singleBlobStore}'s wire codec (a `bigint`,
240
+ * `Date`, or bytes survives a reload); a corrupt blob reads as an empty cache.
241
+ *
242
+ * AsyncStorage has no transactions, so every read-modify-write runs through
243
+ * {@link singleBlobStore}'s serialized chain — concurrent `put`/`remove` calls
244
+ * run one at a time and can't clobber each other's writes.
245
+ *
246
+ * Single-blob storage rewrites the whole cache per `put` (bounded by
247
+ * `maxEntries` — see the cap's note on Android's row and shared-budget limits);
248
+ * if that ever shows up in profiles, per-key storage entries are the upgrade
249
+ * path.
250
+ */
251
+ declare const createAsyncStorageQueryCache: (options: AsyncStorageQueryCacheOptions) => QueryCacheAdapter;
252
+ interface AuthTokenProviderOptions {
253
+ /**
254
+ * The stable user id behind the token, passed as `setAuthToken`'s `subject`
255
+ * so a refreshed token is not mistaken for an account switch (which would
256
+ * reject the queued offline writes `OFFLINE_IDENTITY_CHANGED`).
257
+ */
258
+ subject?: string | null;
259
+ }
260
+ /** A provider token's fetcher: the current token, or `null` once the user is signed out. */
261
+ type AuthTokenFetcher = () => Promise<string | null>;
262
+ /**
263
+ * Keep the client's bearer in sync with an external identity provider (Clerk,
264
+ * WorkOS, Auth0…): fetch a token now, install it with `setAuthToken(token,
265
+ * subject)`, and fetch the next one shortly before the current one's `exp`.
266
+ * `onTokenExpired` (a socket closed `4001`, a refused offline replay) triggers
267
+ * an immediate refresh too.
268
+ *
269
+ * - One timer chain: a refresh in flight is shared, and each refresh replaces
270
+ * the pending timer.
271
+ * - `fetchToken` resolving `null` means signed out: the token is cleared and
272
+ * no refresh is scheduled. Map the provider's "not signed in" error to `null`
273
+ * (WorkOS `LoginRequiredError`; Clerk's `getToken()` already resolves `null`).
274
+ * - Any other error keeps the current token and retries after 5 s.
275
+ *
276
+ * Returns a stop function; call it on unmount or before installing another
277
+ * provider.
278
+ *
279
+ * ```ts
280
+ * const stop = setAuthTokenProvider(client, () => getToken(), { subject: userId });
281
+ * ```
282
+ */
283
+ declare const setAuthTokenProvider: (client: LunoraClient, fetchToken: AuthTokenFetcher, options?: AuthTokenProviderOptions) => Unsubscribe;
34
284
  /** Default in-memory bookmark store. Survives the lifetime of the client. */
35
285
  declare const createInMemoryBookmarkStorage: () => BookmarkStorage;
36
286
  /**
37
- * Client-side incremental merging of structured mutation deltas.
38
- *
39
- * Lunora's live-query fan-out has two server paths:
40
- *
41
- * 1. Server re-execution (subscriptions carrying a `functionPath`) pushes a
42
- * full `data` snapshot whenever a write touches a table the query reads. These
43
- * already carry the authoritative result and are applied wholesale.
44
- * 2. Legacy delta fan-out (`broadcastDelta`) pushes a structured `MutationDelta`
45
- * as a `delta` frame to subscribers matched by table + args. The delta describes
46
- * a single row change (`insert` / `update` / `delete`) keyed by row id, so the
47
- * client can splice it into the cached list result without a full re-send.
48
- *
49
- * Historically the client treated the `delta` field as an opaque blob and
50
- * replaced the whole cached value with it on every message — which only made
51
- * sense for the rare delta payloads that already carried the full result. This
52
- * module lets the client recognise a structured delta and merge it into the
53
- * existing array (preserving order, no dup/loss), falling back to full
54
- * replacement when the payload isn't a recognisable row delta or can't be
55
- * applied cleanly against the current cached shape.
56
- */
57
- /**
58
- * One row change as emitted by `@lunora/do`'s `broadcastDelta`. Mirrors
59
- * `MutationDelta` in `@lunora/do` structurally so the client carries no
60
- * dependency on it. `row` is absent on `delete` events (and may be absent on
61
- * older servers for any op).
62
- */
287
+ * Reactive sinks an adapter binds to its own primitive's setters (a React
288
+ * `useState`, a Solid signal, a Vue ref, a Svelte store). The runner pushes into
289
+ * them; how they store the value is the adapter's concern (e.g. Solid and React
290
+ * wrap function-valued results in a thunk so the setter stores them rather than
291
+ * invoking them).
292
+ */
293
+ interface CallRunnerSinks<R> {
294
+ /** Receives the normalized {@link Error} when the latest invocation rejects. */
295
+ setError: (error: Error) => void;
296
+ /** Receives `true` while at least one invocation is in flight (ref-counted across overlapping calls), else `false`. */
297
+ setPending: (pending: boolean) => void;
298
+ /** Receives the resolved value when the latest invocation succeeds. */
299
+ setResult: (result: R) => void;
300
+ }
301
+ /**
302
+ * Build the framework-neutral half of an adapter's write primitive — the `mutate`
303
+ * of `useMutation`/`createMutation`/`mutation`, and the `call` of
304
+ * `useAction`/`createAction`/`action`.
305
+ *
306
+ * It owns the orchestration every adapter otherwise copy-pastes: ref-counting
307
+ * overlapping invocations into `setPending` (so the flag clears only once the
308
+ * last settles), normalizing a thrown non-`Error`, and routing success/failure to
309
+ * `setResult`/`setError` before re-throwing the SAME instance (so a typed error's
310
+ * `.code`/`.data` survive for both the `catch` and the template).
311
+ *
312
+ * `invoke` is a pre-bound thunk — `(args, options) => client.mutation(fn, args, options)`
313
+ * or `(args, options) => client.action(fn, args, options)`. Binding at the call
314
+ * site is what keeps this one function: the runner never inspects `options`, it
315
+ * only forwards them, so the option type is inferred from the closure rather
316
+ * than hard-coded per procedure kind. What actually keeps `optimisticUpdate` off
317
+ * an action is the adapter's exported handle type, not this file.
318
+ *
319
+ * `data`/`error` track the LATEST invocation, not the last to settle: overlapping
320
+ * calls can resolve out of order, so an earlier call that finishes later must not
321
+ * clobber a newer call's outcome. Each invocation takes a monotonic token and
322
+ * writes the value sinks only while it is still the most recent one — otherwise a
323
+ * double-click could leave the UI showing the first click's result, or an error
324
+ * for a call that succeeded.
325
+ */
326
+ declare const createCallRunner: <A, O, R>(invoke: (args: A, options?: O) => Promise<R>, sinks: CallRunnerSinks<R>) => ((args: A, options?: O) => Promise<R>);
327
+ interface TabCoordinatorOptions {
328
+ /**
329
+ * BroadcastChannel name. Defaults to `"lunora-bridge"`.
330
+ */
331
+ channelName?: string;
332
+ /**
333
+ * Interval (ms) between leader heartbeats. Defaults to 1000.
334
+ */
335
+ heartbeatInterval?: number;
336
+ /**
337
+ * Milliseconds without a heartbeat to consider the leader dead. Must be
338
+ * larger than `heartbeatInterval`. Defaults to 3000.
339
+ */
340
+ leaderTimeout?: number;
341
+ /**
342
+ * Called when this tab becomes the leader (should open WS connections).
343
+ */
344
+ onBecomeLeader?: () => void;
345
+ /**
346
+ * Called when the leader broadcasts its aggregate `ConnectionStatus`
347
+ * (see `LunoraClient.emitConnectionStatus`) — a follower owns no socket
348
+ * of its own, so this is its only truthful signal for a status indicator
349
+ * or the offline-queue gate. Sent on every leader-side status change and
350
+ * once more right after a new leader takes over, so a follower already
351
+ * mid-mirroring isn't stuck on a stale value from the PREVIOUS leader.
352
+ *
353
+ * `identity` is the leader's own `identityFingerprint()` (`null` = signed
354
+ * out) — the channel-name scoping (see `LunoraClient.createTabCoordinator`)
355
+ * is the primary defence against a stale frame from a since-changed
356
+ * identity, but `setAuthToken` in one tab can move it to a new channel
357
+ * while this frame is already queued in another tab's message task queue.
358
+ * A follower drops the frame when `identity` is present and doesn't match
359
+ * its own; an **absent** `identity` (mixed-version leader) is accepted —
360
+ * today's behavior, and the channel split already separates version groups.
361
+ */
362
+ onConnectionStatus?: (status: ConnectionStatus, identity?: string | null) => void;
363
+ /**
364
+ * Called when the leader broadcasts a subscription error.
365
+ */
366
+ /** Fired on the LEADER when it answers another tab's leadership claim — the moment a new follower is known to be listening. */
367
+ onLeaderClaimAnswered?: () => void;
368
+ /**
369
+ * Called when this tab loses leadership (should close WS connections).
370
+ */
371
+ onStopBeingLeader?: () => void;
372
+ /**
373
+ * Called when the leader broadcasts subscription data. `cursor`/`epoch`
374
+ * ride along when the leader is CLIENT-01-aware, so the follower can drop
375
+ * its own confirmed optimistic layers instead of just displaying the raw
376
+ * value; both are absent on a mixed-version leader that hasn't shipped the
377
+ * cursor yet (the follower falls back to its historical behavior — see
378
+ * the follower data handler in `tab-leadership.ts`).
379
+ *
380
+ * `identity` is the leader's `identityFingerprint()` (see
381
+ * `onConnectionStatus`'s docblock for the full rationale and the
382
+ * absent-field mixed-version rule — identical here).
383
+ */
384
+ onSubscriptionData?: (key: string, data: unknown, cursor?: number, epoch?: string, identity?: string | null, claims?: string) => void;
385
+ onSubscriptionError?: (key: string, error: SubscriptionError, identity?: string | null, claims?: string) => void;
386
+ /**
387
+ * Called when the leader broadcasts a `settled` frame's checkpoint advance
388
+ * (no value change, but the resume cursor moved). A follower needs this
389
+ * too — otherwise a `setQuery`/per-call optimistic overlay that a
390
+ * byte-identical write just confirmed stays masked on follower tabs until
391
+ * the next VISIBLE data frame arrives, even though the leader already
392
+ * dropped it.
393
+ *
394
+ * `lastMutationId` is the LEADER's own per-client `__client_watermark` —
395
+ * scoped server-side to the socket's announced `clientId` — so it only
396
+ * means anything to a follower whose `clientId` matches the leader's
397
+ * (`clientId` rides along for exactly that comparison; see
398
+ * `LunoraClient`'s wiring). An **absent** `clientId` (a mixed-version
399
+ * leader that hasn't shipped this field yet) also skips the
400
+ * `mutationId` half — safe, because the follower's own gates still
401
+ * resolve via its own RPC-ack watermark path and the `CheckpointRegistry`
402
+ * bounded fallback. The checkpoint (cursor) half of this callback fires
403
+ * unconditionally regardless of `clientId` — only the `mutationId` half
404
+ * is scoped.
405
+ *
406
+ * `identity` is the leader's `identityFingerprint()` — see
407
+ * `onConnectionStatus`'s docblock for the drop rule (identical here).
408
+ */
409
+ onSubscriptionSettled?: (key: string, cursor?: number, epoch?: string, lastMutationId?: number, clientId?: string, identity?: string | null, claims?: string) => void;
410
+ }
411
+ declare class TabCoordinator {
412
+ private readonly bc;
413
+ private readonly tabId;
414
+ private readonly heartbeatInterval;
415
+ private readonly leaderTimeout;
416
+ /** The tab id of the current known leader, or `undefined` if no leader. */
417
+ private knownLeader;
418
+ /** `true` when this tab believes it is the leader. */
419
+ private leader;
420
+ /** `true` once `start()` has been called. */
421
+ private running;
422
+ /**
423
+ * `true` while a `claimAndPromote()` claim window is open. Guards the yield
424
+ * handler and `checkLeaderHealth`'s belt-and-braces else-branch so the two
425
+ * promotion paths can't both arm a `becomeLeader` timeout for the same gap.
426
+ */
427
+ private promotionPending;
428
+ /** Timestamp of the most recent leader heartbeat. */
429
+ private lastHeartbeat;
430
+ /**
431
+ * Snapshots waiting for the end of the current tick, latest per key. A
432
+ * `subscription-data` frame is a full snapshot, so a burst for one key within
433
+ * a tick only needs its last frame posted — each post structured-clones the
434
+ * whole value for every tab on the channel.
435
+ */
436
+ private readonly pendingData;
437
+ /** Snapshots received under `more`, per leader tab, applied with the frame that closes their flush. */
438
+ private readonly heldData;
439
+ private heartbeatTimer;
440
+ private leaderCheckTimer;
441
+ /** Callbacks set via constructor options. */
442
+ private readonly onBecomeLeader;
443
+ private readonly onStopBeingLeader;
444
+ private readonly onConnectionStatus;
445
+ private readonly onSubscriptionData;
446
+ private readonly onLeaderClaimAnswered;
447
+ private readonly onSubscriptionError;
448
+ private readonly onSubscriptionSettled;
449
+ constructor(options?: TabCoordinatorOptions);
450
+ /**
451
+ * Start the coordinator: attempt to claim leadership and begin the
452
+ * heartbeat/leader-check cycle. Safe to call multiple times.
453
+ */
454
+ start(): void;
455
+ /**
456
+ * Stop the coordinator: yield leadership (if held), close the channel, and
457
+ * clear all timers. Safe to call multiple times.
458
+ */
459
+ stop(): void;
460
+ /** `true` when this tab is the current WebSocket leader. */
461
+ isLeader(): boolean;
462
+ /**
463
+ * Force this (freshly `start()`-ed) tab to become leader immediately,
464
+ * skipping the normal claim-then-`leaderTimeout` dance. Safe to call
465
+ * right after `start()` when the caller already knows this tab was the
466
+ * SOLE leader of the group it's replacing (e.g. `LunoraClient`'s
467
+ * identity-change coordinator restart — waiting out the full
468
+ * `leaderTimeout` there would freeze every live query for no reason,
469
+ * since this tab is overwhelmingly likely to be alone on the freshly
470
+ * derived channel). A sibling tab going through the normal `start()`
471
+ * dance for the SAME transition observes this tab's `becomeLeader`
472
+ * heartbeat and defers before its own claim-timeout fires; if another
473
+ * tab ALSO force-promotes at the same moment (e.g. two tabs both
474
+ * transitioning to the same new identity), the existing
475
+ * `resolveLeaderVsLeaderTieBreak` resolves the rare double-promotion
476
+ * the same way it resolves any other split-brain.
477
+ */
478
+ promoteImmediately(): void;
479
+ /** The tab id of the current leader, or `undefined` if unknown / no leader. */
480
+ get leaderTabId(): string | undefined;
481
+ /** The id of this tab. */
482
+ get id(): string;
483
+ /** `true` when the coordinator has been started and is not yet stopped. */
484
+ get isRunning(): boolean;
485
+ /**
486
+ * Broadcast subscription data to all follower tabs. Only the leader should
487
+ * call this. `cursor`/`epoch` are omitted from the wire frame when
488
+ * `undefined` (e.g. a CDC-off shard) — a follower on ANY version treats a
489
+ * missing `cursor` as "no confirmed-layer drop this frame", so omitting it
490
+ * here is equivalent to sending it as `undefined`. `identity` is this
491
+ * (leader) tab's own `identityFingerprint()` (`null` = signed out) —
492
+ * stamped so a follower can drop a frame from a since-changed identity
493
+ * (see the `onSubscriptionData` docblock); spread-included whenever
494
+ * supplied, since a fixed leader always knows its own identity (never
495
+ * omits it) and `null` must round-trip distinctly from "field absent".
496
+ */
497
+ broadcastSubscriptionData(key: string, data: unknown, cursor?: number, epoch?: string, identity?: string | null, claims?: string): void;
498
+ /**
499
+ * Broadcast a subscription error to all follower tabs. Only the leader
500
+ * should call this.
501
+ *
502
+ * `identity` is this tab's own `identityFingerprint()`, stamped so a
503
+ * follower can drop a frame minted under a different credential — the same
504
+ * guard `broadcastSubscriptionData` and `broadcastSubscriptionSettled`
505
+ * carry. This one lacked it, which was harmless only because nothing called
506
+ * it; once the leader started fanning errors, an unstamped frame could
507
+ * deliver one caller's rejection to a tab that had since signed in as
508
+ * someone else.
509
+ */
510
+ broadcastSubscriptionError(key: string, error: SubscriptionError, identity?: string | null, claims?: string): void;
511
+ /**
512
+ * Broadcast a `settled` frame's checkpoint advance to all follower tabs
513
+ * (no value change, but the resume cursor/epoch moved — see
514
+ * `LunoraClient.handleSettledMessage`). `clientId` is this (leader) tab's
515
+ * own client id, stamped so a follower can tell whether the echoed
516
+ * `lastMutationId` watermark is genuinely its own (see the
517
+ * `onSubscriptionSettled` docblock). `identity` is this tab's own
518
+ * `identityFingerprint()` — see `broadcastSubscriptionData`'s docblock for
519
+ * the same round-tripping rule. Only the leader should call this.
520
+ */
521
+ broadcastSubscriptionSettled(key: string, cursor?: number, epoch?: string, lastMutationId?: number, clientId?: string, identity?: string | null, claims?: string): void;
522
+ /**
523
+ * Broadcast this tab's aggregate `ConnectionStatus` to follower tabs, so
524
+ * they can mirror a truthful status without a socket of their own (see
525
+ * `LunoraClient.computeStatus`/`emitConnectionStatus`). `identity` is this
526
+ * tab's own `identityFingerprint()` — see `broadcastSubscriptionData`'s
527
+ * docblock for the same round-tripping rule. Only the leader should call
528
+ * this.
529
+ */
530
+ broadcastConnectionStatus(status: ConnectionStatus, identity?: string | null): void;
531
+ private broadcast;
532
+ /** Post the snapshots queued this tick — unless leadership was lost meanwhile, when the new leader's own snapshots supersede them. */
533
+ private flushPendingData;
534
+ /** Hold a snapshot marked `more`; on the one that closes its flush, apply them all and notify once. */
535
+ private applySubscriptionData;
536
+ private handleMessage;
537
+ private handleClaimLeadership;
538
+ private handleHeartbeat;
539
+ /**
540
+ * Resolve two leaders existing at once — e.g. this tab was backgrounded
541
+ * and its heartbeat/health timers were throttled while a foreground
542
+ * follower's were not, so the follower's `checkLeaderHealth` timed out
543
+ * the (still-alive) leader and self-promoted. `BroadcastChannel` message
544
+ * delivery isn't subject to the same timer-throttling clamp, so even a
545
+ * backgrounded leader eventually observes the pretender's heartbeat here
546
+ * — resolve the split-brain deterministically with the same
547
+ * lexicographically-smaller-tabId rule used at claim-adoption. If the
548
+ * other tab wins, step down; if we win, reassert immediately so the
549
+ * pretender demotes itself the moment it processes our heartbeat.
550
+ */
551
+ private resolveLeaderVsLeaderTieBreak;
552
+ private becomeLeader;
553
+ private sendHeartbeat;
554
+ private checkLeaderHealth;
555
+ /**
556
+ * Broadcast a leadership claim and arm a `becomeLeader` fallback: if no
557
+ * other tab has asserted itself as leader by the time the window elapses,
558
+ * self-promote. Shared by `checkLeaderHealth`'s stale-leader path and the
559
+ * `yield-leadership` handler so both promotion triggers use one claim
560
+ * window instead of each arming its own timeout.
561
+ */
562
+ private claimAndPromote;
563
+ }
564
+ /**
565
+ * One row change as emitted by `@lunora/do`'s `broadcastDelta`. Mirrors
566
+ * `MutationDelta` in `@lunora/do` structurally so the client carries no
567
+ * dependency on it. `row` is absent on `delete` events (and may be absent on
568
+ * older servers for any op).
569
+ */
63
570
  interface MutationDelta {
64
571
  /** Row id (`_id`) the change applies to. */
65
572
  key: string;
66
573
  op: "delete" | "insert" | "update";
67
574
  row?: Record<string, unknown>;
575
+ /**
576
+ * On a re-execution delta, the query's only read table, or `"__lunora__"` when it
577
+ * read several, none, or depends on every table. On a `broadcastDelta` frame, the
578
+ * string the server stamped (the subscription's registered `table`). The merge
579
+ * never uses it (protocol README §5.1.1).
580
+ */
68
581
  table: string;
69
582
  }
70
583
  /**
71
- * Structural guard: is `value` a `MutationDelta` the client knows how to merge?
72
- * We require `op`, `table`, and a string `key` so opaque payloads that merely
73
- * happen to be objects (e.g. an aggregate `{ count: 1 }` a query returns
74
- * verbatim) are never mistaken for a row delta and keep replacing the cached
75
- * value wholesale.
76
- */
584
+ * Structural guard: is `value` a `MutationDelta` the client knows how to merge?
585
+ * We require `op`, `table`, and a string `key` so opaque payloads that merely
586
+ * happen to be objects (e.g. an aggregate `{ count: 1 }` a query returns
587
+ * verbatim) are never mistaken for a row delta and keep replacing the cached
588
+ * value wholesale.
589
+ */
77
590
  declare const isMutationDelta: (value: unknown) => value is MutationDelta;
78
591
  /**
79
- * Apply a structured `MutationDelta` to a cached array result, returning a new
80
- * array (never mutating the input). Returns `undefined` when the delta can't be
81
- * applied cleanly — the caller should then fall back to the existing
82
- * full-replacement behaviour (or trust the next snapshot to reconcile).
83
- *
84
- * Mergeable shape: a plain array of id-bearing row objects, e.g. the result of
85
- * `db.query().collect()`.
86
- *
87
- * Insert / update / delete are matched by row `_id`:
88
- * - `insert`: appended (or placed by `_creationTime` order) if absent; treated
89
- * as an update if a row with the same id already exists (idempotent — guards
90
- * against a delta replayed after a snapshot already included it).
91
- * - `update`: replaces the matching row in place, preserving its position.
92
- * - `delete`: removes the matching row.
93
- *
94
- * Returns `undefined` when `current` isn't an array of id-keyable objects, or
95
- * when an `insert`/`update` delta carries no `row` to splice in.
96
- */
97
- declare const applyDelta: (current: unknown, delta: MutationDelta) => undefined | unknown[];
98
- /** Error code the server uses for optimistic-concurrency conflicts (HTTP 409). */
99
- declare const CONFLICT_ERROR_CODE = "CONFLICT";
592
+ * Apply a structured `MutationDelta` to a cached list result, returning a new
593
+ * value (never mutating the input). Returns `undefined` when the delta can't be
594
+ * applied cleanly — the caller should then fall back to the existing
595
+ * full-replacement behaviour (or trust the next snapshot to reconcile).
596
+ *
597
+ * Mergeable shapes: an array of id-bearing row objects, or a `.paginate()`
598
+ * result wrapping one in `page` (see `rowListOf`). A paginated value keeps its
599
+ * other fields and comes back as a new object with a new `page` — the server
600
+ * only sends row deltas for that shape when everything outside the page is
601
+ * unchanged, so the merged value matches the snapshot it chose not to send.
602
+ * @returns the merged value, or `undefined` when the delta cannot be applied
603
+ */
604
+ declare const applyDelta: (current: unknown, delta: MutationDelta) => Record<string, unknown> | undefined | unknown[];
100
605
  /**
101
- * Whether an unknown rejection is an optimistic-concurrency conflict — the
102
- * server lost a write race and the caller should refetch and retry (or surface
103
- * the conflict). Structural check on the `code` property the client attaches
104
- * when decoding the worker's `{ error: { code, message } }` envelope.
105
- */
106
- declare const isConflictError: (error: unknown) => error is Error & {
107
- code: "CONFLICT";
108
- };
109
- /** The single transport method a mutation runner needs — narrowed so adapters can test against a stub. */
110
- interface MutationCapableClient<F extends FunctionReference> {
111
- mutation: (function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>) => Promise<ReturnOf<F>>;
606
+ * Options accepted by {@link httpStream}.
607
+ */
608
+ interface HttpStreamOptions {
609
+ /**
610
+ * Origin (or origin + prefix) the route path is appended to, e.g.
611
+ * `https://my-app.example.com`. Defaults to `""` — a relative URL, which
612
+ * resolves against the page origin in a browser.
613
+ */
614
+ baseUrl?: string;
615
+ /** `fetch` implementation override; defaults to the global `fetch`. */
616
+ fetch?: typeof fetch;
617
+ /** Extra request headers (e.g. `authorization`). `accept: text/event-stream` is always sent. */
618
+ headers?: Record<string, string>;
619
+ /**
620
+ * Treat a connection that delivers nothing — no chunk, no keepalive comment —
621
+ * for this many milliseconds as dead: it is cancelled, then reconnected with
622
+ * {@link HttpStreamOptions.reconnect} or failed with `STREAM_IDLE`. Off by
623
+ * default, because a route may be silent for as long as its handler works
624
+ * (a model thinking); set it to a few multiples of the route's keepalive
625
+ * interval when the route sends one.
626
+ *
627
+ * Measured per streamed read, so it needs a `fetch` that exposes
628
+ * `response.body`. A runtime whose `fetch` delivers no body stream (React
629
+ * Native) reads the whole payload with one `text()` call that resolves only
630
+ * at the end — no per-frame progress exists to measure silence against, so
631
+ * this bound does not apply there and a stalled read waits for
632
+ * `.cancel()` or {@link HttpStreamOptions.signal} instead.
633
+ */
634
+ idleTimeoutMs?: number;
635
+ /**
636
+ * Seed the first request's `Last-Event-ID` header, resuming a stream from a
637
+ * position a previous consumer persisted. Once frames arrive this is
638
+ * superseded by their `id:`, and a reconnecting stream always sends the
639
+ * latest id it saw.
640
+ */
641
+ lastEventId?: string;
642
+ /** Caps the in-flight chunk buffer (see `createStream`); exceeding it fails the stream. */
643
+ maxBuffer?: number;
644
+ /** Called with each frame's `id:` as it is seen (the value that will be replayed on reconnect). */
645
+ onEventId?: (id: string) => void;
646
+ /** Called when the server advertises a `retry:` reconnect delay, in milliseconds. */
647
+ onRetry?: (ms: number) => void;
648
+ /**
649
+ * Reopen the request after a transport interruption — a bare EOF or a
650
+ * read/transport error — replaying the last seen id as `Last-Event-ID`.
651
+ * Defaults to `false`, which surfaces the interruption as
652
+ * `HTTP_STREAM_INTERRUPTED` exactly as before. A terminal `complete`/`error`
653
+ * frame, a non-2xx status, and a consumer cancel never reconnect.
654
+ */
655
+ reconnect?: boolean;
656
+ /** External abort signal — aborting it cancels the fetch (→ the server handler's `signal`). */
657
+ signal?: AbortSignal;
112
658
  }
113
659
  /**
114
- * Reactive sinks an adapter binds to its own primitive's setters (a Solid
115
- * signal, a Vue ref, a Svelte store). The runner pushes into them; how they
116
- * store the value is the adapter's concern (e.g. Solid wraps function-valued
117
- * results in a thunk).
118
- */
119
- interface MutationRunnerSinks<R> {
120
- /** Receives the normalized {@link Error} when an invocation rejects. */
121
- setError: (error: Error) => void;
660
+ * Open a typed HTTP-SSE stream route and iterate its chunks:
661
+ *
662
+ * ```ts
663
+ * const stream = httpStream(httpStreams.http.tokens, { searchParams: { prompt } }, { baseUrl });
664
+ * for await (const token of stream) {
665
+ * render(token); // typed as the route handler's yielded chunk
666
+ * }
667
+ * ```
668
+ *
669
+ * The returned iterable terminates when the server writes `event: complete`;
670
+ * an `event: error` frame (or a transport failure) surfaces as a coded
671
+ * rejection on the next `next()`. `.cancel()` — or aborting `options.signal` —
672
+ * aborts the underlying fetch, which the server observes via `request.signal`.
673
+ */
674
+ declare const httpStream: <Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: HttpStreamOptions) => StreamIterable<HttpStreamChunkOf<Ref>>;
675
+ /** Options for {@link connectLiveStream}. */
676
+ interface ConnectLiveStreamOptions {
677
+ /** `fetch` override (a test seam, or a custom transport). */
678
+ fetch?: typeof fetch;
679
+ /** Extra headers sent on both the stream and the control requests. */
680
+ headers?: Record<string, string>;
681
+ /**
682
+ * Treat a connection that delivers nothing — not even a keepalive — for this many milliseconds as
683
+ * dead, and reconnect. Every target that serves live streams (Cloudflare Workers, the Node host
684
+ * and celld) runs the same `ShardDO` live handlers, and they write a `:ka` comment every 25s
685
+ * while a stream is open, so the default is `75000`. Set `0` to disable the bound when a proxy
686
+ * or a server of your own in front of the shard does not forward comment frames.
687
+ */
688
+ idleTimeoutMs?: number;
689
+ /** Ceiling for the reconnect backoff, in ms. Defaults to `30000`. */
690
+ maxDelayMs?: number;
691
+ /** Base reconnect delay in ms. Defaults to `1000`. */
692
+ retryDelay?: number;
693
+ /** Send cookies / credentials on the stream and control requests. */
694
+ withCredentials?: boolean;
695
+ }
696
+ /** A delivered live event. */
697
+ interface LiveStreamEvent {
698
+ /** The decoded payload the publisher sent. */
699
+ payload: unknown;
700
+ /** The topic the event was published on. */
701
+ topic: string;
702
+ }
703
+ /** Options for {@link LiveStream.subscribe}. */
704
+ /** A subscribe the shard refused for good: a reconnect would only be refused again. */
705
+ interface LiveStreamSubscribeError {
706
+ /** The HTTP status of the refusal, e.g. 403, 409 or 429. */
707
+ status: number;
708
+ subscriptionId: string;
709
+ topic: string;
710
+ }
711
+ interface LiveStreamSubscribeOptions {
712
+ /** Stable caller id; a generated one is used when omitted. */
713
+ id?: string;
714
+ /**
715
+ * Called when the shard refuses this subscription (403, 409, 429 and similar). The subscription is dropped
716
+ * first, so a later subscribe with the same id is accepted. A 401 is not reported: the stream reconnects,
717
+ * which re-authenticates and registers the subscription again.
718
+ */
719
+ onError?: (error: LiveStreamSubscribeError) => void;
720
+ /** Called for every event on `topic`. */
721
+ onEvent?: (payload: unknown) => void;
722
+ /** The topic to follow. */
723
+ topic: string;
724
+ }
725
+ /** A live stream connection. */
726
+ interface LiveStream {
727
+ /** Close the stream and stop reconnecting. */
728
+ close: () => void;
729
+ /** The server-minted connection id, or `undefined` before the first connect and while reconnecting. */
730
+ readonly connectionId: string | undefined;
731
+ /** Observe every event on the connection; returns an unsubscribe handle. */
732
+ onEvent: (handler: (event: LiveStreamEvent) => void) => () => void;
733
+ /** Resolves once the first connection is established (rejects only if `close`d first). */
734
+ readonly ready: Promise<void>;
735
+ /** Follow a topic; returns an unsubscribe handle. */
736
+ subscribe: (options: LiveStreamSubscribeOptions) => () => void;
737
+ }
738
+ /**
739
+ * Connect to a live topic stream. See the module docblock.
740
+ * @param url the `connect` route URL (its sibling `control` route is derived)
741
+ */
742
+ declare const connectLiveStream: (url: string, options?: ConnectLiveStreamOptions) => LiveStream;
743
+ /**
744
+ * A reference to one declared live topic, as `_generated/live.ts` hands it out. Plain data
745
+ * (no server code), so a client bundle can hold it; the phantom `Payload` is what lets
746
+ * `ctx.live.publish` and the framework hooks type the event.
747
+ */
748
+ interface LiveTopicRef<Payload = unknown> {
749
+ /** Phantom: carries the declared payload type. Never present at runtime. */
750
+ readonly __payload?: Payload;
751
+ /** The `id` of the `defineLiveStream` that declares and authorizes this topic. */
752
+ readonly __lunoraLive: string;
753
+ /** The encoded wire topic (see {@link encodeLiveTopic}). */
754
+ readonly topic: string;
755
+ }
756
+ /** Options for {@link subscribeLiveTopic}. */
757
+ interface SubscribeLiveTopicOptions extends Omit<ConnectLiveStreamOptions, "fetch"> {
758
+ /** Called when the shard refuses this subscription (403, 409, 429 and similar). */
759
+ onError?: (error: LiveStreamSubscribeError) => void;
760
+ /** Called for every event on `topic`. */
761
+ onEvent?: (payload: unknown) => void;
762
+ /**
763
+ * Partitions the shared connection. A cookie-authenticated stream is bound to the session that opened it, so
764
+ * pass something that changes when the signed-in user does (a user id): a new value opens a new connection
765
+ * and the old one closes once its subscribers have moved. It is never sent to the server.
766
+ */
767
+ sessionKey?: string;
768
+ /** The topic to follow. */
769
+ topic: string;
770
+ /** The `connect` route URL of a `defineLiveStream`. */
771
+ url: string;
772
+ }
773
+ /**
774
+ * Follow `topic` on the shared connection for `url`.
775
+ * @returns an unsubscribe handle; the last one out closes the connection
776
+ */
777
+ declare const subscribeLiveTopic: (options: SubscribeLiveTopicOptions) => (() => void);
778
+ /**
779
+ * What a framework hook takes besides the topic reference: the transport tuning of
780
+ * {@link SubscribeLiveTopicOptions}, with `onEvent` typed by the topic's declared payload.
781
+ */
782
+ interface LiveTopicOptions<Payload = unknown> extends Omit<SubscribeLiveTopicOptions, "onEvent" | "topic" | "url"> {
783
+ /** Called for every event on the topic. The payload is the type the topic declares. */
784
+ onEvent?: (payload: Payload) => void;
785
+ /**
786
+ * Follow the topic on this shard: the connect URL gets `?shard=<key>`, and the control calls carry it too. Omit it
787
+ * for the default shard. Publish to the same shard with `{ shardKey }`, since delivery never crosses shards.
788
+ */
789
+ shardKey?: string;
790
+ }
791
+ /**
792
+ * Resolve a topic reference to the string-based options {@link subscribeLiveTopic} takes: the connect URL is the
793
+ * stream's route under the client's base URL, and the topic is the reference's encoded wire topic. Every framework
794
+ * hook goes through this, so they all build the same connection (and so share it).
795
+ */
796
+ declare const liveTopicSubscription: <Payload>(client: {
797
+ readonly url: string;
798
+ }, ref: LiveTopicRef<Payload>, options?: LiveTopicOptions<Payload>) => SubscribeLiveTopicOptions;
799
+ /**
800
+ * The structural surface of a TanStack `Transaction` a bound custom mutator
801
+ * returns — its `isPersisted.promise` resolves once the write is persisted and
802
+ * rejects on failure. Typed structurally so the framework adapters need not
803
+ * depend on `@tanstack/db` or `@lunora/db` (the handle is created app-side by
804
+ * `bindMutators`).
805
+ */
806
+ interface MutatorTransaction {
807
+ isPersisted: {
808
+ promise: Promise<unknown>;
809
+ };
810
+ }
811
+ /**
812
+ * A bound custom-mutator handle produced by `bindMutators(client, ctx, mutators)`
813
+ * in `@lunora/db`. Calling it applies the optimistic overlay to the local
814
+ * collections and pushes the authoritative server write; it returns the TanStack
815
+ * transaction whose `isPersisted` promise tracks completion.
816
+ */
817
+ type MutatorHandle<TArgs> = (args: TArgs) => MutatorTransaction;
818
+ /**
819
+ * Reactive sinks an adapter binds to its own primitive's setters (a React
820
+ * `useState`, a Solid signal, a Vue ref, a Svelte store). The runner pushes into
821
+ * them; how they store the value is the adapter's concern.
822
+ */
823
+ interface MutatorRunnerSinks {
824
+ /** Receives the normalized {@link Error} when an invocation rejects, or `undefined` on success / reset. */
825
+ setError: (error: Error | undefined) => void;
122
826
  /** Receives `true` while at least one invocation is in flight (ref-counted across overlapping calls), else `false`. */
123
827
  setPending: (pending: boolean) => void;
124
- /** Receives the resolved value when an invocation succeeds. */
125
- setResult: (result: R) => void;
126
828
  }
127
829
  /**
128
- * Build the framework-neutral `mutate` half of an adapter's mutation hook.
129
- *
130
- * Owns the orchestration every adapter otherwise copy-pastes: ref-counts
131
- * overlapping invocations into `setPending` (so it only clears once the last
132
- * settles), normalizes a thrown non-`Error`, and routes success/failure to
133
- * `setResult`/`setError` before re-throwing. Each adapter (`@lunora/react`,
134
- * `/solid`, `/svelte`, `/vue`) binds the three sinks to its own reactive
135
- * setters, so this logic lives in exactly one place. Optimistic-update options
136
- * pass straight through to `client.mutation`.
137
- */
138
- declare const createMutationRunner: <F extends FunctionReference>(client: MutationCapableClient<F>, function_: F, sinks: MutationRunnerSinks<ReturnOf<F>>) => ((args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>) => Promise<ReturnOf<F>>);
830
+ * Build the framework-neutral `mutate` / `reset` pair of an adapter's
831
+ * custom-mutator hook (`useMutator` / `createMutator` / `mutator`).
832
+ *
833
+ * Owns the orchestration every adapter otherwise copy-pastes: ref-counts
834
+ * overlapping invocations into `setPending` (so it only clears once the last
835
+ * settles), awaits the bound handle's `isPersisted` promise, normalizes a thrown
836
+ * non-`Error`, and routes failure to `setError` (clearing it on success) before
837
+ * re-throwing. Each adapter (`@lunora/react`, `/solid`, `/svelte`, `/vue`) binds
838
+ * the two sinks to its own reactive setters, so this logic lives in exactly one
839
+ * place. The optimistic overlay + server push are owned by the bound handle.
840
+ *
841
+ * `error` tracks the LATEST invocation, not the last to settle: overlapping
842
+ * calls can resolve out of order, so an earlier call that finishes later must
843
+ * not clobber a newer call's outcome. Each invocation takes a monotonic token
844
+ * and only writes `setError` while it is still the most recent one — otherwise
845
+ * `error`/`isError` could surface a stale success or failure (the documented
846
+ * "latest invocation's error" contract every adapter advertises).
847
+ */
848
+ declare const createMutatorRunner: <TArgs>(handle: MutatorHandle<TArgs>, sinks: MutatorRunnerSinks) => {
849
+ mutate: (args: TArgs) => Promise<void>;
850
+ reset: () => void;
851
+ };
139
852
  interface QueuedMutation<T = unknown> {
853
+ /**
854
+ * Set on a write that was queued because its direct send failed in a way that
855
+ * says nothing about its fate (see `LunoraClient.mutation`). Its caller is still
856
+ * waiting and was never told it failed, so the replay counts its transient
857
+ * failures and rejects it after a few, rather than retrying for ever.
858
+ */
859
+ readonly ambiguousSend?: boolean;
140
860
  readonly args: Record<string, unknown>;
861
+ /**
862
+ * CDC cursor this write was composed against (see
863
+ * {@link PersistedMutation.baselineSeq}). Persisted and restored so a replay is
864
+ * judged against what its author could see, not against what the client has
865
+ * since caught up to.
866
+ */
867
+ readonly baselineSeq?: number;
868
+ /**
869
+ * The client id that queued this write (see {@link PersistedMutation.clientId}).
870
+ * Persisted and restored, so a replay namespaces by the id that issued the
871
+ * write rather than whatever the current session minted.
872
+ */
873
+ clientId?: string;
141
874
  readonly functionPath: string;
142
875
  /** Stable id used to remove the entry from durable storage once replayed; assigned by the queue when absent. */
143
876
  id?: string;
144
877
  /**
145
- * Issuing identity fingerprint carried through to durable storage (`null` =
146
- * signed out). Absent on hydrated legacy records, which replay ambiently.
147
- */
148
- readonly identity?: string | null;
878
+ * Issuing identity fingerprint carried through to durable storage (`null` =
879
+ * signed out). Absent on hydrated legacy records, which replay ambiently.
880
+ *
881
+ * Mutable so {@link OfflineQueue.restampIdentity} can relabel a still-queued
882
+ * write when the identity's LABEL changes but the credential does not (the
883
+ * `setAuthToken(token, userId)` case where the subject resolves a tick after
884
+ * the token). The value is re-persisted alongside, so the new label survives
885
+ * a reload and a requeue.
886
+ */
887
+ identity?: string | null;
888
+ /**
889
+ * Position in the order this session ISSUED its writes, taken before the first send. A write whose
890
+ * direct send failed ambiguously is queued only once that send gives up, behind writes issued (and
891
+ * queued) while it was in flight; this puts it back ahead of them. Absent on hydrated records,
892
+ * which are older than anything issued this session.
893
+ */
894
+ readonly issueSeq?: number;
895
+ /**
896
+ * `true` when a live caller is still awaiting this write's `mutation()`
897
+ * Promise; `false`/absent for a write restored from durable storage after a
898
+ * reload (its original awaiter is gone). Carried so terminal-verdict
899
+ * observers can distinguish "the caller already saw this" from "nothing else
900
+ * will report this". Maps to the public `MutationSettledEvent.hadAwaiter`.
901
+ */
902
+ liveAwaiter?: boolean;
903
+ /**
904
+ * Invoked on a successful replay with the server's echoed commit CDC cursor,
905
+ * so a live per-call optimistic layer drops gaplessly once a frame reaches it.
906
+ * Absent on hydrated records (the optimistic write lived in a prior session).
907
+ */
908
+ readonly onCommit?: (commitCursor: number | undefined) => void;
909
+ /**
910
+ * Optional sync predicate evaluated just before replay. When it returns
911
+ * `false` the write is dropped instead of replaying, handling the case
912
+ * where the mutation's preconditions are no longer valid (e.g. the
913
+ * document it referred to was deleted while offline). Absent or `true`
914
+ * means "ok to replay".
915
+ */
916
+ readonly precondition?: () => boolean;
149
917
  /** Rejects if the mutation can no longer be replayed. */
150
918
  readonly reject: (error: unknown) => void;
151
919
  /** Resolves once the mutation has been replayed against the server. */
@@ -153,61 +921,214 @@ interface QueuedMutation<T = unknown> {
153
921
  readonly shardKey?: string;
154
922
  }
155
923
  /**
156
- * Bounded FIFO queue. Mutations issued while the client is offline are
157
- * enqueued and replayed in the order they were submitted once the WS
158
- * reconnects and identifies. If the queue exceeds `maxItems` the oldest
159
- * entry is rejected with `OFFLINE_QUEUE_OVERFLOW`.
160
- *
161
- * When a {@link PersistenceAdapter} is supplied, enqueued mutations are mirrored
162
- * to durable storage so they survive a reload — {@link OfflineQueue.hydrate} restores them on
163
- * the next startup and the client replays them on reconnect. Durable removal is
164
- * the caller's responsibility *after* a successful replay (see `LunoraClient`);
165
- * the queue only persists on enqueue and un-persists on overflow.
166
- */
924
+ * Invoked when the queue itself discards an entry on overflow (capacity
925
+ * eviction), so the client can surface the dropped write on its
926
+ * terminal-verdict observer even when the entry has no live awaiter (a hydrated
927
+ * record). The `error` carries the `OFFLINE_QUEUE_OVERFLOW` code.
928
+ *
929
+ * The `sdks/*` ports deliberately do NOT mirror this shape — they return the
930
+ * discarded entry from `enqueue`/`hydrate`/`drainConflict`/`clear` instead,
931
+ * because they call the queue with a real lock held and settling a write needs
932
+ * that same lock, which self-deadlocks a non-reentrant one. Keep the callback
933
+ * here: this client is single-threaded, so the hazard does not exist, and an
934
+ * observer the queue fires itself is what covers the case a return value's
935
+ * consumer can quietly miss — a hydrated entry whose `reject` is a no-op.
936
+ */
937
+ type EvictHandler = (entry: QueuedMutation, error: Error & {
938
+ code?: string;
939
+ }) => void;
940
+ /** Injected dependencies for {@link OfflineQueue} (kept off the user-facing {@link OfflineQueueOptions}). */
941
+ interface OfflineQueueDeps {
942
+ /** Invoked when an entry is discarded on capacity overflow (carries `OFFLINE_QUEUE_OVERFLOW`). */
943
+ onEvict?: EvictHandler;
944
+ /** Invoked when a write that was out for replay settles, which `onSizeChange` does not cover: the queue was already shorter. */
945
+ onReplayingChange?: () => void;
946
+ /** Invoked with the new depth after any size change (drives the client's pending-sync count). */
947
+ onSizeChange?: (size: number) => void;
948
+ /** Durable store; when present, writes are mirrored and restored across reloads. */
949
+ persistence?: PersistenceAdapter;
950
+ /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
951
+ version?: string;
952
+ }
953
+ /**
954
+ * Bounded FIFO queue. Mutations issued while the client is offline are
955
+ * enqueued and replayed in the order they were submitted once the WS
956
+ * reconnects and identifies. If the queue exceeds `maxItems` the oldest
957
+ * entry is rejected with `OFFLINE_QUEUE_OVERFLOW`.
958
+ *
959
+ * When a {@link PersistenceAdapter} is supplied, enqueued mutations are mirrored
960
+ * to durable storage so they survive a reload — {@link OfflineQueue.hydrate} restores them on
961
+ * the next startup and the client replays them on reconnect. Durable removal is
962
+ * the caller's responsibility *after* a successful replay (see `LunoraClient`);
963
+ * the queue only persists on enqueue and un-persists on overflow.
964
+ */
167
965
  declare class OfflineQueue {
168
966
  /** Opt-in to queueing mutations before the targeted shard's first connect. */
169
967
  readonly queueBeforeFirstConnect: boolean;
170
968
  private readonly maxItems;
171
969
  private readonly onPersistenceError;
172
970
  private readonly persistence;
971
+ private readonly onEvict;
972
+ private readonly onSizeChange;
973
+ private readonly onReplayingChange;
974
+ /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
975
+ private readonly version;
173
976
  private readonly items;
174
- constructor(options?: OfflineQueueOptions, persistence?: PersistenceAdapter);
977
+ /**
978
+ * Writes a flush has {@link OfflineQueue.drain}ed and neither requeued nor discarded yet, by id, which are on the wire or about
979
+ * to be. The objects are kept so a restamp can reach them: a replay that fails transiently requeues these same objects.
980
+ */
981
+ private readonly replayingIds;
982
+ /** Appends still in flight, by write id, each resolving to whether the record landed. Anything that touches a record durably waits on its append first. */
983
+ private readonly appending;
984
+ /**
985
+ * Writes enqueued this session and not yet settled (see {@link OfflineQueue.discard}). Unlike `items`
986
+ * this survives a replay temporarily draining the queue, so a failed append is tracked for as long as
987
+ * the write is unsettled, and a retry derives its record from the entry as it is NOW.
988
+ */
989
+ private readonly unsettled;
990
+ /** Ids whose append was rejected (a quota error, a closed connection), kept to be tried again — see {@link OfflineQueue.flushUnpersisted}. */
991
+ private readonly unpersisted;
992
+ constructor(options?: OfflineQueueOptions, deps?: OfflineQueueDeps);
175
993
  get size(): number;
994
+ /** Writes drained for replay and not yet settled or requeued: out of {@link OfflineQueue.size}, but still unsettled. */
995
+ get replaying(): number;
176
996
  enqueue<T>(entry: QueuedMutation<T>): void;
177
997
  /**
178
- * Restore mutations persisted in a prior session and re-queue them in FIFO
179
- * order. Restored entries already live in durable storage, so they are not
180
- * re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
181
- * gone after a reload). No-op when no persistence adapter is configured.
182
- * Returns the distinct shard keys of the restored writes so the caller can
183
- * open their sockets to trigger a flush.
184
- */
998
+ * Remove a settled write's durable record — after its append, if that is
999
+ * still in flight. A write that replays quickly can settle before its append
1000
+ * has landed; a `remove` that overtook it found nothing, and the record then
1001
+ * landed behind it and replayed in the next session.
1002
+ */
1003
+ discard(id: string): void;
1004
+ /**
1005
+ * Try again to persist every write whose append was rejected. Called when the
1006
+ * page is being hidden: the last chance to get a still-queued write into
1007
+ * durable storage before a reload or a discard of the tab loses it.
1008
+ *
1009
+ * A write whose append is still in flight is skipped: `visibilitychange` and `pagehide` fire
1010
+ * back to back, and a second append for the same id would hit a unique-id constraint (or store
1011
+ * the record twice) and leave the write wrongly tracked as unpersisted.
1012
+ */
1013
+ flushUnpersisted(): void;
1014
+ /**
1015
+ * Restore mutations persisted in a prior session and re-queue them in FIFO
1016
+ * order. Restored entries already live in durable storage, so they are not
1017
+ * re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
1018
+ * gone after a reload). No-op when no persistence adapter is configured.
1019
+ * Returns the distinct shard keys of the restored writes so the caller can
1020
+ * open their sockets to trigger a flush.
1021
+ *
1022
+ * `hydrate()` runs post-construction (the caller awaits an async durable-store
1023
+ * load), so a mutation issued while offline during that boot window is
1024
+ * enqueued into `items` *before* this method's `await` resolves. Restored
1025
+ * records are therefore `unshift`-ed ahead of whatever is already queued
1026
+ * rather than `push`-ed to the end: the durable store's persist order is
1027
+ * authoritative (a prior-session write is always older than anything from
1028
+ * this session), so replaying a same-session boot-time write before an
1029
+ * older restored write on the same document would let last-writer-wins
1030
+ * silently clobber the newer data with the stale one.
1031
+ */
185
1032
  hydrate(): Promise<(string | undefined)[]>;
186
1033
  /**
187
- * Remove and return queued mutations. With no `predicate`, drains the whole
188
- * queue. With one, drains only matching entries (preserving FIFO order) and
189
- * leaves the rest queued — used to flush a single shard's writes when its
190
- * socket reconnects while other shards are still down.
191
- */
1034
+ * Relabel every queued write stamped `from` to `to`, in memory AND in durable
1035
+ * storage.
1036
+ *
1037
+ * Used when the auth identity's LABEL changes while the credential does not —
1038
+ * `setAuthToken(token, userId)` where the user id resolves a tick after the
1039
+ * token was set. `setAuthToken` documents that this re-stamps in-flight
1040
+ * queued writes rather than dropping them, and that promise only held for the
1041
+ * caller's live in-memory stamp map, which is consumed and deleted on the
1042
+ * first flush attempt. Everything durable still carried the old token hash,
1043
+ * so a reload — or a transient-failure requeue after the token had since been
1044
+ * refreshed — fell back to it, failed the replay identity gate, and rejected
1045
+ * the SAME user's offline write with `OFFLINE_IDENTITY_CHANGED`.
1046
+ *
1047
+ * The durable rewrite goes through `PersistenceAdapter.replace`, the one
1048
+ * operation on the contract that is required to be atomic — see
1049
+ * {@link OfflineQueue.rewriteStamp}.
1050
+ */
1051
+ restampIdentity(from: string | null, to: string | null): void;
1052
+ /**
1053
+ * Whether any queued mutation matches — the cheap "is there a write ahead of
1054
+ * me on this shard?" question, answered without draining. A write held at
1055
+ * flush time (an identity not yet re-confirmed) sits here with no barrier
1056
+ * published for a later `mutation()` to wait on, so this is what keeps a
1057
+ * live write from overtaking it.
1058
+ */
1059
+ hasPending(predicate: (item: QueuedMutation) => boolean): boolean;
1060
+ /**
1061
+ * Remove and return queued mutations. With no `predicate`, drains the whole
1062
+ * queue. With one, drains only matching entries (preserving FIFO order) and
1063
+ * leaves the rest queued — used to flush a single shard's writes when its
1064
+ * socket reconnects while other shards are still down.
1065
+ */
192
1066
  drain(predicate?: (item: QueuedMutation) => boolean): QueuedMutation[];
193
1067
  /**
194
- * Return previously-drained mutations to the front of the queue, preserving
195
- * their FIFO order, without re-persisting them — they were never unpersisted,
196
- * so durable storage still holds them. Used when a flush aborts on a transient
197
- * transport failure: the unreplayed writes stay queued for the next reconnect.
198
- */
1068
+ * Return previously-drained mutations to the front of the queue, preserving
1069
+ * their FIFO order, without re-persisting them — they were never unpersisted,
1070
+ * so durable storage still holds them. Used when a flush aborts on a transient
1071
+ * transport failure: the unreplayed writes stay queued for the next reconnect.
1072
+ */
199
1073
  requeue(items: QueuedMutation[]): void;
1074
+ /**
1075
+ * Remove mutations whose precondition evaluates to `false` (stale/dirty
1076
+ * writes that should not replay) and reject each with an
1077
+ * `OFFLINE_PRECONDITION_FAILED` error. The valid (admitted) mutations stay
1078
+ * queued in FIFO order. Returns the drained stale entries.
1079
+ *
1080
+ * Called during reconnect before the flush cycle to weed out writes whose
1081
+ * assumptions no longer hold (e.g. a document was deleted by another client).
1082
+ */
1083
+ drainConflict(): QueuedMutation[];
200
1084
  clear(): void;
1085
+ /** The durable form of a queued write. */
1086
+ private recordOf;
1087
+ /** Append `record`, remembering it as unpersisted if the append is rejected. */
1088
+ private persist;
1089
+ /**
1090
+ * The durable half of {@link OfflineQueue.restampIdentity}: rewrite the
1091
+ * persisted record under the new identity stamp.
1092
+ *
1093
+ * This used to be `remove` then `append` (because `append` is an insert, not
1094
+ * an upsert) with a compensating re-append on failure, and no arrangement of
1095
+ * those two calls is safe. A process stop between a committed `remove` and
1096
+ * the `append` leaves the mutation in NO durable store while the in-memory
1097
+ * entry has already advanced, so a reload loses the write outright — and
1098
+ * compensation cannot cover a crash, only a rejection. The re-append also
1099
+ * moved the record to the tail, replaying it out of issue order.
1100
+ *
1101
+ * `PersistenceAdapter.replace` is the single atomic operation that removes
1102
+ * both: the swap lands whole or not at all, and the record keeps its place
1103
+ * in FIFO order. A rejection means nothing changed durably — the record
1104
+ * stands under its OLD stamp, which is the documented outcome (a replay
1105
+ * under a stale stamp is refused with `OFFLINE_IDENTITY_CHANGED`, visible
1106
+ * and recoverable, unlike a silent loss) — so there is nothing to
1107
+ * compensate, only to report.
1108
+ */
1109
+ private rewriteStamp;
1110
+ /**
1111
+ * Evict entries from the FRONT of `items` (the oldest — FIFO order) until
1112
+ * the queue is at or under `maxItems`, rejecting each with
1113
+ * `OFFLINE_QUEUE_OVERFLOW`, un-persisting it, and firing `onEvict`. Shared
1114
+ * by `enqueue` (a live write pushes past capacity) and `hydrate` (a durable
1115
+ * store restored more than `maxItems` records — CLIENT-03) so an overflow
1116
+ * always drops the same way regardless of which caller triggered it.
1117
+ */
1118
+ private evictOverflow;
1119
+ private markReplaying;
1120
+ /** Notify the size observer (the client's pending-sync count) after any change. */
1121
+ private notifySize;
201
1122
  }
202
1123
  /**
203
- * In-memory {@link PersistenceAdapter}. Doesn't survive a reload — it exists so
204
- * the persistence wiring can be exercised without IndexedDB (tests, SSR, or as
205
- * a deliberate "no durable store" choice that still satisfies the interface).
206
- * Preserves enqueue order; `clone` keeps callers from mutating stored args.
207
- */
1124
+ * In-memory {@link PersistenceAdapter}. Doesn't survive a reload — it exists so
1125
+ * the persistence wiring can be exercised without IndexedDB (tests, SSR, or as
1126
+ * a deliberate "no durable store" choice that still satisfies the interface).
1127
+ * Preserves enqueue order; `clone` keeps callers from mutating stored args.
1128
+ */
208
1129
  declare const createInMemoryPersistence: () => PersistenceAdapter;
209
1130
  interface IndexedDbPersistenceOptions {
210
- /** Database name; defaults to `"lunora"`. */
1131
+ /** Database name; defaults to `"lunora-outbox"` (its own DB, separate from the read cache). */
211
1132
  databaseName?: string;
212
1133
  /** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
213
1134
  indexedDB?: IDBFactory;
@@ -215,67 +1136,77 @@ interface IndexedDbPersistenceOptions {
215
1136
  storeName?: string;
216
1137
  }
217
1138
  /**
218
- * IndexedDB-backed {@link PersistenceAdapter}. Each mutation is stored under an
219
- * autoincrementing key (so `load()` returns them in enqueue order regardless of
220
- * the string ids) with a unique secondary index on `id` for `remove()`.
221
- *
222
- * The store handle is opened lazily and the open promise is cached, so repeated
223
- * ops reuse one connection. Throws eagerly if no `IDBFactory` is available —
224
- * callers in non-browser environments should use {@link createInMemoryPersistence}.
225
- */
1139
+ * IndexedDB-backed {@link PersistenceAdapter}. Each mutation is stored under an
1140
+ * autoincrementing key (so `load()` returns them in enqueue order regardless of
1141
+ * the string ids) with a unique secondary index on `id` for `remove()`.
1142
+ *
1143
+ * The store handle is opened lazily and the open promise is cached, so repeated
1144
+ * ops reuse one connection. Throws eagerly if no `IDBFactory` is available —
1145
+ * callers in non-browser environments should use {@link createInMemoryPersistence}.
1146
+ */
226
1147
  declare const createIndexedDbPersistence: (options?: IndexedDbPersistenceOptions) => PersistenceAdapter;
227
1148
  /**
228
- * Compose the read-cache key for a subscription. Mirrors how
229
- * `SubscriptionRegistry` keys live subscriptions so a hydrated value lines up
230
- * with the subscription that will consume it. `shardKey` defaults to `""` (the
231
- * root shard) exactly as the registry does.
232
- */
1149
+ * Compose the read-cache key for a subscription. Mirrors how
1150
+ * `SubscriptionRegistry` keys live subscriptions so a hydrated value lines up
1151
+ * with the subscription that will consume it. `shardKey` defaults to `""` (the
1152
+ * root shard) exactly as the registry does.
1153
+ */
233
1154
  declare const queryCacheKey: (functionPath: string, argsKey: string, shardKey?: string) => string;
234
1155
  /**
235
- * In-memory {@link QueryCacheAdapter}. Doesn't survive a reload — it exists so
236
- * the read-cache wiring can be exercised without IndexedDB (tests, SSR, or as a
237
- * deliberate "no durable store" choice that still satisfies the interface).
238
- * Enforces the same LRU row cap as the IndexedDB adapter; `clone` keeps callers
239
- * from mutating stored values.
240
- */
1156
+ * In-memory {@link QueryCacheAdapter}. Doesn't survive a reload — it exists so
1157
+ * the read-cache wiring can be exercised without IndexedDB (tests, SSR, or as a
1158
+ * deliberate "no durable store" choice that still satisfies the interface).
1159
+ * Enforces the same LRU row cap as the IndexedDB adapter; `clone` keeps callers
1160
+ * from mutating stored values.
1161
+ */
241
1162
  declare const createInMemoryQueryCache: (options?: {
242
1163
  maxEntries?: number;
243
1164
  }) => QueryCacheAdapter;
244
1165
  interface IndexedDbQueryCacheOptions {
245
- /** Database name; defaults to `"lunora"` (shared with the offline-mutation store). */
1166
+ /** Database name; defaults to `"lunora-query-cache"` (its own DB, separate from the offline outbox). */
246
1167
  databaseName?: string;
247
1168
  /** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
248
1169
  indexedDB?: IDBFactory;
249
- /** LRU row cap; defaults to 500. The oldest rows by `ts` are pruned on `put` once exceeded. */
1170
+ /** LRU row cap; defaults to 500. Must be a positive integer. The oldest rows by `ts` are pruned on `put` once exceeded. */
250
1171
  maxEntries?: number;
251
1172
  /** Object-store name; defaults to `"query-cache"`. */
252
1173
  storeName?: string;
253
1174
  }
254
1175
  /**
255
- * IndexedDB-backed {@link QueryCacheAdapter}. Each query is stored under its
256
- * composite key (`functionPath::argsKey::shardKey`) with a `ts` index driving
257
- * LRU eviction. The store handle is opened lazily and cached, so repeated ops
258
- * reuse one connection.
259
- *
260
- * The store lives in the same `lunora` database as the offline-mutation queue
261
- * (bumped to schema v2). Opening it upgrades a v1 database in place, adding the
262
- * `query-cache` store without touching `offline-mutations`. Throws eagerly if no
263
- * `IDBFactory` is available — callers in non-browser environments should use
264
- * {@link createInMemoryQueryCache}.
265
- */
1176
+ * IndexedDB-backed {@link QueryCacheAdapter}. Each query is stored under its
1177
+ * composite key (`functionPath::argsKey::shardKey`) with a `ts` index driving
1178
+ * LRU eviction. The store handle is opened lazily and cached, so repeated ops
1179
+ * reuse one connection.
1180
+ *
1181
+ * The store lives in its own `lunora-query-cache` database — deliberately
1182
+ * separate from the offline-mutation outbox's `lunora-outbox` database so the two
1183
+ * independently-toggleable adapters never share (and drift on) a schema version.
1184
+ * Throws eagerly if no `IDBFactory` is available — callers in non-browser
1185
+ * environments should use {@link createInMemoryQueryCache}.
1186
+ */
266
1187
  declare const createIndexedDbQueryCache: (options?: IndexedDbQueryCacheOptions) => QueryCacheAdapter;
267
1188
  /**
268
- * Exponential backoff calculator with optional jitter.
269
- *
270
- * `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
271
- * enabled the returned value is randomized in `[delay/2, delay]` so a fleet
272
- * of clients reconnecting at the same time spread out their retries.
273
- */
274
- interface ReconnectCalculator {
275
- /** Returns the delay to wait before the next reconnect attempt. */
276
- next: () => number;
277
- /** Resets the backoff to the initial delay (call on successful reconnect). */
278
- reset: () => void;
279
- }
280
- declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
281
- export { type ArgsOf, type AsyncStorageLike, type AsyncStoragePersistenceOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, type FunctionReference, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, type MutationCallOptions, type MutationDelta, type MutationRunnerSinks, OfflineQueue, type OfflineQueueOptions, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, type ReconnectCalculator, type ReconnectOptions, type ReturnOf, applyDelta, createAsyncStoragePersistence, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutationRunner, createReconnect, isConflictError, isMutationDelta, queryCacheKey };
1189
+ * Capture a snapshot of the current live query value at call time and produce a
1190
+ * `() => boolean` precondition that compares it against the value at replay time.
1191
+ *
1192
+ * When the precondition is checked (on queue drain / reconnect) it re-reads the
1193
+ * query's current state via {@link LunoraClient.peekActiveQuerySnapshot}. The
1194
+ * comparison only runs when a live subscription backed **both** reads; if either
1195
+ * read found no active subscription (e.g. the originating component unmounted
1196
+ * before replay, or a reconnect blanked it and it has not been answered again),
1197
+ * the precondition returns `true` (not stale) because absence of a subscription
1198
+ * is not evidence the value changed — the read simply cannot see it. When both reads did have a live subscription and the value differs, the
1199
+ * precondition returns `false` and the offline mutation is dropped as stale.
1200
+ *
1201
+ * The offline queue does not evaluate it while the subscription is still waiting
1202
+ * for its answer on a reconnected socket: the value it holds then is the previous
1203
+ * socket's (or blank), so the write stays queued until the answer lands.
1204
+ * @example
1205
+ * ```ts
1206
+ * client.mutation(api.todos.update, { id, text }, {
1207
+ * precondition: createSnapshotPrecondition(client, api.todos.list, { userId }),
1208
+ * });
1209
+ * ```
1210
+ */
1211
+ declare const createSnapshotPrecondition: (client: LunoraClient, functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string) => (() => boolean);
1212
+ export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type AuthTokenFetcher, type AuthTokenProviderOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, type ConnectLiveStreamOptions, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, type LiveStream, type LiveStreamEvent, type LiveStreamSubscribeError, type LiveStreamSubscribeOptions, type LiveTopicOptions, type LiveTopicRef, LunoraClient, type MutationDelta, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type OptimisticMessage, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, RETIRE_AFTER_DURABLE_SEQ_ADVANCE, type ReconcileDurableMessage, type ReconnectCalculator, type ReconnectOptions, type StreamIterable, type SubscribeLiveTopicOptions, type SubscriptionError, TabCoordinator, TransportError, type Unsubscribe, applyDelta, connectLiveStream, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createSnapshotPrecondition, getErrorCode, getRetryAfterMs, httpStream, isAuthReplayFailure, isConflictError, isForbiddenError, isMutationDelta, isRateLimitedError, isUnauthorizedError, liveTopicSubscription, maxSeq, queryCacheKey, reconcileOptimistic, setAuthTokenProvider, subscribeLiveTopic };