@lunora/client 1.0.0-alpha.6 → 1.0.0-alpha.61

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 (88) hide show
  1. package/LICENSE.md +6 -0
  2. package/dist/auth/index.d.mts +11 -10
  3. package/dist/auth/index.d.ts +11 -10
  4. package/dist/auth/index.mjs +1 -60
  5. package/dist/index.d.mts +779 -230
  6. package/dist/index.d.ts +779 -230
  7. package/dist/index.mjs +1 -15
  8. package/dist/packem_shared/CONFLICT_ERROR_CODE-LjU7z0mB.mjs +1 -0
  9. package/dist/packem_shared/ClientServiceWorker-DXnBXeWK.mjs +1 -0
  10. package/dist/packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs +1 -0
  11. package/dist/packem_shared/LunoraClient-CMVwq6C2.mjs +1 -0
  12. package/dist/packem_shared/OfflineQueue-DG51qWl4.mjs +1 -0
  13. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  14. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  15. package/dist/packem_shared/SubscriptionRegistry-CdHSrDqu.mjs +1 -0
  16. package/dist/packem_shared/TabCoordinator-CXD7vulJ.mjs +1 -0
  17. package/dist/packem_shared/anyApi-CBOws2ZA.mjs +1 -0
  18. package/dist/packem_shared/applyDelta-DGqMpi3N.mjs +1 -0
  19. package/dist/packem_shared/createAsyncStoragePersistence-CNdM5o1u.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStorageQueryCache-Di-S52wy.mjs +1 -0
  21. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  22. package/dist/packem_shared/createClientQuery-TKD_52cT.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryPersistence-C0qm7c47.mjs +1 -0
  25. package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
  26. package/dist/packem_shared/createLocalStore-CZwiN9F4.mjs +1 -0
  27. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  28. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  29. package/dist/packem_shared/createReply-CwFABEJs.mjs +1 -0
  30. package/dist/packem_shared/createServerClient-D3TBy--H.mjs +1 -0
  31. package/dist/packem_shared/createSnapshotPrecondition-BPMQbAbk.mjs +1 -0
  32. package/dist/packem_shared/delta-merge-BoVuM-rE.mjs +1 -0
  33. package/dist/packem_shared/deserializePreloaded-CHfOFpka.mjs +1 -0
  34. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  35. package/dist/packem_shared/httpStream-x6q-x4yK.mjs +11 -0
  36. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  37. package/dist/packem_shared/local-store-tpI9VFpO.mjs +1 -0
  38. package/dist/packem_shared/lunora-client.d-CEJvJAXn.d.mts +2295 -0
  39. package/dist/packem_shared/lunora-client.d-CU6S8XiA.d.ts +2295 -0
  40. package/dist/packem_shared/offline-queue-CzI2lYQ8.mjs +1 -0
  41. package/dist/packem_shared/preload.d-7lAyp-Ky.d.mts +21 -0
  42. package/dist/packem_shared/preload.d-Gmmtaq2-.d.ts +21 -0
  43. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  44. package/dist/packem_shared/single-blob-store-DrhzObic.mjs +1 -0
  45. package/dist/packem_shared/types.d-BOB755CV.d.mts +1015 -0
  46. package/dist/packem_shared/types.d-BOB755CV.d.ts +1015 -0
  47. package/dist/packem_shared/wire-codec-D4iww4NV.mjs +1 -0
  48. package/dist/packem_shared/wire-key-BOdKmpG3.mjs +1 -0
  49. package/dist/pagination/index.d.mts +42 -42
  50. package/dist/pagination/index.d.ts +42 -42
  51. package/dist/pagination/index.mjs +1 -61
  52. package/dist/query/index.d.mts +110 -43
  53. package/dist/query/index.d.ts +110 -43
  54. package/dist/query/index.mjs +1 -1
  55. package/dist/service.d.mts +49 -0
  56. package/dist/service.d.ts +49 -0
  57. package/dist/service.mjs +1 -0
  58. package/dist/ssr/index.d.mts +100 -79
  59. package/dist/ssr/index.d.ts +100 -79
  60. package/dist/ssr/index.mjs +1 -4
  61. package/dist/upload.d.mts +35 -0
  62. package/dist/upload.d.ts +35 -0
  63. package/dist/upload.mjs +1 -0
  64. package/package.json +13 -1
  65. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  66. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  67. package/dist/packem_shared/LunoraClient-DhwA_5Kj.mjs +0 -2502
  68. package/dist/packem_shared/OfflineQueue-D-ASeqL7.mjs +0 -131
  69. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  70. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +0 -1
  71. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  72. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  73. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  74. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +0 -105
  75. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +0 -138
  76. package/dist/packem_shared/createLocalStore-DSUfoLqY.mjs +0 -36
  77. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  78. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  79. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  80. package/dist/packem_shared/createServerClient-XahK8bPv.mjs +0 -11
  81. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  82. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  83. package/dist/packem_shared/lunora-client.d-DzEWBYeP.d.mts +0 -1948
  84. package/dist/packem_shared/lunora-client.d-DzEWBYeP.d.ts +0 -1948
  85. package/dist/packem_shared/preload.d-CmMMC-wm.d.ts +0 -20
  86. package/dist/packem_shared/preload.d-DuYqEQ5J.d.mts +0 -20
  87. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  88. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +0 -55
