@lunora/client 1.0.0-alpha.28 → 1.0.0-alpha.280

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 (106) hide show
  1. package/README.md +19 -4
  2. package/dist/admin/index.d.mts +647 -0
  3. package/dist/admin/index.d.ts +647 -0
  4. package/dist/admin/index.mjs +1 -0
  5. package/dist/auth/index.d.mts +138 -5
  6. package/dist/auth/index.d.ts +138 -5
  7. package/dist/auth/index.mjs +1 -60
  8. package/dist/index.d.mts +756 -186
  9. package/dist/index.d.ts +756 -186
  10. package/dist/index.mjs +1 -21
  11. package/dist/packem_shared/ADMIN_AUTH_DEFAULT_PAGE_SIZE-V9c3bHU1.mjs +1 -0
  12. package/dist/packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs +1 -0
  13. package/dist/packem_shared/DEFAULT_MAX_BUFFER-Bd-_iyiV.mjs +1 -0
  14. package/dist/packem_shared/LunoraAdminClient-1KWk7JkZ.mjs +1 -0
  15. package/dist/packem_shared/LunoraClient-DKPUPbuv.mjs +1 -0
  16. package/dist/packem_shared/OfflineQueue-Ba2qgZK1.mjs +1 -0
  17. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  18. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  19. package/dist/packem_shared/SubscriptionRegistry-BKgQtuh9.mjs +1 -0
  20. package/dist/packem_shared/TabCoordinator-IUCwjnqX.mjs +1 -0
  21. package/dist/packem_shared/applyDelta-CaudNj2C.mjs +1 -0
  22. package/dist/packem_shared/base64-849R7V-V.mjs +1 -0
  23. package/dist/packem_shared/client-tuning-C10B2KCO.mjs +1 -0
  24. package/dist/packem_shared/client-urls-BHLUjjcG.mjs +1 -0
  25. package/dist/packem_shared/connectLiveStream-BdjsWP1-.mjs +1 -0
  26. package/dist/packem_shared/createAsyncStoragePersistence-BgfdvLwe.mjs +1 -0
  27. package/dist/packem_shared/createAsyncStorageQueryCache-6Y94ocbQ.mjs +1 -0
  28. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  29. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  30. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  31. package/dist/packem_shared/createInMemoryPersistence-C-IzNVbg.mjs +1 -0
  32. package/dist/packem_shared/createInMemoryQueryCache-DR6AorA2.mjs +1 -0
  33. package/dist/packem_shared/createLocalStore-D38o4O8Z.mjs +1 -0
  34. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  35. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  36. package/dist/packem_shared/createServerClient-97d5uFpA.mjs +1 -0
  37. package/dist/packem_shared/createSnapshotPrecondition-BXP1NPBW.mjs +1 -0
  38. package/dist/packem_shared/delta-merge-C6OqMEPH.mjs +1 -0
  39. package/dist/packem_shared/deserializePreloaded-DxozvweR.mjs +1 -0
  40. package/dist/packem_shared/frame-hint-D-NK691z.mjs +1 -0
  41. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  42. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  43. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  44. package/dist/packem_shared/httpStream-DN3D9WqW.mjs +7 -0
  45. package/dist/packem_shared/idb-utility-BS7xvou1.mjs +1 -0
  46. package/dist/packem_shared/live-stream-DBKgZlnb.mjs +10 -0
  47. package/dist/packem_shared/liveTopicSubscription-DQtKMFKw.mjs +1 -0
  48. package/dist/packem_shared/lunora-client-CNUU3FU7.mjs +1 -0
  49. package/dist/packem_shared/lunora-client.d-C8zXKzbE.d.mts +4966 -0
  50. package/dist/packem_shared/lunora-client.d-CAIGiEHg.d.ts +4966 -0
  51. package/dist/packem_shared/lunoraQueryKey-CucWmxnx.mjs +1 -0
  52. package/dist/packem_shared/offline-queue-BEqCPDmw.mjs +1 -0
  53. package/dist/packem_shared/optimistic-layers-D-7D3yeJ.mjs +1 -0
  54. package/dist/packem_shared/{preload.d-Cqb4Kh2I.d.ts → preload.d-CLx5oM3f.d.mts} +2 -1
  55. package/dist/packem_shared/{preload.d-CLwoXl3R.d.mts → preload.d-DTHQlBVJ.d.ts} +2 -1
  56. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  57. package/dist/packem_shared/setAuthTokenProvider-DhBppDiZ.mjs +1 -0
  58. package/dist/packem_shared/single-blob-store-DeaYPBSS.mjs +1 -0
  59. package/dist/packem_shared/snapshot-precondition-BEtcSbWr.mjs +1 -0
  60. package/dist/packem_shared/stream-idle-C7CsIT_m.mjs +1 -0
  61. package/dist/packem_shared/wire-errors-BDckSTKZ.mjs +1 -0
  62. package/dist/pagination/index.mjs +1 -61
  63. package/dist/query/index.d.mts +143 -4
  64. package/dist/query/index.d.ts +143 -4
  65. package/dist/query/index.mjs +1 -1
  66. package/dist/service.d.mts +49 -0
  67. package/dist/service.d.ts +49 -0
  68. package/dist/service.mjs +1 -0
  69. package/dist/ssr/index.d.mts +45 -16
  70. package/dist/ssr/index.d.ts +45 -16
  71. package/dist/ssr/index.mjs +1 -4
  72. package/dist/upload.d.mts +14 -0
  73. package/dist/upload.d.ts +14 -0
  74. package/dist/upload.mjs +1 -24
  75. package/package.json +15 -3
  76. package/dist/packem_shared/CONFLICT_ERROR_CODE-B8gQ8tyU.mjs +0 -33
  77. package/dist/packem_shared/ClientServiceWorker-C3PAFwy0.mjs +0 -100
  78. package/dist/packem_shared/DEFAULT_MAX_BUFFER-7hFnzNk9.mjs +0 -110
  79. package/dist/packem_shared/LunoraClient-DKATLGHY.mjs +0 -3631
  80. package/dist/packem_shared/OfflineQueue-BgarnAub.mjs +0 -1
  81. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  82. package/dist/packem_shared/SubscriptionRegistry-CxS_Inha.mjs +0 -31
  83. package/dist/packem_shared/TabCoordinator-D_5oNTTt.mjs +0 -258
  84. package/dist/packem_shared/applyDelta-CRKZ1PBt.mjs +0 -81
  85. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  86. package/dist/packem_shared/createClientQuery-dJZg1ohm.mjs +0 -80
  87. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  88. package/dist/packem_shared/createInMemoryPersistence-DZ2VHWgm.mjs +0 -79
  89. package/dist/packem_shared/createInMemoryQueryCache-DiaGZkA2.mjs +0 -112
  90. package/dist/packem_shared/createLocalStore-BtqUmOQA.mjs +0 -2
  91. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  92. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  93. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  94. package/dist/packem_shared/createReply-lI4tVS2w.mjs +0 -36
  95. package/dist/packem_shared/createServerClient-Bp2r9tcB.mjs +0 -11
  96. package/dist/packem_shared/createSnapshotPrecondition-CxQ1T4ZP.mjs +0 -18
  97. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  98. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  99. package/dist/packem_shared/httpStream-DIdL8NEw.mjs +0 -168
  100. package/dist/packem_shared/idb-utility-DrSVX43Q.mjs +0 -48
  101. package/dist/packem_shared/local-store-DIq-UWfD.mjs +0 -106
  102. package/dist/packem_shared/lunora-client.d-B1iZb2Ph.d.mts +0 -2845
  103. package/dist/packem_shared/lunora-client.d-B1iZb2Ph.d.ts +0 -2845
  104. package/dist/packem_shared/offline-queue-N-1JvYb4.mjs +0 -211
  105. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  106. package/dist/packem_shared/wire-key-Djie6aaR.mjs +0 -266
package/dist/index.d.ts CHANGED
@@ -1,7 +1,193 @@
1
- import { c as PersistenceAdapter, B as BookmarkStorage, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, F as FunctionReference, A as ArgsOf, M as MutationCallOptions, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, g as ReconnectOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-B1iZb2Ph.js";
2
- export { type h as BatchSlot, C as CONFLICT_ERROR_CODE, type i as CachedQuery, type j as ClientMessage, type k as ClientQueryRef, type l as ClientShapeSubscribeMessage, type m as ClientShapeUnsubscribeMessage, type n as ConnectionStatus, D as DEFAULT_MAX_BUFFER, type o as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type x as LunoraErrorCode, type y as MutationSettledEvent, type z as OptimisticLocalStore, type E as OptimisticUpdate, type I as OutboxMutation, type J as OutboxSink, type K as PersistedMutation, type P as Preloaded, type N as RowOp, type T as RpcEnvelope, type V as RpcResponseBody, type W as ScheduleRecord, type X as SchedulerPoolStatus, type Y as SchedulerStatus, type Z as ServerMessage, type _ as ServerPokeEndMessage, type $ as ServerPokePartMessage, type a0 as ServerPokeStartMessage, type a1 as ShardTrafficEntry, type a2 as ShardTrafficResult, type a3 as StorageListPage, type a4 as StorageObject, type a5 as StreamHandle, type a6 as SubscriptionCallback, type b as SubscriptionErrorCallback, a7 as SubscriptionRegistry, type a8 as SubscriptionState, type a9 as SyncWatermark, type a as Unsubscribe, type U as User, type aa as WorkflowInstanceAction, type ab as WorkflowInstanceDetail, type ac as WorkflowInstancePage, type ad as WorkflowInstanceStatus, type ae as WorkflowInstanceSummary, type af as WorkflowStepDetail, type ag as WsTokenProvider, ah as createClientQuery, ai as createLocalStore, aj as createStream, ak as getErrorCode, al as getRetryAfterMs, am as isConflictError, an as isForbiddenError, ao as isRateLimitedError, ap as isUnauthorizedError } from "./packem_shared/lunora-client.d-B1iZb2Ph.js";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-Cqb4Kh2I.js";
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-CAIGiEHg.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 WorkflowInstanceDetail, type aq as WorkflowInstancePage, type ar as WorkflowInstanceStatus, type as as WorkflowInstanceSummary, type at as WorkflowStepDetail, type au as WsTokenProvider, av as createClientQuery, aw as createLocalStore, ax as createStream } from "./packem_shared/lunora-client.d-CAIGiEHg.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-DTHQlBVJ.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";
4
8
  export type { AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, 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[];
5
191
  /**
6
192
  * The slice of React Native's `AsyncStorage` (or any async key/value store —
7
193
  * Expo `SecureStore`, a wrapped `localForage`, an in-memory map in tests) this
@@ -22,17 +208,122 @@ interface AsyncStoragePersistenceOptions {
22
208
  /**
23
209
  * Builds a {@link PersistenceAdapter} over an async key/value store — the React
24
210
  * 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.
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.
28
220
  *
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.
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.
32
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;
286
+ /**
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>);
36
327
  interface TabCoordinatorOptions {
37
328
  /**
38
329
  * BroadcastChannel name. Defaults to `"lunora-bridge"`.
@@ -51,18 +342,71 @@ interface TabCoordinatorOptions {
51
342
  * Called when this tab becomes the leader (should open WS connections).
52
343
  */
53
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;
54
368
  /**
55
369
  * Called when this tab loses leadership (should close WS connections).
56
370
  */
57
371
  onStopBeingLeader?: () => void;
58
372
  /**
59
- * Called when the leader broadcasts subscription data.
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).
60
383
  */
61
- onSubscriptionData?: (key: string, data: unknown) => void;
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;
62
386
  /**
63
- * Called when the leader broadcasts a subscription error.
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).
64
408
  */
65
- onSubscriptionError?: (key: string, error: SubscriptionError) => void;
409
+ onSubscriptionSettled?: (key: string, cursor?: number, epoch?: string, lastMutationId?: number, clientId?: string, identity?: string | null, claims?: string) => void;
66
410
  }