package/dist/index.d.mts CHANGED
@@ -1,13 +1,104 @@
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-DzEWBYeP.mjs";
2
- export { type C as CachedQuery, type e as ClientMessage, type f as ClientShapeSubscribeMessage, type g as ClientShapeUnsubscribeMessage, type h as ConnectionStatus, D as DEFAULT_MAX_BUFFER, type i as FunctionArgumentDescriptor, type j as FunctionDescriptor, type G as GlobalFacetResult, type k as GlobalFacetValue, type l as GlobalFilterClause, type m as GlobalTableInfo, type n as GlobalTablePage, L as LunoraClient, type o as LunoraClientOptions, type p as OptimisticLocalStore, type q as OptimisticUpdate, type r as OutboxMutation, type s as OutboxSink, type t as PersistedMutation, type P as Preloaded, type u as RowOp, type v as RpcEnvelope, type w as RpcResponseBody, type x as ScheduleRecord, type y as SchedulerPoolStatus, type z as SchedulerStatus, type E as ServerMessage, type H as ServerPokeEndMessage, type I as ServerPokePartMessage, type J as ServerPokeStartMessage, type K as ShardTrafficEntry, type N as ShardTrafficResult, type T as StorageListPage, type V as StorageObject, type W as StreamHandle, type X as StreamIterable, type Y as SubscriptionCallback, type S as SubscriptionError, type b as SubscriptionErrorCallback, Z as SubscriptionRegistry, type _ as SubscriptionState, type $ as SyncWatermark, type a as Unsubscribe, type U as User, type a0 as WorkflowInstanceAction, type a1 as WorkflowInstanceDetail, type a2 as WorkflowInstancePage, type a3 as WorkflowInstanceStatus, type a4 as WorkflowInstanceSummary, type a5 as WorkflowStepDetail, a6 as createLocalStore, a7 as createStream } from "./packem_shared/lunora-client.d-DzEWBYeP.mjs";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-DuYqEQ5J.mjs";
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 { o as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, O as OfflineQueueOptions, p as ReconnectOptions, F as FunctionReference } from "./packem_shared/types.d-BOB755CV.mjs";
2
+ export type { A as ArgsOf, C as CachedQuery, q as ClientMessage, r as ClientShapeSubscribeMessage, s as ClientShapeUnsubscribeMessage, t as FunctionArgumentDescriptor, h as FunctionDescriptor, l as GlobalFacetResult, u as GlobalFacetValue, j as GlobalFilterClause, G as GlobalTableInfo, k as GlobalTablePage, v as HttpStreamCallArgs, L as LunoraClientOptions, w as OutboxMutation, x as OutboxSink, y as PersistedMutation, P as Preloaded, R as ReturnOf, z as RowOp, D as RpcEnvelope, E as RpcResponseBody, b as ScheduleRecord, I as SchedulerPoolStatus, c as SchedulerStatus, J as ServerMessage, K as ServerPokeEndMessage, M as ServerPokePartMessage, N as ServerPokeStartMessage, T as ShardTrafficEntry, S as ShardTrafficResult, i as StorageListPage, V as StorageObject, X as StoredQuery, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus, Y as WorkflowInstanceSummary, Z as WorkflowStepDetail, W as WsTokenProvider } from "./packem_shared/types.d-BOB755CV.mjs";
3
+ import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, L as LunoraClient } from "./packem_shared/lunora-client.d-CEJvJAXn.mjs";
4
+ export { type A as ActionCallOptions, type B as BatchSlot, c as CONFLICT_ERROR_CODE, type d as ClientDebugShard, type e as ClientDebugSnapshot, type f as ClientDebugSubscription, type g as ClientQueryRef, D as DEFAULT_MAX_BUFFER, type h as LunoraClientError, type i as LunoraErrorCode, type M as MutationCallOptions, type j as MutationSettledEvent, type O as OptimisticLocalStore, type k as OptimisticUpdate, type l as StreamHandle, type m as SubscriptionCallback, type a as SubscriptionErrorCallback, n as SubscriptionRegistry, type o as SubscriptionState, type p as SyncWatermark, q as createClientQuery, r as createLocalStore, s as createStream, t as getErrorCode, u as getRetryAfterMs, v as isConflictError, w as isForbiddenError, x as isRateLimitedError, y as isUnauthorizedError } from "./packem_shared/lunora-client.d-CEJvJAXn.mjs";
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-7lAyp-Ky.mjs";
6
+ 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';
7
+ declare const anyApi: Record<string, Record<string, unknown>>;
8
+ /**
9
+ * Optimistic-reconcile logic shared by every `@lunora/*` framework adapter's
10
+ * agent-chat surface (`@lunora/react` `useAgentChat`, plus the `@lunora/vue`,
11
+ * `@lunora/solid`, `@lunora/svelte`, and `@lunora/angular` counterparts). The
12
+ * adapters keep only their framework-specific state plumbing
13
+ * (`useState` / `.value` / `.set()` / a store) and delegate the pure merge decision
14
+ * here, so the heuristic lives — and is tested — in exactly one place.
15
+ */
16
+ /**
17
+ * The durable-message shape the reconcile reads: a structural subset of each
18
+ * adapter's `AgentChatMessage` (itself a client-safe mirror of `@lunora/agent`'s
19
+ * `AgentMessageRow`). Only `content`, `role`, and the globally-monotonic `seq` are
20
+ * consulted; adapters pass their fuller row type, which is assignable to this.
21
+ */
22
+ interface ReconcileDurableMessage {
23
+ content: string;
24
+ role: "assistant" | "system" | "tool" | "user";
25
+ seq: number;
26
+ }
27
+ /**
28
+ * A local optimistic user turn awaiting server acknowledgement. `id` is a
29
+ * client-generated handle the adapter uses to roll the row back on a failed send;
30
+ * the reconcile itself reads only `content` and `maxDurableSeqAtSend`.
31
+ */
32
+ interface OptimisticMessage {
33
+ content: string;
34
+ id: number;
35
+ /**
36
+ * The highest durable `seq` present when this row was sent. The reconcile
37
+ * retires the row when a durable `user` row with matching `content` lands at a
38
+ * STRICTLY GREATER `seq` (i.e. after the send) — window-independent because
39
+ * `seq` is globally monotonic, not a positional count. Also the age baseline for
40
+ * the {@link RETIRE_AFTER_DURABLE_SEQ_ADVANCE} fallback.
41
+ */
42
+ maxDurableSeqAtSend: number;
43
+ }
44
+ /**
45
+ * The highest `seq` across `messages`, or `-1` when empty. Used both to capture an
46
+ * optimistic row's `maxDurableSeqAtSend` at send time and to base the synthetic
47
+ * seqs of rendered optimistic rows above the highest real durable seq (not just
48
+ * `messages.length`, which under-counts when durable rows have gaps), so a
49
+ * placeholder seq never collides with a real one.
50
+ */
51
+ declare const maxSeq: (messages: ReadonlyArray<{
52
+ seq: number;
53
+ }>) => number;
54
+ /**
55
+ * Secondary, windowed fallback: retire a pending optimistic row once the durable
56
+ * history's highest `seq` has advanced at least this far past the value seen at
57
+ * send, even though no matching-content user row is currently visible to claim it.
58
+ * This covers the pathological "identical content already present at send time"
59
+ * case, where no user row with a STRICTLY GREATER `seq` than the send-time max will
60
+ * ever appear for the primary content match to consume (e.g. the acknowledging row
61
+ * was evicted by a bounded `limit` before reconcile could see it). `seq` is globally
62
+ * monotonic, so it keeps climbing even when the visible user-row COUNT does not.
63
+ *
64
+ * The `2` is a heuristic threshold, NOT an invariant about turn shape. It is
65
+ * tempting to read it as "one turn == a user row and an assistant row (+2)", but
66
+ * `@lunora/agent`'s tool-loop turns can persist MANY rows, and an ERRORED turn
67
+ * persists only the user row (+1). Those non-(+2) turns are retired by the PRIMARY
68
+ * seq-based content match below (which sees the user row land at a greater `seq`),
69
+ * never by this count-based fallback. The fully robust fix is a server-echoed
70
+ * correlation id on each persisted user row (deferred — see plan 188).
71
+ *
72
+ * KNOWN LIMITATION (inherent to a client-only heuristic): on an ownerless /
73
+ * `instanceId`-less thread a FOREIGN writer that advances `seq` by >= 2 between this
74
+ * row's send and its own acknowledgement can trip this fallback and retire the row a
75
+ * beat early. The correlation id closes that gap; until then it is the accepted
76
+ * residual edge.
77
+ */
78
+ declare const RETIRE_AFTER_DURABLE_SEQ_ADVANCE = 2;
79
+ /**
80
+ * Drop the optimistic user turns the durable history has now caught up on. Pure —
81
+ * it reads only the two arrays plus values captured on each pending row at send
82
+ * time (no clock, no state mutation), so it is safe to run in render.
83
+ *
84
+ * The primary retire condition: a durable `user` row with the same `content` exists
85
+ * whose `seq` is STRICTLY GREATER than the row's `maxDurableSeqAtSend` — i.e. a user
86
+ * row that landed AFTER the send. This is window-independent (it matches on monotonic
87
+ * `seq`, not a positional count), so it retires the normal turn AND an errored
88
+ * single-row (+1) turn even under a saturated, sliding `limit`. Each durable row is
89
+ * consumed at most once (the `consumed` set), so repeated identical prompts sent
90
+ * back-to-back each wait for their OWN durable row instead of collapsing onto one.
91
+ *
92
+ * Failing that, the {@link RETIRE_AFTER_DURABLE_SEQ_ADVANCE} windowed fallback fires
93
+ * (see its doc) for the "identical content already present" pathological case.
94
+ */
95
+ declare const reconcileOptimistic: (optimistic: ReadonlyArray<OptimisticMessage>, durable: ReadonlyArray<ReconcileDurableMessage>) => OptimisticMessage[];
96
+ /**
97
+ * The slice of React Native's `AsyncStorage` (or any async key/value store —
98
+ * Expo `SecureStore`, a wrapped `localForage`, an in-memory map in tests) this
99
+ * adapter needs. Matches `@react-native-async-storage/async-storage`'s core
100
+ * surface, so you can pass the module straight in.
101
+ */
11
102
  interface AsyncStorageLike {
12
103
  getItem: (key: string) => Promise<string | null>;
13
104
  removeItem: (key: string) => Promise<void>;
@@ -20,46 +111,325 @@ interface AsyncStoragePersistenceOptions {
20
111
  storage: AsyncStorageLike;
21
112
  }
22
113
  /**
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
- */
114
+ * Builds a {@link PersistenceAdapter} over an async key/value store — the React
115
+ * Native / Expo counterpart to the IndexedDB adapter (`createIndexedDbPersistence`).
116
+ * The whole FIFO mutation log is serialized to JSON under a single key (`key`),
117
+ * so enqueue order is preserved and `load()` returns freshly-parsed records that
118
+ * callers can't alias.
119
+ *
120
+ * AsyncStorage has no transactions, so every read-modify-write runs through
121
+ * {@link singleBlobStore}'s serialized chain — concurrent `append`/`remove`
122
+ * calls run one at a time and can't clobber each other's writes.
123
+ */
33
124
  declare const createAsyncStoragePersistence: (options: AsyncStoragePersistenceOptions) => PersistenceAdapter;
125
+ interface AsyncStorageQueryCacheOptions {
126
+ /** Storage key the cache is serialized under; defaults to `"lunora:query-cache"`. */
127
+ key?: string;
128
+ /** 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. */
129
+ maxEntries?: number;
130
+ /** The async key/value store the cache is read from and written to (e.g. React Native `AsyncStorage`). */
131
+ storage: AsyncStorageLike;
132
+ }
133
+ /**
134
+ * Builds a {@link QueryCacheAdapter} over an async key/value store — the React
135
+ * Native / Expo counterpart to `createIndexedDbQueryCache`. The whole cache is
136
+ * serialized under a single key (`key`).
137
+ *
138
+ * Values pass through the transport's {@link encodeWire}/{@link decodeWire}
139
+ * codec, NOT raw `JSON.stringify`. What this cache holds is a decoded SERVER
140
+ * value — whatever the query returned, including the `bigint`, `Date`, `Map`,
141
+ * `Set`, `ArrayBuffer`/typed-array, and `NaN`/`Infinity` leaves `decodeWire`
142
+ * just reconstructed on the way in. Raw JSON would mangle every one of them
143
+ * (`Date` to a string, bytes to `{}`, `NaN` to `null`) or throw outright on a
144
+ * `bigint`, and nothing would ever repair it: a `resume` frame keeps the
145
+ * hydrated value as-is, so the damage would survive every reconnect and every
146
+ * delta merged onto it. The IndexedDB sibling gets this for free via structured
147
+ * clone; here it is explicit. (This is what separates the read cache from the
148
+ * outbox, which stores JSON-safe args the caller chose.)
149
+ *
150
+ * AsyncStorage has no transactions, so every read-modify-write runs through
151
+ * {@link singleBlobStore}'s serialized chain — concurrent `put`/`remove` calls
152
+ * run one at a time and can't clobber each other's writes.
153
+ *
154
+ * Single-blob storage rewrites the whole cache per `put` (bounded by
155
+ * `maxEntries` — see the cap's note on Android's row and shared-budget limits);
156
+ * if that ever shows up in profiles, per-key storage entries are the upgrade
157
+ * path.
158
+ */
159
+ declare const createAsyncStorageQueryCache: (options: AsyncStorageQueryCacheOptions) => QueryCacheAdapter;
34
160
  /** Default in-memory bookmark store. Survives the lifetime of the client. */
35
161
  declare const createInMemoryBookmarkStorage: () => BookmarkStorage;
36
162
  /**
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
- */
163
+ * Reactive sinks an adapter binds to its own primitive's setters (a React
164
+ * `useState`, a Solid signal, a Vue ref, a Svelte store). The runner pushes into
165
+ * them; how they store the value is the adapter's concern (e.g. Solid and React
166
+ * wrap function-valued results in a thunk so the setter stores them rather than
167
+ * invoking them).
168
+ */
169
+ interface CallRunnerSinks<R> {
170
+ /** Receives the normalized {@link Error} when the latest invocation rejects. */
171
+ setError: (error: Error) => void;
172
+ /** Receives `true` while at least one invocation is in flight (ref-counted across overlapping calls), else `false`. */
173
+ setPending: (pending: boolean) => void;
174
+ /** Receives the resolved value when the latest invocation succeeds. */
175
+ setResult: (result: R) => void;
176
+ }
177
+ /**
178
+ * Build the framework-neutral half of an adapter's write primitive the `mutate`
179
+ * of `useMutation`/`createMutation`/`mutation`, and the `call` of
180
+ * `useAction`/`createAction`/`action`.
181
+ *
182
+ * It owns the orchestration every adapter otherwise copy-pastes: ref-counting
183
+ * overlapping invocations into `setPending` (so the flag clears only once the
184
+ * last settles), normalizing a thrown non-`Error`, and routing success/failure to
185
+ * `setResult`/`setError` before re-throwing the SAME instance (so a typed error's
186
+ * `.code`/`.data` survive for both the `catch` and the template).
187
+ *
188
+ * `invoke` is a pre-bound thunk — `(args, options) => client.mutation(fn, args, options)`
189
+ * or `(args, options) => client.action(fn, args, options)`. Binding at the call
190
+ * site is what keeps this one function: the runner never inspects `options`, it
191
+ * only forwards them, so the option type is inferred from the closure rather
192
+ * than hard-coded per procedure kind. What actually keeps `optimisticUpdate` off
193
+ * an action is the adapter's exported handle type, not this file.
194
+ *
195
+ * `data`/`error` track the LATEST invocation, not the last to settle: overlapping
196
+ * calls can resolve out of order, so an earlier call that finishes later must not
197
+ * clobber a newer call's outcome. Each invocation takes a monotonic token and
198
+ * writes the value sinks only while it is still the most recent one — otherwise a
199
+ * double-click could leave the UI showing the first click's result, or an error
200
+ * for a call that succeeded.
201
+ */
202
+ declare const createCallRunner: <A, O, R>(invoke: (args: A, options?: O) => Promise<R>, sinks: CallRunnerSinks<R>) => ((args: A, options?: O) => Promise<R>);
203
+ interface TabCoordinatorOptions {
204
+ /**
205
+ * BroadcastChannel name. Defaults to `"lunora-bridge"`.
206
+ */
207
+ channelName?: string;
208
+ /**
209
+ * Interval (ms) between leader heartbeats. Defaults to 1000.
210
+ */
211
+ heartbeatInterval?: number;
212
+ /**
213
+ * Milliseconds without a heartbeat to consider the leader dead. Must be
214
+ * larger than `heartbeatInterval`. Defaults to 3000.
215
+ */
216
+ leaderTimeout?: number;
217
+ /**
218
+ * Called when this tab becomes the leader (should open WS connections).
219
+ */
220
+ onBecomeLeader?: () => void;
221
+ /**
222
+ * Called when the leader broadcasts its aggregate `ConnectionStatus`
223
+ * (see `LunoraClient.emitConnectionStatus`) — a follower owns no socket
224
+ * of its own, so this is its only truthful signal for a status indicator
225
+ * or the offline-queue gate. Sent on every leader-side status change and
226
+ * once more right after a new leader takes over, so a follower already
227
+ * mid-mirroring isn't stuck on a stale value from the PREVIOUS leader.
228
+ *
229
+ * `identity` is the leader's own `identityFingerprint()` (`null` = signed
230
+ * out) — the channel-name scoping (see `LunoraClient.createTabCoordinator`)
231
+ * is the primary defence against a stale frame from a since-changed
232
+ * identity, but `setAuthToken` in one tab can move it to a new channel
233
+ * while this frame is already queued in another tab's message task queue.
234
+ * A follower drops the frame when `identity` is present and doesn't match
235
+ * its own; an **absent** `identity` (mixed-version leader) is accepted —
236
+ * today's behavior, and the channel split already separates version groups.
237
+ */
238
+ onConnectionStatus?: (status: ConnectionStatus, identity?: string | null) => void;
239
+ /**
240
+ * Called when the leader broadcasts a subscription error.
241
+ */
242
+ /** Fired on the LEADER when it answers another tab's leadership claim — the moment a new follower is known to be listening. */
243
+ onLeaderClaimAnswered?: () => void;
244
+ /**
245
+ * Called when this tab loses leadership (should close WS connections).
246
+ */
247
+ onStopBeingLeader?: () => void;
248
+ /**
249
+ * Called when the leader broadcasts subscription data. `cursor`/`epoch`
250
+ * ride along when the leader is CLIENT-01-aware, so the follower can drop
251
+ * its own confirmed optimistic layers instead of just displaying the raw
252
+ * value; both are absent on a mixed-version leader that hasn't shipped the
253
+ * cursor yet (the follower falls back to its historical behavior — see
254
+ * `lunora-client.ts`'s `onSubscriptionData` wiring).
255
+ *
256
+ * `identity` is the leader's `identityFingerprint()` (see
257
+ * `onConnectionStatus`'s docblock for the full rationale and the
258
+ * absent-field mixed-version rule — identical here).
259
+ */
260
+ onSubscriptionData?: (key: string, data: unknown, cursor?: number, epoch?: string, identity?: string | null) => void;
261
+ onSubscriptionError?: (key: string, error: SubscriptionError, identity?: string | null) => void;
262
+ /**
263
+ * Called when the leader broadcasts a `settled` frame's checkpoint advance
264
+ * (no value change, but the resume cursor moved). A follower needs this
265
+ * too — otherwise a `setQuery`/per-call optimistic overlay that a
266
+ * byte-identical write just confirmed stays masked on follower tabs until
267
+ * the next VISIBLE data frame arrives, even though the leader already
268
+ * dropped it.
269
+ *
270
+ * `lastMutationId` is the LEADER's own per-client `__client_watermark` —
271
+ * scoped server-side to the socket's announced `clientId` — so it only
272
+ * means anything to a follower whose `clientId` matches the leader's
273
+ * (`clientId` rides along for exactly that comparison; see
274
+ * `LunoraClient`'s wiring). An **absent** `clientId` (a mixed-version
275
+ * leader that hasn't shipped this field yet) also skips the
276
+ * `mutationId` half — safe, because the follower's own gates still
277
+ * resolve via its own RPC-ack watermark path and the `CheckpointRegistry`
278
+ * bounded fallback. The checkpoint (cursor) half of this callback fires
279
+ * unconditionally regardless of `clientId` — only the `mutationId` half
280
+ * is scoped.
281
+ *
282
+ * `identity` is the leader's `identityFingerprint()` — see
283
+ * `onConnectionStatus`'s docblock for the drop rule (identical here).
284
+ */
285
+ onSubscriptionSettled?: (key: string, cursor?: number, epoch?: string, lastMutationId?: number, clientId?: string, identity?: string | null) => void;
286
+ }
287
+ declare class TabCoordinator {
288
+ private readonly bc;
289
+ private readonly tabId;
290
+ private readonly heartbeatInterval;
291
+ private readonly leaderTimeout;
292
+ /** The tab id of the current known leader, or `undefined` if no leader. */
293
+ private knownLeader;
294
+ /** `true` when this tab believes it is the leader. */
295
+ private leader;
296
+ /** `true` once `start()` has been called. */
297
+ private running;
298
+ /**
299
+ * `true` while a `claimAndPromote()` claim window is open. Guards the yield
300
+ * handler and `checkLeaderHealth`'s belt-and-braces else-branch so the two
301
+ * promotion paths can't both arm a `becomeLeader` timeout for the same gap.
302
+ */
303
+ private promotionPending;
304
+ /** Timestamp of the most recent leader heartbeat. */
305
+ private lastHeartbeat;
306
+ private heartbeatTimer;
307
+ private leaderCheckTimer;
308
+ /** Callbacks set via constructor options. */
309
+ private readonly onBecomeLeader;
310
+ private readonly onStopBeingLeader;
311
+ private readonly onConnectionStatus;
312
+ private readonly onSubscriptionData;
313
+ private readonly onLeaderClaimAnswered;
314
+ private readonly onSubscriptionError;
315
+ private readonly onSubscriptionSettled;
316
+ constructor(options?: TabCoordinatorOptions);
317
+ /**
318
+ * Start the coordinator: attempt to claim leadership and begin the
319
+ * heartbeat/leader-check cycle. Safe to call multiple times.
320
+ */
321
+ start(): void;
322
+ /**
323
+ * Stop the coordinator: yield leadership (if held), close the channel, and
324
+ * clear all timers. Safe to call multiple times.
325
+ */
326
+ stop(): void;
327
+ /** `true` when this tab is the current WebSocket leader. */
328
+ isLeader(): boolean;
329
+ /**
330
+ * Force this (freshly `start()`-ed) tab to become leader immediately,
331
+ * skipping the normal claim-then-`leaderTimeout` dance. Safe to call
332
+ * right after `start()` when the caller already knows this tab was the
333
+ * SOLE leader of the group it's replacing (e.g. `LunoraClient`'s
334
+ * identity-change coordinator restart — waiting out the full
335
+ * `leaderTimeout` there would freeze every live query for no reason,
336
+ * since this tab is overwhelmingly likely to be alone on the freshly
337
+ * derived channel). A sibling tab going through the normal `start()`
338
+ * dance for the SAME transition observes this tab's `becomeLeader`
339
+ * heartbeat and defers before its own claim-timeout fires; if another
340
+ * tab ALSO force-promotes at the same moment (e.g. two tabs both
341
+ * transitioning to the same new identity), the existing
342
+ * `resolveLeaderVsLeaderTieBreak` resolves the rare double-promotion
343
+ * the same way it resolves any other split-brain.
344
+ */
345
+ promoteImmediately(): void;
346
+ /** The tab id of the current leader, or `undefined` if unknown / no leader. */
347
+ get leaderTabId(): string | undefined;
348
+ /** The id of this tab. */
349
+ get id(): string;
350
+ /** `true` when the coordinator has been started and is not yet stopped. */
351
+ get isRunning(): boolean;
352
+ /**
353
+ * Broadcast subscription data to all follower tabs. Only the leader should
354
+ * call this. `cursor`/`epoch` are omitted from the wire frame when
355
+ * `undefined` (e.g. a CDC-off shard) — a follower on ANY version treats a
356
+ * missing `cursor` as "no confirmed-layer drop this frame", so omitting it
357
+ * here is equivalent to sending it as `undefined`. `identity` is this
358
+ * (leader) tab's own `identityFingerprint()` (`null` = signed out) —
359
+ * stamped so a follower can drop a frame from a since-changed identity
360
+ * (see the `onSubscriptionData` docblock); spread-included whenever
361
+ * supplied, since a fixed leader always knows its own identity (never
362
+ * omits it) and `null` must round-trip distinctly from "field absent".
363
+ */
364
+ broadcastSubscriptionData(key: string, data: unknown, cursor?: number, epoch?: string, identity?: string | null): void;
365
+ /**
366
+ * Broadcast a subscription error to all follower tabs. Only the leader
367
+ * should call this.
368
+ *
369
+ * `identity` is this tab's own `identityFingerprint()`, stamped so a
370
+ * follower can drop a frame minted under a different credential — the same
371
+ * guard `broadcastSubscriptionData` and `broadcastSubscriptionSettled`
372
+ * carry. This one lacked it, which was harmless only because nothing called
373
+ * it; once the leader started fanning errors, an unstamped frame could
374
+ * deliver one caller's rejection to a tab that had since signed in as
375
+ * someone else.
376
+ */
377
+ broadcastSubscriptionError(key: string, error: SubscriptionError, identity?: string | null): void;
378
+ /**
379
+ * Broadcast a `settled` frame's checkpoint advance to all follower tabs
380
+ * (no value change, but the resume cursor/epoch moved — see
381
+ * `LunoraClient.handleSettledMessage`). `clientId` is this (leader) tab's
382
+ * own client id, stamped so a follower can tell whether the echoed
383
+ * `lastMutationId` watermark is genuinely its own (see the
384
+ * `onSubscriptionSettled` docblock). `identity` is this tab's own
385
+ * `identityFingerprint()` — see `broadcastSubscriptionData`'s docblock for
386
+ * the same round-tripping rule. Only the leader should call this.
387
+ */
388
+ broadcastSubscriptionSettled(key: string, cursor?: number, epoch?: string, lastMutationId?: number, clientId?: string, identity?: string | null): void;
389
+ /**
390
+ * Broadcast this tab's aggregate `ConnectionStatus` to follower tabs, so
391
+ * they can mirror a truthful status without a socket of their own (see
392
+ * `LunoraClient.computeStatus`/`emitConnectionStatus`). `identity` is this
393
+ * tab's own `identityFingerprint()` — see `broadcastSubscriptionData`'s
394
+ * docblock for the same round-tripping rule. Only the leader should call
395
+ * this.
396
+ */
397
+ broadcastConnectionStatus(status: ConnectionStatus, identity?: string | null): void;
398
+ private broadcast;
399
+ private handleMessage;
400
+ private handleClaimLeadership;
401
+ private handleHeartbeat;
402
+ /**
403
+ * Resolve two leaders existing at once — e.g. this tab was backgrounded
404
+ * and its heartbeat/health timers were throttled while a foreground
405
+ * follower's were not, so the follower's `checkLeaderHealth` timed out
406
+ * the (still-alive) leader and self-promoted. `BroadcastChannel` message
407
+ * delivery isn't subject to the same timer-throttling clamp, so even a
408
+ * backgrounded leader eventually observes the pretender's heartbeat here
409
+ * — resolve the split-brain deterministically with the same
410
+ * lexicographically-smaller-tabId rule used at claim-adoption. If the
411
+ * other tab wins, step down; if we win, reassert immediately so the
412
+ * pretender demotes itself the moment it processes our heartbeat.
413
+ */
414
+ private resolveLeaderVsLeaderTieBreak;
415
+ private becomeLeader;
416
+ private sendHeartbeat;
417
+ private checkLeaderHealth;
418
+ /**
419
+ * Broadcast a leadership claim and arm a `becomeLeader` fallback: if no
420
+ * other tab has asserted itself as leader by the time the window elapses,
421
+ * self-promote. Shared by `checkLeaderHealth`'s stale-leader path and the
422
+ * `yield-leadership` handler so both promotion triggers use one claim
423
+ * window instead of each arming its own timeout.
424
+ */
425
+ private claimAndPromote;
426
+ }
427
+ /**
428
+ * One row change as emitted by `@lunora/do`'s `broadcastDelta`. Mirrors
429
+ * `MutationDelta` in `@lunora/do` structurally so the client carries no
430
+ * dependency on it. `row` is absent on `delete` events (and may be absent on
431
+ * older servers for any op).
432
+ */
63
433
  interface MutationDelta {
64
434
  /** Row id (`_id`) the change applies to. */
65
435
  key: string;
@@ -68,98 +438,88 @@ interface MutationDelta {
68
438
  table: string;
69
439
  }
70
440
  /**
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
- */
441
+ * Structural guard: is `value` a `MutationDelta` the client knows how to merge?
442
+ * We require `op`, `table`, and a string `key` so opaque payloads that merely
443
+ * happen to be objects (e.g. an aggregate `{ count: 1 }` a query returns
444
+ * verbatim) are never mistaken for a row delta and keep replacing the cached
445
+ * value wholesale.
446
+ */
77
447
  declare const isMutationDelta: (value: unknown) => value is MutationDelta;
78
448
  /**
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";
100
- /**
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>>;
112
- }
449
+ * Apply a structured `MutationDelta` to a cached list result, returning a new
450
+ * value (never mutating the input). Returns `undefined` when the delta can't be
451
+ * applied cleanly — the caller should then fall back to the existing
452
+ * full-replacement behaviour (or trust the next snapshot to reconcile).
453
+ *
454
+ * Mergeable shapes: an array of id-bearing row objects, or a `.paginate()`
455
+ * result wrapping one in `page` (see `rowListOf`). A paginated value keeps its
456
+ * other fields and comes back as a new object with a new `page` — the server
457
+ * only sends row deltas for that shape when everything outside the page is
458
+ * unchanged, so the merged value matches the snapshot it chose not to send.
459
+ * @returns the merged value, or `undefined` when the delta cannot be applied
460
+ */
461
+ declare const applyDelta: (current: unknown, delta: MutationDelta) => Record<string, unknown> | undefined | unknown[];
113
462
  /**
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;
122
- /** Receives `true` while at least one invocation is in flight (ref-counted across overlapping calls), else `false`. */
123
- setPending: (pending: boolean) => void;
124
- /** Receives the resolved value when an invocation succeeds. */
125
- setResult: (result: R) => void;
463
+ * Options accepted by {@link httpStream}.
464
+ * @experimental Part of the HTTP-SSE stream surface.
465
+ */
466
+ interface HttpStreamOptions {
467
+ /**
468
+ * Origin (or origin + prefix) the route path is appended to, e.g.
469
+ * `https://my-app.example.com`. Defaults to `""` a relative URL, which
470
+ * resolves against the page origin in a browser.
471
+ */
472
+ baseUrl?: string;
473
+ /** `fetch` implementation override; defaults to the global `fetch`. */
474
+ fetch?: typeof fetch;
475
+ /** Extra request headers (e.g. `authorization`). `accept: text/event-stream` is always sent. */
476
+ headers?: Record<string, string>;
477
+ /** Caps the in-flight chunk buffer (see `createStream`); exceeding it fails the stream. */
478
+ maxBuffer?: number;
479
+ /** External abort signal — aborting it cancels the fetch (→ the server handler's `signal`). */
480
+ signal?: AbortSignal;
126
481
  }
127
482
  /**
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>>);
139
- /**
140
- * The structural surface of a TanStack `Transaction` a bound custom mutator
141
- * returns its `isPersisted.promise` resolves once the write is persisted and
142
- * rejects on failure. Typed structurally so the framework adapters need not
143
- * depend on `@tanstack/db` or `@lunora/db` (the handle is created app-side by
144
- * `bindMutators`).
145
- */
483
+ * Open a typed HTTP-SSE stream route and iterate its chunks:
484
+ *
485
+ * ```ts
486
+ * const stream = httpStream(httpStreams.http.tokens, { searchParams: { prompt } }, { baseUrl });
487
+ * for await (const token of stream) {
488
+ * render(token); // typed as the route handler's yielded chunk
489
+ * }
490
+ * ```
491
+ *
492
+ * The returned iterable terminates when the server writes `event: complete`;
493
+ * an `event: error` frame (or a transport failure) surfaces as a coded
494
+ * rejection on the next `next()`. `.cancel()` — or aborting `options.signal` —
495
+ * aborts the underlying fetch, which the server observes via `request.signal`.
496
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
497
+ */
498
+ declare const httpStream: <Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: HttpStreamOptions) => StreamIterable<HttpStreamChunkOf<Ref>>;
499
+ /**
500
+ * The structural surface of a TanStack `Transaction` a bound custom mutator
501
+ * returns — its `isPersisted.promise` resolves once the write is persisted and
502
+ * rejects on failure. Typed structurally so the framework adapters need not
503
+ * depend on `@tanstack/db` or `@lunora/db` (the handle is created app-side by
504
+ * `bindMutators`).
505
+ */
146
506
  interface MutatorTransaction {
147
507
  isPersisted: {
148
508
  promise: Promise<unknown>;
149
509
  };
150
510
  }