67
411
  declare class TabCoordinator {
68
412
  private readonly bc;
@@ -75,15 +419,33 @@ declare class TabCoordinator {
75
419
  private leader;
76
420
  /** `true` once `start()` has been called. */
77
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;
78
428
  /** Timestamp of the most recent leader heartbeat. */
79
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;
80
439
  private heartbeatTimer;
81
440
  private leaderCheckTimer;
82
441
  /** Callbacks set via constructor options. */
83
442
  private readonly onBecomeLeader;
84
443
  private readonly onStopBeingLeader;
444
+ private readonly onConnectionStatus;
85
445
  private readonly onSubscriptionData;
446
+ private readonly onLeaderClaimAnswered;
86
447
  private readonly onSubscriptionError;
448
+ private readonly onSubscriptionSettled;
87
449
  constructor(options?: TabCoordinatorOptions);
88
450
  /**
89
451
  * Start the coordinator: attempt to claim leadership and begin the
@@ -97,6 +459,23 @@ declare class TabCoordinator {
97
459
  stop(): void;
98
460
  /** `true` when this tab is the current WebSocket leader. */
99
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;
100
479
  /** The tab id of the current leader, or `undefined` if unknown / no leader. */
101
480
  get leaderTabId(): string | undefined;
102
481
  /** The id of this tab. */
@@ -105,15 +484,55 @@ declare class TabCoordinator {
105
484
  get isRunning(): boolean;
106
485
  /**
107
486
  * Broadcast subscription data to all follower tabs. Only the leader should
108
- * call this.
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".
109
496
  */
110
- broadcastSubscriptionData(key: string, data: unknown): void;
497
+ broadcastSubscriptionData(key: string, data: unknown, cursor?: number, epoch?: string, identity?: string | null, claims?: string): void;
111
498
  /**
112
499
  * Broadcast a subscription error to all follower tabs. Only the leader
113
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.
114
529
  */
115
- broadcastSubscriptionError(key: string, error: SubscriptionError): void;
530
+ broadcastConnectionStatus(status: ConnectionStatus, identity?: string | null): void;
116
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;
117
536
  private handleMessage;
118
537
  private handleClaimLeadership;
119
538
  private handleHeartbeat;
@@ -133,28 +552,15 @@ declare class TabCoordinator {
133
552
  private becomeLeader;
134
553
  private sendHeartbeat;
135
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;
136
563
  }
137
- /**
138
- * Client-side incremental merging of structured mutation deltas.
139
- *
140
- * Lunora's live-query fan-out has two server paths:
141
- *
142
- * 1. Server re-execution (subscriptions carrying a `functionPath`) pushes a
143
- * full `data` snapshot whenever a write touches a table the query reads. These
144
- * already carry the authoritative result and are applied wholesale.
145
- * 2. Legacy delta fan-out (`broadcastDelta`) pushes a structured `MutationDelta`
146
- * as a `delta` frame to subscribers matched by table + args. The delta describes
147
- * a single row change (`insert` / `update` / `delete`) keyed by row id, so the
148
- * client can splice it into the cached list result without a full re-send.
149
- *
150
- * Historically the client treated the `delta` field as an opaque blob and
151
- * replaced the whole cached value with it on every message — which only made
152
- * sense for the rare delta payloads that already carried the full result. This
153
- * module lets the client recognise a structured delta and merge it into the
154
- * existing array (preserving order, no dup/loss), falling back to full
155
- * replacement when the payload isn't a recognisable row delta or can't be
156
- * applied cleanly against the current cached shape.
157
- */
158
564
  /**
159
565
  * One row change as emitted by `@lunora/do`'s `broadcastDelta`. Mirrors
160
566
  * `MutationDelta` in `@lunora/do` structurally so the client carries no
@@ -177,28 +583,21 @@ interface MutationDelta {
177
583
  */
178
584
  declare const isMutationDelta: (value: unknown) => value is MutationDelta;
179
585
  /**
180
- * Apply a structured `MutationDelta` to a cached array result, returning a new
181
- * array (never mutating the input). Returns `undefined` when the delta can't be
586
+ * Apply a structured `MutationDelta` to a cached list result, returning a new
587
+ * value (never mutating the input). Returns `undefined` when the delta can't be
182
588
  * applied cleanly — the caller should then fall back to the existing
183
589
  * full-replacement behaviour (or trust the next snapshot to reconcile).
184
590
  *
185
- * Mergeable shape: a plain array of id-bearing row objects, e.g. the result of
186
- * `db.query().collect()`.
187
- *
188
- * Insert / update / delete are matched by row `_id`:
189
- * - `insert`: appended (or placed by `_creationTime` order) if absent; treated
190
- * as an update if a row with the same id already exists (idempotent — guards
191
- * against a delta replayed after a snapshot already included it).
192
- * - `update`: replaces the matching row in place, preserving its position.
193
- * - `delete`: removes the matching row.
194
- *
195
- * Returns `undefined` when `current` isn't an array of id-keyable objects, or
196
- * when an `insert`/`update` delta carries no `row` to splice in.
591
+ * Mergeable shapes: an array of id-bearing row objects, or a `.paginate()`
592
+ * result wrapping one in `page` (see `rowListOf`). A paginated value keeps its
593
+ * other fields and comes back as a new object with a new `page` — the server
594
+ * only sends row deltas for that shape when everything outside the page is
595
+ * unchanged, so the merged value matches the snapshot it chose not to send.
596
+ * @returns the merged value, or `undefined` when the delta cannot be applied
197
597
  */
198
- declare const applyDelta: (current: unknown, delta: MutationDelta) => undefined | unknown[];
598
+ declare const applyDelta: (current: unknown, delta: MutationDelta) => Record<string, unknown> | undefined | unknown[];
199
599
  /**
200
600
  * Options accepted by {@link httpStream}.
201
- * @experimental Part of the HTTP-SSE stream surface.
202
601
  */
203
602
  interface HttpStreamOptions {
204
603
  /**
@@ -211,8 +610,43 @@ interface HttpStreamOptions {
211
610
  fetch?: typeof fetch;
212
611
  /** Extra request headers (e.g. `authorization`). `accept: text/event-stream` is always sent. */
213
612
  headers?: Record<string, string>;
613
+ /**
614
+ * Treat a connection that delivers nothing — no chunk, no keepalive comment —
615
+ * for this many milliseconds as dead: it is cancelled, then reconnected with
616
+ * {@link HttpStreamOptions.reconnect} or failed with `STREAM_IDLE`. Off by
617
+ * default, because a route may be silent for as long as its handler works
618
+ * (a model thinking); set it to a few multiples of the route's keepalive
619
+ * interval when the route sends one.
620
+ *
621
+ * Measured per streamed read, so it needs a `fetch` that exposes
622
+ * `response.body`. A runtime whose `fetch` delivers no body stream (React
623
+ * Native) reads the whole payload with one `text()` call that resolves only
624
+ * at the end — no per-frame progress exists to measure silence against, so
625
+ * this bound does not apply there and a stalled read waits for
626
+ * `.cancel()` or {@link HttpStreamOptions.signal} instead.
627
+ */
628
+ idleTimeoutMs?: number;
629
+ /**
630
+ * Seed the first request's `Last-Event-ID` header, resuming a stream from a
631
+ * position a previous consumer persisted. Once frames arrive this is
632
+ * superseded by their `id:`, and a reconnecting stream always sends the
633
+ * latest id it saw.
634
+ */
635
+ lastEventId?: string;
214
636
  /** Caps the in-flight chunk buffer (see `createStream`); exceeding it fails the stream. */
215
637
  maxBuffer?: number;
638
+ /** Called with each frame's `id:` as it is seen (the value that will be replayed on reconnect). */
639
+ onEventId?: (id: string) => void;
640
+ /** Called when the server advertises a `retry:` reconnect delay, in milliseconds. */
641
+ onRetry?: (ms: number) => void;
642
+ /**
643
+ * Reopen the request after a transport interruption — a bare EOF or a
644
+ * read/transport error — replaying the last seen id as `Last-Event-ID`.
645
+ * Defaults to `false`, which surfaces the interruption as
646
+ * `HTTP_STREAM_INTERRUPTED` exactly as before. A terminal `complete`/`error`
647
+ * frame, a non-2xx status, and a consumer cancel never reconnect.
648
+ */
649
+ reconnect?: boolean;
216
650
  /** External abort signal — aborting it cancels the fetch (→ the server handler's `signal`). */
217
651
  signal?: AbortSignal;
218
652
  }
@@ -230,39 +664,132 @@ interface HttpStreamOptions {
230
664
  * an `event: error` frame (or a transport failure) surfaces as a coded
231
665
  * rejection on the next `next()`. `.cancel()` — or aborting `options.signal` —
232
666
  * aborts the underlying fetch, which the server observes via `request.signal`.
233
- * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
234
667
  */
235
668
  declare const httpStream: <Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: HttpStreamOptions) => StreamIterable<HttpStreamChunkOf<Ref>>;
236
- /** The single transport method a mutation runner needs — narrowed so adapters can test against a stub. */
237
- interface MutationCapableClient<F extends FunctionReference> {
238
- mutation: (function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>) => Promise<ReturnOf<F>>;
669
+ /** Options for {@link connectLiveStream}. */
670
+ interface ConnectLiveStreamOptions {
671
+ /** `fetch` override (a test seam, or a custom transport). */
672
+ fetch?: typeof fetch;
673
+ /** Extra headers sent on both the stream and the control requests. */
674
+ headers?: Record<string, string>;
675
+ /**
676
+ * Treat a connection that delivers nothing — not even a keepalive — for this many milliseconds as
677
+ * dead, and reconnect. Every target that serves live streams (Cloudflare Workers, the Node host
678
+ * and celld) runs the same `ShardDO` live handlers, and they write a `:ka` comment every 25s
679
+ * while a stream is open, so the default is `75000`. Set `0` to disable the bound when a proxy
680
+ * or a server of your own in front of the shard does not forward comment frames.
681
+ */
682
+ idleTimeoutMs?: number;
683
+ /** Ceiling for the reconnect backoff, in ms. Defaults to `30000`. */
684
+ maxDelayMs?: number;
685
+ /** Base reconnect delay in ms. Defaults to `1000`. */
686
+ retryDelay?: number;
687
+ /** Send cookies / credentials on the stream and control requests. */
688
+ withCredentials?: boolean;
689
+ }
690
+ /** A delivered live event. */
691
+ interface LiveStreamEvent {
692
+ /** The decoded payload the publisher sent. */
693
+ payload: unknown;
694
+ /** The topic the event was published on. */
695
+ topic: string;
696
+ }
697
+ /** Options for {@link LiveStream.subscribe}. */
698
+ /** A subscribe the shard refused for good: a reconnect would only be refused again. */
699
+ interface LiveStreamSubscribeError {
700
+ /** The HTTP status of the refusal, e.g. 403, 409 or 429. */
701
+ status: number;
702
+ subscriptionId: string;
703
+ topic: string;
704
+ }
705
+ interface LiveStreamSubscribeOptions {
706
+ /** Stable caller id; a generated one is used when omitted. */
707
+ id?: string;
708
+ /**
709
+ * Called when the shard refuses this subscription (403, 409, 429 and similar). The subscription is dropped
710
+ * first, so a later subscribe with the same id is accepted. A 401 is not reported: the stream reconnects,
711
+ * which re-authenticates and registers the subscription again.
712
+ */
713
+ onError?: (error: LiveStreamSubscribeError) => void;
714
+ /** Called for every event on `topic`. */
715
+ onEvent?: (payload: unknown) => void;
716
+ /** The topic to follow. */
717
+ topic: string;
718
+ }
719
+ /** A live stream connection. */
720
+ interface LiveStream {
721
+ /** Close the stream and stop reconnecting. */
722
+ close: () => void;
723
+ /** The server-minted connection id, or `undefined` before the first connect and while reconnecting. */
724
+ readonly connectionId: string | undefined;
725
+ /** Observe every event on the connection; returns an unsubscribe handle. */
726
+ onEvent: (handler: (event: LiveStreamEvent) => void) => () => void;
727
+ /** Resolves once the first connection is established (rejects only if `close`d first). */
728
+ readonly ready: Promise<void>;
729
+ /** Follow a topic; returns an unsubscribe handle. */
730
+ subscribe: (options: LiveStreamSubscribeOptions) => () => void;
239
731
  }
240
732
  /**
241
- * Reactive sinks an adapter binds to its own primitive's setters (a Solid
242
- * signal, a Vue ref, a Svelte store). The runner pushes into them; how they
243
- * store the value is the adapter's concern (e.g. Solid wraps function-valued
244
- * results in a thunk).
733
+ * Connect to a live topic stream. See the module docblock.
734
+ * @param url the `connect` route URL (its sibling `control` route is derived)
245
735
  */
246
- interface MutationRunnerSinks<R> {
247
- /** Receives the normalized {@link Error} when an invocation rejects. */
248
- setError: (error: Error) => void;
249
- /** Receives `true` while at least one invocation is in flight (ref-counted across overlapping calls), else `false`. */
250
- setPending: (pending: boolean) => void;
251
- /** Receives the resolved value when an invocation succeeds. */
252
- setResult: (result: R) => void;
736
+ declare const connectLiveStream: (url: string, options?: ConnectLiveStreamOptions) => LiveStream;
737
+ /**
738
+ * A reference to one declared live topic, as `_generated/live.ts` hands it out. Plain data
739
+ * (no server code), so a client bundle can hold it; the phantom `Payload` is what lets
740
+ * `ctx.live.publish` and the framework hooks type the event.
741
+ */
742
+ interface LiveTopicRef<Payload = unknown> {
743
+ /** Phantom: carries the declared payload type. Never present at runtime. */
744
+ readonly __payload?: Payload;
745
+ /** The `id` of the `defineLiveStream` that declares and authorizes this topic. */
746
+ readonly __lunoraLive: string;
747
+ /** The encoded wire topic (see {@link encodeLiveTopic}). */
748
+ readonly topic: string;
749
+ }
750
+ /** Options for {@link subscribeLiveTopic}. */
751
+ interface SubscribeLiveTopicOptions extends Omit<ConnectLiveStreamOptions, "fetch"> {
752
+ /** Called when the shard refuses this subscription (403, 409, 429 and similar). */
753
+ onError?: (error: LiveStreamSubscribeError) => void;
754
+ /** Called for every event on `topic`. */
755
+ onEvent?: (payload: unknown) => void;
756
+ /**
757
+ * Partitions the shared connection. A cookie-authenticated stream is bound to the session that opened it, so
758
+ * pass something that changes when the signed-in user does (a user id): a new value opens a new connection
759
+ * and the old one closes once its subscribers have moved. It is never sent to the server.
760
+ */
761
+ sessionKey?: string;
762
+ /** The topic to follow. */
763
+ topic: string;
764
+ /** The `connect` route URL of a `defineLiveStream`. */
765
+ url: string;
253
766
  }
254
767
  /**
255
- * Build the framework-neutral `mutate` half of an adapter's mutation hook.
256
- *
257
- * Owns the orchestration every adapter otherwise copy-pastes: ref-counts
258
- * overlapping invocations into `setPending` (so it only clears once the last
259
- * settles), normalizes a thrown non-`Error`, and routes success/failure to
260
- * `setResult`/`setError` before re-throwing. Each adapter (`@lunora/react`,
261
- * `/solid`, `/svelte`, `/vue`) binds the three sinks to its own reactive
262
- * setters, so this logic lives in exactly one place. Optimistic-update options
263
- * pass straight through to `client.mutation`.
768
+ * Follow `topic` on the shared connection for `url`.
769
+ * @returns an unsubscribe handle; the last one out closes the connection
264
770
  */
265
- 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>>);
771
+ declare const subscribeLiveTopic: (options: SubscribeLiveTopicOptions) => (() => void);
772
+ /**
773
+ * What a framework hook takes besides the topic reference: the transport tuning of
774
+ * {@link SubscribeLiveTopicOptions}, with `onEvent` typed by the topic's declared payload.
775
+ */
776
+ interface LiveTopicOptions<Payload = unknown> extends Omit<SubscribeLiveTopicOptions, "onEvent" | "topic" | "url"> {
777
+ /** Called for every event on the topic. The payload is the type the topic declares. */
778
+ onEvent?: (payload: Payload) => void;
779
+ /**
780
+ * Follow the topic on this shard: the connect URL gets `?shard=<key>`, and the control calls carry it too. Omit it
781
+ * for the default shard. Publish to the same shard with `{ shardKey }`, since delivery never crosses shards.
782
+ */
783
+ shardKey?: string;
784
+ }
785
+ /**
786
+ * Resolve a topic reference to the string-based options {@link subscribeLiveTopic} takes: the connect URL is the
787
+ * stream's route under the client's base URL, and the topic is the reference's encoded wire topic. Every framework
788
+ * hook goes through this, so they all build the same connection (and so share it).
789
+ */
790
+ declare const liveTopicSubscription: <Payload>(client: {
791
+ readonly url: string;
792
+ }, ref: LiveTopicRef<Payload>, options?: LiveTopicOptions<Payload>) => SubscribeLiveTopicOptions;
266
793
  /**
267
794
  * The structural surface of a TanStack `Transaction` a bound custom mutator
268
795
  * returns — its `isPersisted.promise` resolves once the write is persisted and
@@ -317,15 +844,48 @@ declare const createMutatorRunner: <TArgs>(handle: MutatorHandle<TArgs>, sinks:
317
844
  reset: () => void;
318
845
  };
319
846
  interface QueuedMutation<T = unknown> {
847
+ /**
848
+ * Set on a write that was queued because its direct send failed in a way that
849
+ * says nothing about its fate (see `LunoraClient.mutation`). Its caller is still
850
+ * waiting and was never told it failed, so the replay counts its transient
851
+ * failures and rejects it after a few, rather than retrying for ever.
852
+ */
853
+ readonly ambiguousSend?: boolean;
320
854
  readonly args: Record<string, unknown>;
855
+ /**
856
+ * CDC cursor this write was composed against (see
857
+ * {@link PersistedMutation.baselineSeq}). Persisted and restored so a replay is
858
+ * judged against what its author could see, not against what the client has
859
+ * since caught up to.
860
+ */
861
+ readonly baselineSeq?: number;
862
+ /**
863
+ * The client id that queued this write (see {@link PersistedMutation.clientId}).
864
+ * Persisted and restored, so a replay namespaces by the id that issued the
865
+ * write rather than whatever the current session minted.
866
+ */
867
+ clientId?: string;
321
868
  readonly functionPath: string;
322
869
  /** Stable id used to remove the entry from durable storage once replayed; assigned by the queue when absent. */
323
870
  id?: string;
324
871
  /**
325
872
  * Issuing identity fingerprint carried through to durable storage (`null` =
326
873
  * signed out). Absent on hydrated legacy records, which replay ambiently.
874
+ *
875
+ * Mutable so {@link OfflineQueue.restampIdentity} can relabel a still-queued
876
+ * write when the identity's LABEL changes but the credential does not (the
877
+ * `setAuthToken(token, userId)` case where the subject resolves a tick after
878
+ * the token). The value is re-persisted alongside, so the new label survives
879
+ * a reload and a requeue.
880
+ */
881
+ identity?: string | null;
882
+ /**
883
+ * Position in the order this session ISSUED its writes, taken before the first send. A write whose
884
+ * direct send failed ambiguously is queued only once that send gives up, behind writes issued (and
885
+ * queued) while it was in flight; this puts it back ahead of them. Absent on hydrated records,
886
+ * which are older than anything issued this session.
327
887
  */
328
- readonly identity?: string | null;
888
+ readonly issueSeq?: number;
329
889
  /**
330
890
  * `true` when a live caller is still awaiting this write's `mutation()`
331
891
  * Promise; `false`/absent for a write restored from durable storage after a
@@ -359,6 +919,14 @@ interface QueuedMutation<T = unknown> {
359
919
  * eviction), so the client can surface the dropped write on its
360
920
  * terminal-verdict observer even when the entry has no live awaiter (a hydrated
361
921
  * record). The `error` carries the `OFFLINE_QUEUE_OVERFLOW` code.
922
+ *
923
+ * The `sdks/*` ports deliberately do NOT mirror this shape — they return the
924
+ * discarded entry from `enqueue`/`hydrate`/`drainConflict`/`clear` instead,
925
+ * because they call the queue with a real lock held and settling a write needs
926
+ * that same lock, which self-deadlocks a non-reentrant one. Keep the callback
927
+ * here: this client is single-threaded, so the hazard does not exist, and an
928
+ * observer the queue fires itself is what covers the case a return value's
929
+ * consumer can quietly miss — a hydrated entry whose `reject` is a no-op.
362
930
  */
363
931
  type EvictHandler = (entry: QueuedMutation, error: Error & {
364
932
  code?: string;
@@ -367,6 +935,8 @@ type EvictHandler = (entry: QueuedMutation, error: Error & {
367
935
  interface OfflineQueueDeps {
368
936
  /** Invoked when an entry is discarded on capacity overflow (carries `OFFLINE_QUEUE_OVERFLOW`). */
369
937
  onEvict?: EvictHandler;
938
+ /** Invoked when a write that was out for replay settles, which `onSizeChange` does not cover: the queue was already shorter. */
939
+ onReplayingChange?: () => void;
370
940
  /** Invoked with the new depth after any size change (drives the client's pending-sync count). */
371
941
  onSizeChange?: (size: number) => void;
372
942
  /** Durable store; when present, writes are mirrored and restored across reloads. */
@@ -394,12 +964,44 @@ declare class OfflineQueue {
394
964
  private readonly persistence;
395
965
  private readonly onEvict;
396
966
  private readonly onSizeChange;
967
+ private readonly onReplayingChange;
397
968
  /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
398
969
  private readonly version;
399
970
  private readonly items;
971
+ /** Ids of writes a flush has {@link OfflineQueue.drain}ed and neither requeued nor discarded yet, which are on the wire or about to be. */
972
+ private readonly replayingIds;
973
+ /** 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. */
974
+ private readonly appending;
975
+ /**
976
+ * Writes enqueued this session and not yet settled (see {@link OfflineQueue.discard}). Unlike `items`
977
+ * this survives a replay temporarily draining the queue, so a failed append is tracked for as long as
978
+ * the write is unsettled, and a retry derives its record from the entry as it is NOW.
979
+ */
980
+ private readonly unsettled;
981
+ /** Ids whose append was rejected (a quota error, a closed connection), kept to be tried again — see {@link OfflineQueue.flushUnpersisted}. */
982
+ private readonly unpersisted;
400
983
  constructor(options?: OfflineQueueOptions, deps?: OfflineQueueDeps);
401
984
  get size(): number;
985
+ /** Writes drained for replay and not yet settled or requeued: out of {@link OfflineQueue.size}, but still unsettled. */
986
+ get replaying(): number;
402
987
  enqueue<T>(entry: QueuedMutation<T>): void;
988
+ /**
989
+ * Remove a settled write's durable record — after its append, if that is
990
+ * still in flight. A write that replays quickly can settle before its append
991
+ * has landed; a `remove` that overtook it found nothing, and the record then
992
+ * landed behind it and replayed in the next session.
993
+ */
994
+ discard(id: string): void;
995
+ /**
996
+ * Try again to persist every write whose append was rejected. Called when the
997
+ * page is being hidden: the last chance to get a still-queued write into
998
+ * durable storage before a reload or a discard of the tab loses it.
999
+ *
1000
+ * A write whose append is still in flight is skipped: `visibilitychange` and `pagehide` fire
1001
+ * back to back, and a second append for the same id would hit a unique-id constraint (or store
1002
+ * the record twice) and leave the write wrongly tracked as unpersisted.
1003
+ */
1004
+ flushUnpersisted(): void;
403
1005
  /**
404
1006
  * Restore mutations persisted in a prior session and re-queue them in FIFO
405
1007
  * order. Restored entries already live in durable storage, so they are not
@@ -419,6 +1021,33 @@ declare class OfflineQueue {
419
1021
  * silently clobber the newer data with the stale one.
420
1022
  */
421
1023
  hydrate(): Promise<(string | undefined)[]>;
1024
+ /**
1025
+ * Relabel every queued write stamped `from` to `to`, in memory AND in durable
1026
+ * storage.
1027
+ *
1028
+ * Used when the auth identity's LABEL changes while the credential does not —
1029
+ * `setAuthToken(token, userId)` where the user id resolves a tick after the
1030
+ * token was set. `setAuthToken` documents that this re-stamps in-flight
1031
+ * queued writes rather than dropping them, and that promise only held for the
1032
+ * caller's live in-memory stamp map, which is consumed and deleted on the
1033
+ * first flush attempt. Everything durable still carried the old token hash,
1034
+ * so a reload — or a transient-failure requeue after the token had since been
1035
+ * refreshed — fell back to it, failed the replay identity gate, and rejected
1036
+ * the SAME user's offline write with `OFFLINE_IDENTITY_CHANGED`.
1037
+ *
1038
+ * The durable rewrite goes through `PersistenceAdapter.replace`, the one
1039
+ * operation on the contract that is required to be atomic — see
1040
+ * {@link OfflineQueue.rewriteStamp}.
1041
+ */
1042
+ restampIdentity(from: string | null, to: string | null): void;
1043
+ /**
1044
+ * Whether any queued mutation matches — the cheap "is there a write ahead of
1045
+ * me on this shard?" question, answered without draining. A write held at
1046
+ * flush time (an identity not yet re-confirmed) sits here with no barrier
1047
+ * published for a later `mutation()` to wait on, so this is what keeps a
1048
+ * live write from overtaking it.
1049
+ */
1050
+ hasPending(predicate: (item: QueuedMutation) => boolean): boolean;
422
1051
  /**
423
1052
  * Remove and return queued mutations. With no `predicate`, drains the whole
424
1053
  * queue. With one, drains only matching entries (preserving FIFO order) and
@@ -444,6 +1073,41 @@ declare class OfflineQueue {
444
1073
  */
445
1074
  drainConflict(): QueuedMutation[];
446
1075
  clear(): void;
1076
+ /** The durable form of a queued write. */
1077
+ private recordOf;
1078
+ /** Append `record`, remembering it as unpersisted if the append is rejected. */
1079
+ private persist;
1080
+ /**
1081
+ * The durable half of {@link OfflineQueue.restampIdentity}: rewrite the
1082
+ * persisted record under the new identity stamp.
1083
+ *
1084
+ * This used to be `remove` then `append` (because `append` is an insert, not
1085
+ * an upsert) with a compensating re-append on failure, and no arrangement of
1086
+ * those two calls is safe. A process stop between a committed `remove` and
1087
+ * the `append` leaves the mutation in NO durable store while the in-memory
1088
+ * entry has already advanced, so a reload loses the write outright — and
1089
+ * compensation cannot cover a crash, only a rejection. The re-append also
1090
+ * moved the record to the tail, replaying it out of issue order.
1091
+ *
1092
+ * `PersistenceAdapter.replace` is the single atomic operation that removes
1093
+ * both: the swap lands whole or not at all, and the record keeps its place
1094
+ * in FIFO order. A rejection means nothing changed durably — the record
1095
+ * stands under its OLD stamp, which is the documented outcome (a replay
1096
+ * under a stale stamp is refused with `OFFLINE_IDENTITY_CHANGED`, visible
1097
+ * and recoverable, unlike a silent loss) — so there is nothing to
1098
+ * compensate, only to report.
1099
+ */
1100
+ private rewriteStamp;
1101
+ /**
1102
+ * Evict entries from the FRONT of `items` (the oldest — FIFO order) until
1103
+ * the queue is at or under `maxItems`, rejecting each with
1104
+ * `OFFLINE_QUEUE_OVERFLOW`, un-persisting it, and firing `onEvict`. Shared
1105
+ * by `enqueue` (a live write pushes past capacity) and `hydrate` (a durable
1106
+ * store restored more than `maxItems` records — CLIENT-03) so an overflow
1107
+ * always drops the same way regardless of which caller triggered it.
1108
+ */
1109
+ private evictOverflow;
1110
+ private markReplaying;
447
1111
  /** Notify the size observer (the client's pending-sync count) after any change. */
448
1112
  private notifySize;
449
1113
  }
@@ -494,7 +1158,7 @@ interface IndexedDbQueryCacheOptions {
494
1158
  databaseName?: string;
495
1159
  /** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
496
1160
  indexedDB?: IDBFactory;
497
- /** LRU row cap; defaults to 500. The oldest rows by `ts` are pruned on `put` once exceeded. */
1161
+ /** LRU row cap; defaults to 500. Must be a positive integer. The oldest rows by `ts` are pruned on `put` once exceeded. */
498
1162
  maxEntries?: number;
499
1163
  /** Object-store name; defaults to `"query-cache"`. */
500
1164
  storeName?: string;
@@ -512,28 +1176,22 @@ interface IndexedDbQueryCacheOptions {
512
1176
  * environments should use {@link createInMemoryQueryCache}.
513
1177
  */
514
1178
  declare const createIndexedDbQueryCache: (options?: IndexedDbQueryCacheOptions) => QueryCacheAdapter;
515
- /**
516
- * Exponential backoff calculator with optional jitter.
517
- *
518
- * `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
519
- * enabled the returned value is randomized in `[delay/2, delay]` so a fleet
520
- * of clients reconnecting at the same time spread out their retries.
521
- */
522
- interface ReconnectCalculator {
523
- /** Returns the delay to wait before the next reconnect attempt. */
524
- next: () => number;
525
- /** Resets the backoff to the initial delay (call on successful reconnect). */
526
- reset: () => void;
527
- }
528
- declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
529
1179
  /**
530
1180
  * Capture a snapshot of the current live query value at call time and produce a
531
1181
  * `() => boolean` precondition that compares it against the value at replay time.
532
1182
  *
533
1183
  * When the precondition is checked (on queue drain / reconnect) it re-reads the
534
- * query's current value via {@link LunoraClient.peekActiveQueryValue}. If the
535
- * value differs from what was captured at call time the precondition returns
536
- * `false` and the offline mutation is dropped as stale.
1184
+ * query's current state via {@link LunoraClient.peekActiveQuerySnapshot}. The
1185
+ * comparison only runs when a live subscription backed **both** reads; if either
1186
+ * read found no active subscription (e.g. the originating component unmounted
1187
+ * before replay, or a reconnect blanked it and it has not been answered again),
1188
+ * the precondition returns `true` (not stale) because absence of a subscription
1189
+ * 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
1190
+ * precondition returns `false` and the offline mutation is dropped as stale.
1191
+ *
1192
+ * The offline queue does not evaluate it while the subscription is still waiting
1193
+ * for its answer on a reconnected socket: the value it holds then is the previous
1194
+ * socket's (or blank), so the write stays queued until the answer lands.
537
1195
  * @example
538
1196
  * ```ts
539
1197
  * client.mutation(api.todos.update, { id, text }, {
@@ -542,92 +1200,4 @@ declare const createReconnect: (options?: ReconnectOptions, random?: () => numbe
542
1200
  * ```
543
1201
  */
544
1202
  declare const createSnapshotPrecondition: (client: LunoraClient, functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string) => (() => boolean);
545
- /**
546
- * Client-side service-worker registration and lifecycle management.
547
- *
548
- * Usage:
549
- * ```ts
550
- * const sw = new ClientServiceWorker({ swUrl: "/sw.js" });
551
- * await sw.register();
552
- *
553
- * if (sw.active) {
554
- * sw.postMessage({ type: "sync" });
555
- * }
556
- * ```
557
- */
558
- type ServiceWorkerStatus = "unsupported" | "unregistered" | "registering" | "active" | "error";
559
- interface ClientSwOptions {
560
- /** Called when the status changes. */
561
- onStatusChange?: (status: ServiceWorkerStatus) => void;
562
- /** Optional registration scope. Defaults to `/`. */
563
- scope?: string;
564
- /** URL of the service worker script (relative to origin). */
565
- swUrl: string;
566
- }
567
- /**
568
- * Manages service-worker registration and provides a simple API for
569
- * sending messages and listening for responses.
570
- */
571
- declare class ClientServiceWorker {
572
- #private;
573
- readonly swUrl: string;
574
- readonly scope: string;
575
- constructor(options: ClientSwOptions);
576
- /** Current registration status. */
577
- get status(): ServiceWorkerStatus;
578
- /** The underlying `ServiceWorkerRegistration`, if registered. */
579
- get registration(): ServiceWorkerRegistration | undefined;
580
- /** Whether the SW is currently controlling this page. */
581
- get active(): boolean;
582
- /**
583
- * Register the service worker.
584
- *
585
- * Returns `false` when the browser does not support service workers.
586
- */
587
- register(): Promise<boolean>;
588
- /**
589
- * Remove the active service worker registration and clear listeners.
590
- *
591
- * Returns `false` when no registration is currently held.
592
- */
593
- unregister(): Promise<boolean>;
594
- /**
595
- * Send a message to the active service worker.
596
- */
597
- postMessage(message: unknown): void;
598
- /**
599
- * Register a handler for messages **from** the service worker.
600
- * @returns Unsubscribe function.
601
- */
602
- onMessage(handler: (event: MessageEvent) => void): () => void;
603
- }
604
- /**
605
- * Outbound message from the client to the SW.
606
- */
607
- interface ClientToSwMessage {
608
- /** Opaque correlation ID for request/response patterns. */
609
- correlationId?: string;
610
- payload?: unknown;
611
- type: string;
612
- }
613
- /**
614
- * Inbound message from the SW to the client.
615
- */
616
- interface SwToClientMessage {
617
- /** Echoes the correlation ID from the client request, if any. */
618
- correlationId?: string;
619
- payload?: unknown;
620
- type: string;
621
- }
622
- /**
623
- * Send a typed message to the service worker and optionally await a
624
- * matching response.
625
- * @returns A promise that resolves when the SW sends a reply with the
626
- * same `correlationId` (if `expectResponse` is true).
627
- */
628
- declare const sendToSw: (sw: ServiceWorker | null, message: ClientToSwMessage, expectResponse?: boolean) => Promise<unknown>;
629
- /**
630
- * Create a reply for a client message (call from inside the SW).
631
- */
632
- declare const createReply: (original: ClientToSwMessage, payload?: unknown) => SwToClientMessage;
633
- export { type ArgsOf, type AsyncStorageLike, type AsyncStoragePersistenceOptions, type BookmarkStorage, ClientServiceWorker, type ClientSwOptions, type ClientToSwMessage, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, LunoraClient, type MutationCallOptions, type MutationDelta, type MutationRunnerSinks, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, type ReconnectCalculator, type ReconnectOptions, type ReturnOf, type ServiceWorkerStatus, type StreamIterable, type SubscriptionError, type SwToClientMessage, TabCoordinator, applyDelta, createAsyncStoragePersistence, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutationRunner, createMutatorRunner, createReconnect, createReply, createSnapshotPrecondition, httpStream, isMutationDelta, queryCacheKey, sendToSw };
1203
+ 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 };