151
511
  /**
152
- * A bound custom-mutator handle produced by `bindMutators(client, ctx, mutators)`
153
- * in `@lunora/db`. Calling it applies the optimistic overlay to the local
154
- * collections and pushes the authoritative server write; it returns the TanStack
155
- * transaction whose `isPersisted` promise tracks completion.
156
- */
512
+ * A bound custom-mutator handle produced by `bindMutators(client, ctx, mutators)`
513
+ * in `@lunora/db`. Calling it applies the optimistic overlay to the local
514
+ * collections and pushes the authoritative server write; it returns the TanStack
515
+ * transaction whose `isPersisted` promise tracks completion.
516
+ */
157
517
  type MutatorHandle<TArgs> = (args: TArgs) => MutatorTransaction;
158
518
  /**
159
- * Reactive sinks an adapter binds to its own primitive's setters (a React
160
- * `useState`, a Solid signal, a Vue ref, a Svelte store). The runner pushes into
161
- * them; how they store the value is the adapter's concern.
162
- */
519
+ * Reactive sinks an adapter binds to its own primitive's setters (a React
520
+ * `useState`, a Solid signal, a Vue ref, a Svelte store). The runner pushes into
521
+ * them; how they store the value is the adapter's concern.
522
+ */
163
523
  interface MutatorRunnerSinks {
164
524
  /** Receives the normalized {@link Error} when an invocation rejects, or `undefined` on success / reset. */
165
525
  setError: (error: Error | undefined) => void;
@@ -167,38 +527,66 @@ interface MutatorRunnerSinks {
167
527
  setPending: (pending: boolean) => void;
168
528
  }
169
529
  /**
170
- * Build the framework-neutral `mutate` / `reset` pair of an adapter's
171
- * custom-mutator hook (`useMutator` / `createMutator` / `mutator`).
172
- *
173
- * Owns the orchestration every adapter otherwise copy-pastes: ref-counts
174
- * overlapping invocations into `setPending` (so it only clears once the last
175
- * settles), awaits the bound handle's `isPersisted` promise, normalizes a thrown
176
- * non-`Error`, and routes failure to `setError` (clearing it on success) before
177
- * re-throwing. Each adapter (`@lunora/react`, `/solid`, `/svelte`, `/vue`) binds
178
- * the two sinks to its own reactive setters, so this logic lives in exactly one
179
- * place. The optimistic overlay + server push are owned by the bound handle.
180
- *
181
- * `error` tracks the LATEST invocation, not the last to settle: overlapping
182
- * calls can resolve out of order, so an earlier call that finishes later must
183
- * not clobber a newer call's outcome. Each invocation takes a monotonic token
184
- * and only writes `setError` while it is still the most recent one — otherwise
185
- * `error`/`isError` could surface a stale success or failure (the documented
186
- * "latest invocation's error" contract every adapter advertises).
187
- */
530
+ * Build the framework-neutral `mutate` / `reset` pair of an adapter's
531
+ * custom-mutator hook (`useMutator` / `createMutator` / `mutator`).
532
+ *
533
+ * Owns the orchestration every adapter otherwise copy-pastes: ref-counts
534
+ * overlapping invocations into `setPending` (so it only clears once the last
535
+ * settles), awaits the bound handle's `isPersisted` promise, normalizes a thrown
536
+ * non-`Error`, and routes failure to `setError` (clearing it on success) before
537
+ * re-throwing. Each adapter (`@lunora/react`, `/solid`, `/svelte`, `/vue`) binds
538
+ * the two sinks to its own reactive setters, so this logic lives in exactly one
539
+ * place. The optimistic overlay + server push are owned by the bound handle.
540
+ *
541
+ * `error` tracks the LATEST invocation, not the last to settle: overlapping
542
+ * calls can resolve out of order, so an earlier call that finishes later must
543
+ * not clobber a newer call's outcome. Each invocation takes a monotonic token
544
+ * and only writes `setError` while it is still the most recent one — otherwise
545
+ * `error`/`isError` could surface a stale success or failure (the documented
546
+ * "latest invocation's error" contract every adapter advertises).
547
+ */
188
548
  declare const createMutatorRunner: <TArgs>(handle: MutatorHandle<TArgs>, sinks: MutatorRunnerSinks) => {
189
549
  mutate: (args: TArgs) => Promise<void>;
190
550
  reset: () => void;
191
551
  };
192
552
  interface QueuedMutation<T = unknown> {
193
553
  readonly args: Record<string, unknown>;
554
+ /**
555
+ * The client id that queued this write (see {@link PersistedMutation.clientId}).
556
+ * Persisted and restored, so a replay namespaces by the id that issued the
557
+ * write rather than whatever the current session minted.
558
+ */
559
+ clientId?: string;
194
560
  readonly functionPath: string;
195
561
  /** Stable id used to remove the entry from durable storage once replayed; assigned by the queue when absent. */
196
562
  id?: string;
197
563
  /**
198
- * Issuing identity fingerprint carried through to durable storage (`null` =
199
- * signed out). Absent on hydrated legacy records, which replay ambiently.
200
- */
564
+ * Issuing identity fingerprint carried through to durable storage (`null` =
565
+ * signed out). Absent on hydrated legacy records, which replay ambiently.
566
+ */
201
567
  readonly identity?: string | null;
568
+ /**
569
+ * `true` when a live caller is still awaiting this write's `mutation()`
570
+ * Promise; `false`/absent for a write restored from durable storage after a
571
+ * reload (its original awaiter is gone). Carried so terminal-verdict
572
+ * observers can distinguish "the caller already saw this" from "nothing else
573
+ * will report this". Maps to the public `MutationSettledEvent.hadAwaiter`.
574
+ */
575
+ liveAwaiter?: boolean;
576
+ /**
577
+ * Invoked on a successful replay with the server's echoed commit CDC cursor,
578
+ * so a live per-call optimistic layer drops gaplessly once a frame reaches it.
579
+ * Absent on hydrated records (the optimistic write lived in a prior session).
580
+ */
581
+ readonly onCommit?: (commitCursor: number | undefined) => void;
582
+ /**
583
+ * Optional sync predicate evaluated just before replay. When it returns
584
+ * `false` the write is dropped instead of replaying, handling the case
585
+ * where the mutation's preconditions are no longer valid (e.g. the
586
+ * document it referred to was deleted while offline). Absent or `true`
587
+ * means "ok to replay".
588
+ */
589
+ readonly precondition?: () => boolean;
202
590
  /** Rejects if the mutation can no longer be replayed. */
203
591
  readonly reject: (error: unknown) => void;
204
592
  /** Resolves once the mutation has been replayed against the server. */
@@ -206,71 +594,124 @@ interface QueuedMutation<T = unknown> {
206
594
  readonly shardKey?: string;
207
595
  }
208
596
  /**
209
- * A process-unique id, used both per-mutation and as the fallback `clientId`. It
210
- * MUST be globally unique: the server scopes a custom mutator's replay watermark
211
- * by `(verifiedIdentity, clientId)`, and an anonymous push has no verified
212
- * identity so two anonymous clients that collide on `clientId` would share one
213
- * watermark namespace, letting one stall/suppress the other's ordered mutations.
214
- * `crypto.randomUUID` covers every modern runtime; the fallback still mixes
215
- * crypto-quality (or `Math.random`) entropy with the timestamp + counter so it
216
- * can't collide across two clients started in the same millisecond.
217
- */
218
- /**
219
- * Bounded FIFO queue. Mutations issued while the client is offline are
220
- * enqueued and replayed in the order they were submitted once the WS
221
- * reconnects and identifies. If the queue exceeds `maxItems` the oldest
222
- * entry is rejected with `OFFLINE_QUEUE_OVERFLOW`.
223
- *
224
- * When a {@link PersistenceAdapter} is supplied, enqueued mutations are mirrored
225
- * to durable storage so they survive a reload {@link OfflineQueue.hydrate} restores them on
226
- * the next startup and the client replays them on reconnect. Durable removal is
227
- * the caller's responsibility *after* a successful replay (see `LunoraClient`);
228
- * the queue only persists on enqueue and un-persists on overflow.
229
- */
597
+ * Invoked when the queue itself discards an entry on overflow (capacity
598
+ * eviction), so the client can surface the dropped write on its
599
+ * terminal-verdict observer even when the entry has no live awaiter (a hydrated
600
+ * record). The `error` carries the `OFFLINE_QUEUE_OVERFLOW` code.
601
+ *
602
+ * The `sdks/*` ports deliberately do NOT mirror this shape — they return the
603
+ * discarded entry from `enqueue`/`hydrate`/`drainConflict`/`clear` instead,
604
+ * because they call the queue with a real lock held and settling a write needs
605
+ * that same lock, which self-deadlocks a non-reentrant one. Keep the callback
606
+ * here: this client is single-threaded, so the hazard does not exist, and an
607
+ * observer the queue fires itself is what covers the case a return value's
608
+ * consumer can quietly miss a hydrated entry whose `reject` is a no-op.
609
+ */
610
+ type EvictHandler = (entry: QueuedMutation, error: Error & {
611
+ code?: string;
612
+ }) => void;
613
+ /** Injected dependencies for {@link OfflineQueue} (kept off the user-facing {@link OfflineQueueOptions}). */
614
+ interface OfflineQueueDeps {
615
+ /** Invoked when an entry is discarded on capacity overflow (carries `OFFLINE_QUEUE_OVERFLOW`). */
616
+ onEvict?: EvictHandler;
617
+ /** Invoked with the new depth after any size change (drives the client's pending-sync count). */
618
+ onSizeChange?: (size: number) => void;
619
+ /** Durable store; when present, writes are mirrored and restored across reloads. */
620
+ persistence?: PersistenceAdapter;
621
+ /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
622
+ version?: string;
623
+ }
624
+ /**
625
+ * Bounded FIFO queue. Mutations issued while the client is offline are
626
+ * enqueued and replayed in the order they were submitted once the WS
627
+ * reconnects and identifies. If the queue exceeds `maxItems` the oldest
628
+ * entry is rejected with `OFFLINE_QUEUE_OVERFLOW`.
629
+ *
630
+ * When a {@link PersistenceAdapter} is supplied, enqueued mutations are mirrored
631
+ * to durable storage so they survive a reload — {@link OfflineQueue.hydrate} restores them on
632
+ * the next startup and the client replays them on reconnect. Durable removal is
633
+ * the caller's responsibility *after* a successful replay (see `LunoraClient`);
634
+ * the queue only persists on enqueue and un-persists on overflow.
635
+ */
230
636
  declare class OfflineQueue {
231
637
  /** Opt-in to queueing mutations before the targeted shard's first connect. */
232
638
  readonly queueBeforeFirstConnect: boolean;
233
639
  private readonly maxItems;
234
640
  private readonly onPersistenceError;
235
641
  private readonly persistence;
642
+ private readonly onEvict;
643
+ private readonly onSizeChange;
644
+ /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
645
+ private readonly version;
236
646
  private readonly items;
237
- constructor(options?: OfflineQueueOptions, persistence?: PersistenceAdapter);
647
+ constructor(options?: OfflineQueueOptions, deps?: OfflineQueueDeps);
238
648
  get size(): number;
239
649
  enqueue<T>(entry: QueuedMutation<T>): void;
240
650
  /**
241
- * Restore mutations persisted in a prior session and re-queue them in FIFO
242
- * order. Restored entries already live in durable storage, so they are not
243
- * re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
244
- * gone after a reload). No-op when no persistence adapter is configured.
245
- * Returns the distinct shard keys of the restored writes so the caller can
246
- * open their sockets to trigger a flush.
247
- */
651
+ * Restore mutations persisted in a prior session and re-queue them in FIFO
652
+ * order. Restored entries already live in durable storage, so they are not
653
+ * re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
654
+ * gone after a reload). No-op when no persistence adapter is configured.
655
+ * Returns the distinct shard keys of the restored writes so the caller can
656
+ * open their sockets to trigger a flush.
657
+ *
658
+ * `hydrate()` runs post-construction (the caller awaits an async durable-store
659
+ * load), so a mutation issued while offline during that boot window is
660
+ * enqueued into `items` *before* this method's `await` resolves. Restored
661
+ * records are therefore `unshift`-ed ahead of whatever is already queued
662
+ * rather than `push`-ed to the end: the durable store's persist order is
663
+ * authoritative (a prior-session write is always older than anything from
664
+ * this session), so replaying a same-session boot-time write before an
665
+ * older restored write on the same document would let last-writer-wins
666
+ * silently clobber the newer data with the stale one.
667
+ */
248
668
  hydrate(): Promise<(string | undefined)[]>;
249
669
  /**
250
- * Remove and return queued mutations. With no `predicate`, drains the whole
251
- * queue. With one, drains only matching entries (preserving FIFO order) and
252
- * leaves the rest queued — used to flush a single shard's writes when its
253
- * socket reconnects while other shards are still down.
254
- */
670
+ * Remove and return queued mutations. With no `predicate`, drains the whole
671
+ * queue. With one, drains only matching entries (preserving FIFO order) and
672
+ * leaves the rest queued — used to flush a single shard's writes when its
673
+ * socket reconnects while other shards are still down.
674
+ */
255
675
  drain(predicate?: (item: QueuedMutation) => boolean): QueuedMutation[];
256
676
  /**
257
- * Return previously-drained mutations to the front of the queue, preserving
258
- * their FIFO order, without re-persisting them — they were never unpersisted,
259
- * so durable storage still holds them. Used when a flush aborts on a transient
260
- * transport failure: the unreplayed writes stay queued for the next reconnect.
261
- */
677
+ * Return previously-drained mutations to the front of the queue, preserving
678
+ * their FIFO order, without re-persisting them — they were never unpersisted,
679
+ * so durable storage still holds them. Used when a flush aborts on a transient
680
+ * transport failure: the unreplayed writes stay queued for the next reconnect.
681
+ */
262
682
  requeue(items: QueuedMutation[]): void;
683
+ /**
684
+ * Remove mutations whose precondition evaluates to `false` (stale/dirty
685
+ * writes that should not replay) and reject each with an
686
+ * `OFFLINE_PRECONDITION_FAILED` error. The valid (admitted) mutations stay
687
+ * queued in FIFO order. Returns the drained stale entries.
688
+ *
689
+ * Called during reconnect before the flush cycle to weed out writes whose
690
+ * assumptions no longer hold (e.g. a document was deleted by another client).
691
+ */
692
+ drainConflict(): QueuedMutation[];
263
693
  clear(): void;
694
+ /**
695
+ * Evict entries from the FRONT of `items` (the oldest — FIFO order) until
696
+ * the queue is at or under `maxItems`, rejecting each with
697
+ * `OFFLINE_QUEUE_OVERFLOW`, un-persisting it, and firing `onEvict`. Shared
698
+ * by `enqueue` (a live write pushes past capacity) and `hydrate` (a durable
699
+ * store restored more than `maxItems` records — CLIENT-03) so an overflow
700
+ * always drops the same way regardless of which caller triggered it.
701
+ */
702
+ private evictOverflow;
703
+ /** Notify the size observer (the client's pending-sync count) after any change. */
704
+ private notifySize;
264
705
  }
265
706
  /**
266
- * In-memory {@link PersistenceAdapter}. Doesn't survive a reload — it exists so
267
- * the persistence wiring can be exercised without IndexedDB (tests, SSR, or as
268
- * a deliberate "no durable store" choice that still satisfies the interface).
269
- * Preserves enqueue order; `clone` keeps callers from mutating stored args.
270
- */
707
+ * In-memory {@link PersistenceAdapter}. Doesn't survive a reload — it exists so
708
+ * the persistence wiring can be exercised without IndexedDB (tests, SSR, or as
709
+ * a deliberate "no durable store" choice that still satisfies the interface).
710
+ * Preserves enqueue order; `clone` keeps callers from mutating stored args.
711
+ */
271
712
  declare const createInMemoryPersistence: () => PersistenceAdapter;
272
713
  interface IndexedDbPersistenceOptions {
273
- /** Database name; defaults to `"lunora"`. */
714
+ /** Database name; defaults to `"lunora-outbox"` (its own DB, separate from the read cache). */
274
715
  databaseName?: string;
275
716
  /** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
276
717
  indexedDB?: IDBFactory;
@@ -278,62 +719,62 @@ interface IndexedDbPersistenceOptions {
278
719
  storeName?: string;
279
720
  }
280
721
  /**
281
- * IndexedDB-backed {@link PersistenceAdapter}. Each mutation is stored under an
282
- * autoincrementing key (so `load()` returns them in enqueue order regardless of
283
- * the string ids) with a unique secondary index on `id` for `remove()`.
284
- *
285
- * The store handle is opened lazily and the open promise is cached, so repeated
286
- * ops reuse one connection. Throws eagerly if no `IDBFactory` is available —
287
- * callers in non-browser environments should use {@link createInMemoryPersistence}.
288
- */
722
+ * IndexedDB-backed {@link PersistenceAdapter}. Each mutation is stored under an
723
+ * autoincrementing key (so `load()` returns them in enqueue order regardless of
724
+ * the string ids) with a unique secondary index on `id` for `remove()`.
725
+ *
726
+ * The store handle is opened lazily and the open promise is cached, so repeated
727
+ * ops reuse one connection. Throws eagerly if no `IDBFactory` is available —
728
+ * callers in non-browser environments should use {@link createInMemoryPersistence}.
729
+ */
289
730
  declare const createIndexedDbPersistence: (options?: IndexedDbPersistenceOptions) => PersistenceAdapter;
290
731
  /**
291
- * Compose the read-cache key for a subscription. Mirrors how
292
- * `SubscriptionRegistry` keys live subscriptions so a hydrated value lines up
293
- * with the subscription that will consume it. `shardKey` defaults to `""` (the
294
- * root shard) exactly as the registry does.
295
- */
732
+ * Compose the read-cache key for a subscription. Mirrors how
733
+ * `SubscriptionRegistry` keys live subscriptions so a hydrated value lines up
734
+ * with the subscription that will consume it. `shardKey` defaults to `""` (the
735
+ * root shard) exactly as the registry does.
736
+ */
296
737
  declare const queryCacheKey: (functionPath: string, argsKey: string, shardKey?: string) => string;
297
738
  /**
298
- * In-memory {@link QueryCacheAdapter}. Doesn't survive a reload — it exists so
299
- * the read-cache wiring can be exercised without IndexedDB (tests, SSR, or as a
300
- * deliberate "no durable store" choice that still satisfies the interface).
301
- * Enforces the same LRU row cap as the IndexedDB adapter; `clone` keeps callers
302
- * from mutating stored values.
303
- */
739
+ * In-memory {@link QueryCacheAdapter}. Doesn't survive a reload — it exists so
740
+ * the read-cache wiring can be exercised without IndexedDB (tests, SSR, or as a
741
+ * deliberate "no durable store" choice that still satisfies the interface).
742
+ * Enforces the same LRU row cap as the IndexedDB adapter; `clone` keeps callers
743
+ * from mutating stored values.
744
+ */
304
745
  declare const createInMemoryQueryCache: (options?: {
305
746
  maxEntries?: number;
306
747
  }) => QueryCacheAdapter;
307
748
  interface IndexedDbQueryCacheOptions {
308
- /** Database name; defaults to `"lunora"` (shared with the offline-mutation store). */
749
+ /** Database name; defaults to `"lunora-query-cache"` (its own DB, separate from the offline outbox). */
309
750
  databaseName?: string;
310
751
  /** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
311
752
  indexedDB?: IDBFactory;
312
- /** LRU row cap; defaults to 500. The oldest rows by `ts` are pruned on `put` once exceeded. */
753
+ /** LRU row cap; defaults to 500. Must be a positive integer. The oldest rows by `ts` are pruned on `put` once exceeded. */
313
754
  maxEntries?: number;
314
755
  /** Object-store name; defaults to `"query-cache"`. */
315
756
  storeName?: string;
316
757
  }
317
758
  /**
318
- * IndexedDB-backed {@link QueryCacheAdapter}. Each query is stored under its
319
- * composite key (`functionPath::argsKey::shardKey`) with a `ts` index driving
320
- * LRU eviction. The store handle is opened lazily and cached, so repeated ops
321
- * reuse one connection.
322
- *
323
- * The store lives in the same `lunora` database as the offline-mutation queue
324
- * (bumped to schema v2). Opening it upgrades a v1 database in place, adding the
325
- * `query-cache` store without touching `offline-mutations`. Throws eagerly if no
326
- * `IDBFactory` is available — callers in non-browser environments should use
327
- * {@link createInMemoryQueryCache}.
328
- */
759
+ * IndexedDB-backed {@link QueryCacheAdapter}. Each query is stored under its
760
+ * composite key (`functionPath::argsKey::shardKey`) with a `ts` index driving
761
+ * LRU eviction. The store handle is opened lazily and cached, so repeated ops
762
+ * reuse one connection.
763
+ *
764
+ * The store lives in its own `lunora-query-cache` database deliberately
765
+ * separate from the offline-mutation outbox's `lunora-outbox` database so the two
766
+ * independently-toggleable adapters never share (and drift on) a schema version.
767
+ * Throws eagerly if no `IDBFactory` is available — callers in non-browser
768
+ * environments should use {@link createInMemoryQueryCache}.
769
+ */
329
770
  declare const createIndexedDbQueryCache: (options?: IndexedDbQueryCacheOptions) => QueryCacheAdapter;
330
771
  /**
331
- * Exponential backoff calculator with optional jitter.
332
- *
333
- * `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
334
- * enabled the returned value is randomized in `[delay/2, delay]` so a fleet
335
- * of clients reconnecting at the same time spread out their retries.
336
- */
772
+ * Exponential backoff calculator with optional jitter.
773
+ *
774
+ * `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
775
+ * enabled the returned value is randomized in `[delay/2, delay]` so a fleet
776
+ * of clients reconnecting at the same time spread out their retries.
777
+ */
337
778
  interface ReconnectCalculator {
338
779
  /** Returns the delay to wait before the next reconnect attempt. */
339
780
  next: () => number;
@@ -341,4 +782,112 @@ interface ReconnectCalculator {
341
782
  reset: () => void;
342
783
  }
343
784
  declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
344
- export { type ArgsOf, type AsyncStorageLike, type AsyncStoragePersistenceOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, type FunctionReference, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, 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, applyDelta, createAsyncStoragePersistence, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutationRunner, createMutatorRunner, createReconnect, isConflictError, isMutationDelta, queryCacheKey };
785
+ /**
786
+ * Capture a snapshot of the current live query value at call time and produce a
787
+ * `() => boolean` precondition that compares it against the value at replay time.
788
+ *
789
+ * When the precondition is checked (on queue drain / reconnect) it re-reads the
790
+ * query's current state via {@link LunoraClient.peekActiveQuerySnapshot}. The
791
+ * comparison only runs when a live subscription backed **both** reads; if either
792
+ * read found no active subscription (e.g. the originating component unmounted
793
+ * before replay), the precondition returns `true` (not stale) because absence of
794
+ * a subscription is not evidence the value changed — the read simply cannot see
795
+ * it. When both reads did have a live subscription and the value differs, the
796
+ * precondition returns `false` and the offline mutation is dropped as stale.
797
+ * @example
798
+ * ```ts
799
+ * client.mutation(api.todos.update, { id, text }, {
800
+ * precondition: createSnapshotPrecondition(client, api.todos.list, { userId }),
801
+ * });
802
+ * ```
803
+ */
804
+ declare const createSnapshotPrecondition: (client: LunoraClient, functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string) => (() => boolean);
805
+ /**
806
+ * Client-side service-worker registration and lifecycle management.
807
+ *
808
+ * Usage:
809
+ * ```ts
810
+ * const sw = new ClientServiceWorker({ swUrl: "/sw.js" });
811
+ * await sw.register();
812
+ *
813
+ * if (sw.active) {
814
+ * sw.postMessage({ type: "sync" });
815
+ * }
816
+ * ```
817
+ */
818
+ type ServiceWorkerStatus = "unsupported" | "unregistered" | "registering" | "active" | "error";
819
+ interface ClientSwOptions {
820
+ /** Called when the status changes. */
821
+ onStatusChange?: (status: ServiceWorkerStatus) => void;
822
+ /** Optional registration scope. Defaults to `/`. */
823
+ scope?: string;
824
+ /** URL of the service worker script (relative to origin). */
825
+ swUrl: string;
826
+ }
827
+ /**
828
+ * Manages service-worker registration and provides a simple API for
829
+ * sending messages and listening for responses.
830
+ */
831
+ declare class ClientServiceWorker {
832
+ #private;
833
+ readonly swUrl: string;
834
+ readonly scope: string;
835
+ constructor(options: ClientSwOptions);
836
+ /** Current registration status. */
837
+ get status(): ServiceWorkerStatus;
838
+ /** The underlying `ServiceWorkerRegistration`, if registered. */
839
+ get registration(): ServiceWorkerRegistration | undefined;
840
+ /** Whether the SW is currently controlling this page. */
841
+ get active(): boolean;
842
+ /**
843
+ * Register the service worker.
844
+ *
845
+ * Returns `false` when the browser does not support service workers.
846
+ */
847
+ register(): Promise<boolean>;
848
+ /**
849
+ * Remove the active service worker registration and clear listeners.
850
+ *
851
+ * Returns `false` when no registration is currently held.
852
+ */
853
+ unregister(): Promise<boolean>;
854
+ /**
855
+ * Send a message to the active service worker.
856
+ */
857
+ postMessage(message: unknown): void;
858
+ /**
859
+ * Register a handler for messages **from** the service worker.
860
+ * @returns Unsubscribe function.
861
+ */
862
+ onMessage(handler: (event: MessageEvent) => void): () => void;
863
+ }
864
+ /**
865
+ * Outbound message from the client to the SW.
866
+ */
867
+ interface ClientToSwMessage {
868
+ /** Opaque correlation ID for request/response patterns. */
869
+ correlationId?: string;
870
+ payload?: unknown;
871
+ type: string;
872
+ }
873
+ /**
874
+ * Inbound message from the SW to the client.
875
+ */
876
+ interface SwToClientMessage {
877
+ /** Echoes the correlation ID from the client request, if any. */
878
+ correlationId?: string;
879
+ payload?: unknown;
880
+ type: string;
881
+ }
882
+ /**
883
+ * Send a typed message to the service worker and optionally await a
884
+ * matching response.
885
+ * @returns A promise that resolves when the SW sends a reply with the
886
+ * same `correlationId` (if `expectResponse` is true).
887
+ */
888
+ declare const sendToSw: (sw: ServiceWorker | null, message: ClientToSwMessage, expectResponse?: boolean) => Promise<unknown>;
889
+ /**
890
+ * Create a reply for a client message (call from inside the SW).
891
+ */
892
+ declare const createReply: (original: ClientToSwMessage, payload?: unknown) => SwToClientMessage;
893
+ export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type BookmarkStorage, ClientServiceWorker, type ClientSwOptions, type ClientToSwMessage, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, 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 ServiceWorkerStatus, type StreamIterable, type SubscriptionError, type SwToClientMessage, TabCoordinator, anyApi, applyDelta, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createReply, createSnapshotPrecondition, httpStream, isMutationDelta, maxSeq, queryCacheKey, reconcileOptimistic, sendToSw };