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

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 (76) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +2 -0
  3. package/dist/auth/index.d.mts +10 -10
  4. package/dist/auth/index.d.ts +10 -10
  5. package/dist/auth/index.mjs +1 -60
  6. package/dist/index.d.mts +521 -169
  7. package/dist/index.d.ts +521 -169
  8. package/dist/index.mjs +1 -14
  9. package/dist/packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs +1 -0
  10. package/dist/packem_shared/ClientServiceWorker-CRQ5yl7-.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs +1 -0
  12. package/dist/packem_shared/LunoraClient-DDEoZdgP.mjs +1 -0
  13. package/dist/packem_shared/OfflineQueue-B603_q8m.mjs +1 -0
  14. package/dist/packem_shared/SKIP-CArzT3Vl.mjs +1 -0
  15. package/dist/packem_shared/SubscriptionRegistry-CdrOD7sZ.mjs +1 -0
  16. package/dist/packem_shared/TabCoordinator-ijLic02x.mjs +1 -0
  17. package/dist/packem_shared/applyDelta-DXqQORbM.mjs +1 -0
  18. package/dist/packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs +1 -0
  19. package/dist/packem_shared/createClientQuery-CrdRoicO.mjs +1 -0
  20. package/dist/packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs +1 -0
  21. package/dist/packem_shared/createInMemoryPersistence-CQYXy8UP.mjs +1 -0
  22. package/dist/packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs +1 -0
  23. package/dist/packem_shared/createLocalStore-B3Tw_Tw1.mjs +1 -0
  24. package/dist/packem_shared/createMutationRunner-lQXH8Amk.mjs +1 -0
  25. package/dist/packem_shared/createMutatorRunner-BVzo0FBZ.mjs +1 -0
  26. package/dist/packem_shared/createReconnect-CFT7YRSR.mjs +1 -0
  27. package/dist/packem_shared/createReply-DF0jRsv-.mjs +1 -0
  28. package/dist/packem_shared/createServerClient-B7KqO8tv.mjs +1 -0
  29. package/dist/packem_shared/createSnapshotPrecondition-DOKRAJ4b.mjs +1 -0
  30. package/dist/packem_shared/deserializePreloaded-CHfOFpka.mjs +1 -0
  31. package/dist/packem_shared/getServerSession-CGjgRBAE.mjs +1 -0
  32. package/dist/packem_shared/httpStream-Cz4_QyjV.mjs +11 -0
  33. package/dist/packem_shared/idb-utility-C-DR8nG1.mjs +1 -0
  34. package/dist/packem_shared/local-store-C53xDvEr.mjs +1 -0
  35. package/dist/packem_shared/lunora-client.d-Bt65hm_E.d.mts +2979 -0
  36. package/dist/packem_shared/lunora-client.d-Bt65hm_E.d.ts +2979 -0
  37. package/dist/packem_shared/offline-queue-D73Dq95V.mjs +1 -0
  38. package/dist/packem_shared/preload.d-BmztUzzG.d.mts +20 -0
  39. package/dist/packem_shared/preload.d-DGGRMWB5.d.ts +20 -0
  40. package/dist/packem_shared/preloadQuery-DjwSjFwt.mjs +1 -0
  41. package/dist/packem_shared/wire-key-D_zOxXK4.mjs +1 -0
  42. package/dist/pagination/index.d.mts +42 -42
  43. package/dist/pagination/index.d.ts +42 -42
  44. package/dist/pagination/index.mjs +1 -61
  45. package/dist/query/index.d.mts +42 -42
  46. package/dist/query/index.d.ts +42 -42
  47. package/dist/query/index.mjs +1 -1
  48. package/dist/ssr/index.d.mts +79 -79
  49. package/dist/ssr/index.d.ts +79 -79
  50. package/dist/ssr/index.mjs +1 -4
  51. package/dist/upload.d.mts +35 -0
  52. package/dist/upload.d.ts +35 -0
  53. package/dist/upload.mjs +1 -0
  54. package/package.json +9 -1
  55. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  56. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  57. package/dist/packem_shared/LunoraClient-UiULzH_1.mjs +0 -2165
  58. package/dist/packem_shared/OfflineQueue-D5p_QgF_.mjs +0 -127
  59. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  60. package/dist/packem_shared/SubscriptionRegistry-B-Qx_Gux.mjs +0 -26
  61. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  62. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  63. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  64. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +0 -105
  65. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +0 -138
  66. package/dist/packem_shared/createLocalStore-DSUfoLqY.mjs +0 -36
  67. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  68. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  69. package/dist/packem_shared/createServerClient-BjZc3gD8.mjs +0 -11
  70. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  71. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  72. package/dist/packem_shared/lunora-client.d-DGvyuJ_p.d.mts +0 -1597
  73. package/dist/packem_shared/lunora-client.d-DGvyuJ_p.d.ts +0 -1597
  74. package/dist/packem_shared/preload.d-BoDmFqSG.d.ts +0 -20
  75. package/dist/packem_shared/preload.d-dSaRMuhL.d.mts +0 -20
  76. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
package/dist/index.d.mts CHANGED
@@ -1,13 +1,13 @@
1
- import { c as PersistenceAdapter, B as BookmarkStorage, F as FunctionReference, A as ArgsOf, M as MutationCallOptions, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, d as ReconnectOptions } from "./packem_shared/lunora-client.d-DGvyuJ_p.mjs";
2
- export { type C as CachedQuery, type e as ClientMessage, type f as ConnectionStatus, D as DEFAULT_MAX_BUFFER, type g as FunctionArgumentDescriptor, type h as FunctionDescriptor, type G as GlobalFacetResult, type i as GlobalFacetValue, type j as GlobalFilterClause, type k as GlobalTableInfo, type l as GlobalTablePage, L as LunoraClient, type m as LunoraClientOptions, type n as OptimisticLocalStore, type o as OptimisticUpdate, type p as PersistedMutation, type P as Preloaded, type q as RpcEnvelope, type r as RpcResponseBody, type s as ScheduleRecord, type t as SchedulerPoolStatus, type u as SchedulerStatus, type v as ServerMessage, type w as ShardTrafficEntry, type x as ShardTrafficResult, type y as StorageListPage, type z as StorageObject, type E as StreamHandle, type H as StreamIterable, type I as SubscriptionCallback, type S as SubscriptionError, type b as SubscriptionErrorCallback, J as SubscriptionRegistry, type K as SubscriptionState, type a as Unsubscribe, type U as User, type W as WorkflowInstanceAction, type N as WorkflowInstanceDetail, type T as WorkflowInstancePage, type V as WorkflowInstanceStatus, type X as WorkflowInstanceSummary, type Y as WorkflowStepDetail, Z as createLocalStore, _ as createStream } from "./packem_shared/lunora-client.d-DGvyuJ_p.mjs";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-dSaRMuhL.mjs";
4
- export type { AuthCapabilities, AuthImpersonation, AuthPage, AuthSession, AuthUser, CronJobInfo, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
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-Bt65hm_E.mjs";
2
+ export { type h as BatchSlot, C as CONFLICT_ERROR_CODE, type i as CachedQuery, type j as ClientDebugShard, type k as ClientDebugSnapshot, type l as ClientDebugSubscription, type m as ClientMessage, type n as ClientQueryRef, type o as ClientShapeSubscribeMessage, type p as ClientShapeUnsubscribeMessage, type q as ConnectionStatus, D as DEFAULT_MAX_BUFFER, type r as FunctionArgumentDescriptor, type s as FunctionDescriptor, type G as GlobalFacetResult, type t as GlobalFacetValue, type u as GlobalFilterClause, type v as GlobalTableInfo, type w as GlobalTablePage, type x as HttpStreamCallArgs, type y as LunoraClientError, type z as LunoraClientOptions, type E as LunoraErrorCode, type I as MutationSettledEvent, type J as OptimisticLocalStore, type K as OptimisticUpdate, type N as OutboxMutation, type T as OutboxSink, type V as PersistedMutation, type P as Preloaded, type W as RowOp, type X as RpcEnvelope, type Y as RpcResponseBody, type Z as ScheduleRecord, type _ as SchedulerPoolStatus, type $ as SchedulerStatus, type a0 as ServerMessage, type a1 as ServerPokeEndMessage, type a2 as ServerPokePartMessage, type a3 as ServerPokeStartMessage, type a4 as ShardTrafficEntry, type a5 as ShardTrafficResult, type a6 as StorageListPage, type a7 as StorageObject, type a8 as StreamHandle, type a9 as SubscriptionCallback, type b as SubscriptionErrorCallback, aa as SubscriptionRegistry, type ab as SubscriptionState, type ac as SyncWatermark, type a as Unsubscribe, type U as User, type ad as WorkflowInstanceAction, type ae as WorkflowInstanceDetail, type af as WorkflowInstancePage, type ag as WorkflowInstanceStatus, type ah as WorkflowInstanceSummary, type ai as WorkflowStepDetail, type aj as WsTokenProvider, ak as createClientQuery, al as createLocalStore, am as createStream, an as getErrorCode, ao as getRetryAfterMs, ap as isConflictError, aq as isForbiddenError, ar as isRateLimitedError, as as isUnauthorizedError } from "./packem_shared/lunora-client.d-Bt65hm_E.mjs";
3
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-BmztUzzG.mjs";
4
+ 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';
5
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
- */
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
+ */
11
11
  interface AsyncStorageLike {
12
12
  getItem: (key: string) => Promise<string | null>;
13
13
  removeItem: (key: string) => Promise<void>;
@@ -20,46 +20,147 @@ interface AsyncStoragePersistenceOptions {
20
20
  storage: AsyncStorageLike;
21
21
  }
22
22
  /**
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
- */
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
+ */
33
33
  declare const createAsyncStoragePersistence: (options: AsyncStoragePersistenceOptions) => PersistenceAdapter;
34
34
  /** Default in-memory bookmark store. Survives the lifetime of the client. */
35
35
  declare const createInMemoryBookmarkStorage: () => BookmarkStorage;
36
+ interface TabCoordinatorOptions {
37
+ /**
38
+ * BroadcastChannel name. Defaults to `"lunora-bridge"`.
39
+ */
40
+ channelName?: string;
41
+ /**
42
+ * Interval (ms) between leader heartbeats. Defaults to 1000.
43
+ */
44
+ heartbeatInterval?: number;
45
+ /**
46
+ * Milliseconds without a heartbeat to consider the leader dead. Must be
47
+ * larger than `heartbeatInterval`. Defaults to 3000.
48
+ */
49
+ leaderTimeout?: number;
50
+ /**
51
+ * Called when this tab becomes the leader (should open WS connections).
52
+ */
53
+ onBecomeLeader?: () => void;
54
+ /**
55
+ * Called when this tab loses leadership (should close WS connections).
56
+ */
57
+ onStopBeingLeader?: () => void;
58
+ /**
59
+ * Called when the leader broadcasts subscription data.
60
+ */
61
+ onSubscriptionData?: (key: string, data: unknown) => void;
62
+ /**
63
+ * Called when the leader broadcasts a subscription error.
64
+ */
65
+ onSubscriptionError?: (key: string, error: SubscriptionError) => void;
66
+ }
67
+ declare class TabCoordinator {
68
+ private readonly bc;
69
+ private readonly tabId;
70
+ private readonly heartbeatInterval;
71
+ private readonly leaderTimeout;
72
+ /** The tab id of the current known leader, or `undefined` if no leader. */
73
+ private knownLeader;
74
+ /** `true` when this tab believes it is the leader. */
75
+ private leader;
76
+ /** `true` once `start()` has been called. */
77
+ private running;
78
+ /** Timestamp of the most recent leader heartbeat. */
79
+ private lastHeartbeat;
80
+ private heartbeatTimer;
81
+ private leaderCheckTimer;
82
+ /** Callbacks set via constructor options. */
83
+ private readonly onBecomeLeader;
84
+ private readonly onStopBeingLeader;
85
+ private readonly onSubscriptionData;
86
+ private readonly onSubscriptionError;
87
+ constructor(options?: TabCoordinatorOptions);
88
+ /**
89
+ * Start the coordinator: attempt to claim leadership and begin the
90
+ * heartbeat/leader-check cycle. Safe to call multiple times.
91
+ */
92
+ start(): void;
93
+ /**
94
+ * Stop the coordinator: yield leadership (if held), close the channel, and
95
+ * clear all timers. Safe to call multiple times.
96
+ */
97
+ stop(): void;
98
+ /** `true` when this tab is the current WebSocket leader. */
99
+ isLeader(): boolean;
100
+ /** The tab id of the current leader, or `undefined` if unknown / no leader. */
101
+ get leaderTabId(): string | undefined;
102
+ /** The id of this tab. */
103
+ get id(): string;
104
+ /** `true` when the coordinator has been started and is not yet stopped. */
105
+ get isRunning(): boolean;
106
+ /**
107
+ * Broadcast subscription data to all follower tabs. Only the leader should
108
+ * call this.
109
+ */
110
+ broadcastSubscriptionData(key: string, data: unknown): void;
111
+ /**
112
+ * Broadcast a subscription error to all follower tabs. Only the leader
113
+ * should call this.
114
+ */
115
+ broadcastSubscriptionError(key: string, error: SubscriptionError): void;
116
+ private broadcast;
117
+ private handleMessage;
118
+ private handleClaimLeadership;
119
+ private handleHeartbeat;
120
+ /**
121
+ * Resolve two leaders existing at once — e.g. this tab was backgrounded
122
+ * and its heartbeat/health timers were throttled while a foreground
123
+ * follower's were not, so the follower's `checkLeaderHealth` timed out
124
+ * the (still-alive) leader and self-promoted. `BroadcastChannel` message
125
+ * delivery isn't subject to the same timer-throttling clamp, so even a
126
+ * backgrounded leader eventually observes the pretender's heartbeat here
127
+ * — resolve the split-brain deterministically with the same
128
+ * lexicographically-smaller-tabId rule used at claim-adoption. If the
129
+ * other tab wins, step down; if we win, reassert immediately so the
130
+ * pretender demotes itself the moment it processes our heartbeat.
131
+ */
132
+ private resolveLeaderVsLeaderTieBreak;
133
+ private becomeLeader;
134
+ private sendHeartbeat;
135
+ private checkLeaderHealth;
136
+ }
36
137
  /**
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
- */
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
+ */
57
158
  /**
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
- */
159
+ * One row change as emitted by `@lunora/do`'s `broadcastDelta`. Mirrors
160
+ * `MutationDelta` in `@lunora/do` structurally so the client carries no
161
+ * dependency on it. `row` is absent on `delete` events (and may be absent on
162
+ * older servers for any op).
163
+ */
63
164
  interface MutationDelta {
64
165
  /** Row id (`_id`) the change applies to. */
65
166
  key: string;
@@ -68,54 +169,80 @@ interface MutationDelta {
68
169
  table: string;
69
170
  }
70
171
  /**
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
- */
172
+ * Structural guard: is `value` a `MutationDelta` the client knows how to merge?
173
+ * We require `op`, `table`, and a string `key` so opaque payloads that merely
174
+ * happen to be objects (e.g. an aggregate `{ count: 1 }` a query returns
175
+ * verbatim) are never mistaken for a row delta and keep replacing the cached
176
+ * value wholesale.
177
+ */
77
178
  declare const isMutationDelta: (value: unknown) => value is MutationDelta;
78
179
  /**
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
- */
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
182
+ * applied cleanly — the caller should then fall back to the existing
183
+ * full-replacement behaviour (or trust the next snapshot to reconcile).
184
+ *
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.
197
+ */
97
198
  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
199
  /**
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
- };
200
+ * Options accepted by {@link httpStream}.
201
+ * @experimental Part of the HTTP-SSE stream surface.
202
+ */
203
+ interface HttpStreamOptions {
204
+ /**
205
+ * Origin (or origin + prefix) the route path is appended to, e.g.
206
+ * `https://my-app.example.com`. Defaults to `""` — a relative URL, which
207
+ * resolves against the page origin in a browser.
208
+ */
209
+ baseUrl?: string;
210
+ /** `fetch` implementation override; defaults to the global `fetch`. */
211
+ fetch?: typeof fetch;
212
+ /** Extra request headers (e.g. `authorization`). `accept: text/event-stream` is always sent. */
213
+ headers?: Record<string, string>;
214
+ /** Caps the in-flight chunk buffer (see `createStream`); exceeding it fails the stream. */
215
+ maxBuffer?: number;
216
+ /** External abort signal — aborting it cancels the fetch (→ the server handler's `signal`). */
217
+ signal?: AbortSignal;
218
+ }
219
+ /**
220
+ * Open a typed HTTP-SSE stream route and iterate its chunks:
221
+ *
222
+ * ```ts
223
+ * const stream = httpStream(httpStreams.http.tokens, { searchParams: { prompt } }, { baseUrl });
224
+ * for await (const token of stream) {
225
+ * render(token); // typed as the route handler's yielded chunk
226
+ * }
227
+ * ```
228
+ *
229
+ * The returned iterable terminates when the server writes `event: complete`;
230
+ * an `event: error` frame (or a transport failure) surfaces as a coded
231
+ * rejection on the next `next()`. `.cancel()` — or aborting `options.signal` —
232
+ * 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
+ */
235
+ declare const httpStream: <Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: HttpStreamOptions) => StreamIterable<HttpStreamChunkOf<Ref>>;
109
236
  /** The single transport method a mutation runner needs — narrowed so adapters can test against a stub. */
110
237
  interface MutationCapableClient<F extends FunctionReference> {
111
238
  mutation: (function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>) => Promise<ReturnOf<F>>;
112
239
  }
113
240
  /**
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
- */
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).
245
+ */
119
246
  interface MutationRunnerSinks<R> {
120
247
  /** Receives the normalized {@link Error} when an invocation rejects. */
121
248
  setError: (error: Error) => void;
@@ -125,27 +252,102 @@ interface MutationRunnerSinks<R> {
125
252
  setResult: (result: R) => void;
126
253
  }
127
254
  /**
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
- */
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`.
264
+ */
138
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>>);
266
+ /**
267
+ * The structural surface of a TanStack `Transaction` a bound custom mutator
268
+ * returns — its `isPersisted.promise` resolves once the write is persisted and
269
+ * rejects on failure. Typed structurally so the framework adapters need not
270
+ * depend on `@tanstack/db` or `@lunora/db` (the handle is created app-side by
271
+ * `bindMutators`).
272
+ */
273
+ interface MutatorTransaction {
274
+ isPersisted: {
275
+ promise: Promise<unknown>;
276
+ };
277
+ }
278
+ /**
279
+ * A bound custom-mutator handle produced by `bindMutators(client, ctx, mutators)`
280
+ * in `@lunora/db`. Calling it applies the optimistic overlay to the local
281
+ * collections and pushes the authoritative server write; it returns the TanStack
282
+ * transaction whose `isPersisted` promise tracks completion.
283
+ */
284
+ type MutatorHandle<TArgs> = (args: TArgs) => MutatorTransaction;
285
+ /**
286
+ * Reactive sinks an adapter binds to its own primitive's setters (a React
287
+ * `useState`, a Solid signal, a Vue ref, a Svelte store). The runner pushes into
288
+ * them; how they store the value is the adapter's concern.
289
+ */
290
+ interface MutatorRunnerSinks {
291
+ /** Receives the normalized {@link Error} when an invocation rejects, or `undefined` on success / reset. */
292
+ setError: (error: Error | undefined) => void;
293
+ /** Receives `true` while at least one invocation is in flight (ref-counted across overlapping calls), else `false`. */
294
+ setPending: (pending: boolean) => void;
295
+ }
296
+ /**
297
+ * Build the framework-neutral `mutate` / `reset` pair of an adapter's
298
+ * custom-mutator hook (`useMutator` / `createMutator` / `mutator`).
299
+ *
300
+ * Owns the orchestration every adapter otherwise copy-pastes: ref-counts
301
+ * overlapping invocations into `setPending` (so it only clears once the last
302
+ * settles), awaits the bound handle's `isPersisted` promise, normalizes a thrown
303
+ * non-`Error`, and routes failure to `setError` (clearing it on success) before
304
+ * re-throwing. Each adapter (`@lunora/react`, `/solid`, `/svelte`, `/vue`) binds
305
+ * the two sinks to its own reactive setters, so this logic lives in exactly one
306
+ * place. The optimistic overlay + server push are owned by the bound handle.
307
+ *
308
+ * `error` tracks the LATEST invocation, not the last to settle: overlapping
309
+ * calls can resolve out of order, so an earlier call that finishes later must
310
+ * not clobber a newer call's outcome. Each invocation takes a monotonic token
311
+ * and only writes `setError` while it is still the most recent one — otherwise
312
+ * `error`/`isError` could surface a stale success or failure (the documented
313
+ * "latest invocation's error" contract every adapter advertises).
314
+ */
315
+ declare const createMutatorRunner: <TArgs>(handle: MutatorHandle<TArgs>, sinks: MutatorRunnerSinks) => {
316
+ mutate: (args: TArgs) => Promise<void>;
317
+ reset: () => void;
318
+ };
139
319
  interface QueuedMutation<T = unknown> {
140
320
  readonly args: Record<string, unknown>;
141
321
  readonly functionPath: string;
142
322
  /** Stable id used to remove the entry from durable storage once replayed; assigned by the queue when absent. */
143
323
  id?: string;
144
324
  /**
145
- * Issuing identity fingerprint carried through to durable storage (`null` =
146
- * signed out). Absent on hydrated legacy records, which replay ambiently.
147
- */
325
+ * Issuing identity fingerprint carried through to durable storage (`null` =
326
+ * signed out). Absent on hydrated legacy records, which replay ambiently.
327
+ */
148
328
  readonly identity?: string | null;
329
+ /**
330
+ * `true` when a live caller is still awaiting this write's `mutation()`
331
+ * Promise; `false`/absent for a write restored from durable storage after a
332
+ * reload (its original awaiter is gone). Carried so terminal-verdict
333
+ * observers can distinguish "the caller already saw this" from "nothing else
334
+ * will report this". Maps to the public `MutationSettledEvent.hadAwaiter`.
335
+ */
336
+ liveAwaiter?: boolean;
337
+ /**
338
+ * Invoked on a successful replay with the server's echoed commit CDC cursor,
339
+ * so a live per-call optimistic layer drops gaplessly once a frame reaches it.
340
+ * Absent on hydrated records (the optimistic write lived in a prior session).
341
+ */
342
+ readonly onCommit?: (commitCursor: number | undefined) => void;
343
+ /**
344
+ * Optional sync predicate evaluated just before replay. When it returns
345
+ * `false` the write is dropped instead of replaying, handling the case
346
+ * where the mutation's preconditions are no longer valid (e.g. the
347
+ * document it referred to was deleted while offline). Absent or `true`
348
+ * means "ok to replay".
349
+ */
350
+ readonly precondition?: () => boolean;
149
351
  /** Rejects if the mutation can no longer be replayed. */
150
352
  readonly reject: (error: unknown) => void;
151
353
  /** Resolves once the mutation has been replayed against the server. */
@@ -153,61 +355,107 @@ interface QueuedMutation<T = unknown> {
153
355
  readonly shardKey?: string;
154
356
  }
155
357
  /**
156
- * Bounded FIFO queue. Mutations issued while the client is offline are
157
- * enqueued and replayed in the order they were submitted once the WS
158
- * reconnects and identifies. If the queue exceeds `maxItems` the oldest
159
- * entry is rejected with `OFFLINE_QUEUE_OVERFLOW`.
160
- *
161
- * When a {@link PersistenceAdapter} is supplied, enqueued mutations are mirrored
162
- * to durable storage so they survive a reload — {@link OfflineQueue.hydrate} restores them on
163
- * the next startup and the client replays them on reconnect. Durable removal is
164
- * the caller's responsibility *after* a successful replay (see `LunoraClient`);
165
- * the queue only persists on enqueue and un-persists on overflow.
166
- */
358
+ * Invoked when the queue itself discards an entry on overflow (capacity
359
+ * eviction), so the client can surface the dropped write on its
360
+ * terminal-verdict observer even when the entry has no live awaiter (a hydrated
361
+ * record). The `error` carries the `OFFLINE_QUEUE_OVERFLOW` code.
362
+ */
363
+ type EvictHandler = (entry: QueuedMutation, error: Error & {
364
+ code?: string;
365
+ }) => void;
366
+ /** Injected dependencies for {@link OfflineQueue} (kept off the user-facing {@link OfflineQueueOptions}). */
367
+ interface OfflineQueueDeps {
368
+ /** Invoked when an entry is discarded on capacity overflow (carries `OFFLINE_QUEUE_OVERFLOW`). */
369
+ onEvict?: EvictHandler;
370
+ /** Invoked with the new depth after any size change (drives the client's pending-sync count). */
371
+ onSizeChange?: (size: number) => void;
372
+ /** Durable store; when present, writes are mirrored and restored across reloads. */
373
+ persistence?: PersistenceAdapter;
374
+ /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
375
+ version?: string;
376
+ }
377
+ /**
378
+ * Bounded FIFO queue. Mutations issued while the client is offline are
379
+ * enqueued and replayed in the order they were submitted once the WS
380
+ * reconnects and identifies. If the queue exceeds `maxItems` the oldest
381
+ * entry is rejected with `OFFLINE_QUEUE_OVERFLOW`.
382
+ *
383
+ * When a {@link PersistenceAdapter} is supplied, enqueued mutations are mirrored
384
+ * to durable storage so they survive a reload — {@link OfflineQueue.hydrate} restores them on
385
+ * the next startup and the client replays them on reconnect. Durable removal is
386
+ * the caller's responsibility *after* a successful replay (see `LunoraClient`);
387
+ * the queue only persists on enqueue and un-persists on overflow.
388
+ */
167
389
  declare class OfflineQueue {
168
390
  /** Opt-in to queueing mutations before the targeted shard's first connect. */
169
391
  readonly queueBeforeFirstConnect: boolean;
170
392
  private readonly maxItems;
171
393
  private readonly onPersistenceError;
172
394
  private readonly persistence;
395
+ private readonly onEvict;
396
+ private readonly onSizeChange;
397
+ /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
398
+ private readonly version;
173
399
  private readonly items;
174
- constructor(options?: OfflineQueueOptions, persistence?: PersistenceAdapter);
400
+ constructor(options?: OfflineQueueOptions, deps?: OfflineQueueDeps);
175
401
  get size(): number;
176
402
  enqueue<T>(entry: QueuedMutation<T>): void;
177
403
  /**
178
- * Restore mutations persisted in a prior session and re-queue them in FIFO
179
- * order. Restored entries already live in durable storage, so they are not
180
- * re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
181
- * gone after a reload). No-op when no persistence adapter is configured.
182
- * Returns the distinct shard keys of the restored writes so the caller can
183
- * open their sockets to trigger a flush.
184
- */
404
+ * Restore mutations persisted in a prior session and re-queue them in FIFO
405
+ * order. Restored entries already live in durable storage, so they are not
406
+ * re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
407
+ * gone after a reload). No-op when no persistence adapter is configured.
408
+ * Returns the distinct shard keys of the restored writes so the caller can
409
+ * open their sockets to trigger a flush.
410
+ *
411
+ * `hydrate()` runs post-construction (the caller awaits an async durable-store
412
+ * load), so a mutation issued while offline during that boot window is
413
+ * enqueued into `items` *before* this method's `await` resolves. Restored
414
+ * records are therefore `unshift`-ed ahead of whatever is already queued
415
+ * rather than `push`-ed to the end: the durable store's persist order is
416
+ * authoritative (a prior-session write is always older than anything from
417
+ * this session), so replaying a same-session boot-time write before an
418
+ * older restored write on the same document would let last-writer-wins
419
+ * silently clobber the newer data with the stale one.
420
+ */
185
421
  hydrate(): Promise<(string | undefined)[]>;
186
422
  /**
187
- * Remove and return queued mutations. With no `predicate`, drains the whole
188
- * queue. With one, drains only matching entries (preserving FIFO order) and
189
- * leaves the rest queued — used to flush a single shard's writes when its
190
- * socket reconnects while other shards are still down.
191
- */
423
+ * Remove and return queued mutations. With no `predicate`, drains the whole
424
+ * queue. With one, drains only matching entries (preserving FIFO order) and
425
+ * leaves the rest queued — used to flush a single shard's writes when its
426
+ * socket reconnects while other shards are still down.
427
+ */
192
428
  drain(predicate?: (item: QueuedMutation) => boolean): QueuedMutation[];
193
429
  /**
194
- * Return previously-drained mutations to the front of the queue, preserving
195
- * their FIFO order, without re-persisting them — they were never unpersisted,
196
- * so durable storage still holds them. Used when a flush aborts on a transient
197
- * transport failure: the unreplayed writes stay queued for the next reconnect.
198
- */
430
+ * Return previously-drained mutations to the front of the queue, preserving
431
+ * their FIFO order, without re-persisting them — they were never unpersisted,
432
+ * so durable storage still holds them. Used when a flush aborts on a transient
433
+ * transport failure: the unreplayed writes stay queued for the next reconnect.
434
+ */
199
435
  requeue(items: QueuedMutation[]): void;
436
+ /**
437
+ * Remove mutations whose precondition evaluates to `false` (stale/dirty
438
+ * writes that should not replay) and reject each with an
439
+ * `OFFLINE_PRECONDITION_FAILED` error. The valid (admitted) mutations stay
440
+ * queued in FIFO order. Returns the drained stale entries.
441
+ *
442
+ * Called during reconnect before the flush cycle to weed out writes whose
443
+ * assumptions no longer hold (e.g. a document was deleted by another client).
444
+ */
445
+ drainConflict(): QueuedMutation[];
200
446
  clear(): void;
447
+ /** Notify the size observer (the client's pending-sync count) after any change. */
448
+ private notifySize;
201
449
  }
202
450
  /**
203
- * In-memory {@link PersistenceAdapter}. Doesn't survive a reload — it exists so
204
- * the persistence wiring can be exercised without IndexedDB (tests, SSR, or as
205
- * a deliberate "no durable store" choice that still satisfies the interface).
206
- * Preserves enqueue order; `clone` keeps callers from mutating stored args.
207
- */
451
+ * In-memory {@link PersistenceAdapter}. Doesn't survive a reload — it exists so
452
+ * the persistence wiring can be exercised without IndexedDB (tests, SSR, or as
453
+ * a deliberate "no durable store" choice that still satisfies the interface).
454
+ * Preserves enqueue order; `clone` keeps callers from mutating stored args.
455
+ */
208
456
  declare const createInMemoryPersistence: () => PersistenceAdapter;
209
457
  interface IndexedDbPersistenceOptions {
210
- /** Database name; defaults to `"lunora"`. */
458
+ /** Database name; defaults to `"lunora-outbox"` (its own DB, separate from the read cache). */
211
459
  databaseName?: string;
212
460
  /** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
213
461
  indexedDB?: IDBFactory;
@@ -215,34 +463,34 @@ interface IndexedDbPersistenceOptions {
215
463
  storeName?: string;
216
464
  }
217
465
  /**
218
- * IndexedDB-backed {@link PersistenceAdapter}. Each mutation is stored under an
219
- * autoincrementing key (so `load()` returns them in enqueue order regardless of
220
- * the string ids) with a unique secondary index on `id` for `remove()`.
221
- *
222
- * The store handle is opened lazily and the open promise is cached, so repeated
223
- * ops reuse one connection. Throws eagerly if no `IDBFactory` is available —
224
- * callers in non-browser environments should use {@link createInMemoryPersistence}.
225
- */
466
+ * IndexedDB-backed {@link PersistenceAdapter}. Each mutation is stored under an
467
+ * autoincrementing key (so `load()` returns them in enqueue order regardless of
468
+ * the string ids) with a unique secondary index on `id` for `remove()`.
469
+ *
470
+ * The store handle is opened lazily and the open promise is cached, so repeated
471
+ * ops reuse one connection. Throws eagerly if no `IDBFactory` is available —
472
+ * callers in non-browser environments should use {@link createInMemoryPersistence}.
473
+ */
226
474
  declare const createIndexedDbPersistence: (options?: IndexedDbPersistenceOptions) => PersistenceAdapter;
227
475
  /**
228
- * Compose the read-cache key for a subscription. Mirrors how
229
- * `SubscriptionRegistry` keys live subscriptions so a hydrated value lines up
230
- * with the subscription that will consume it. `shardKey` defaults to `""` (the
231
- * root shard) exactly as the registry does.
232
- */
476
+ * Compose the read-cache key for a subscription. Mirrors how
477
+ * `SubscriptionRegistry` keys live subscriptions so a hydrated value lines up
478
+ * with the subscription that will consume it. `shardKey` defaults to `""` (the
479
+ * root shard) exactly as the registry does.
480
+ */
233
481
  declare const queryCacheKey: (functionPath: string, argsKey: string, shardKey?: string) => string;
234
482
  /**
235
- * In-memory {@link QueryCacheAdapter}. Doesn't survive a reload — it exists so
236
- * the read-cache wiring can be exercised without IndexedDB (tests, SSR, or as a
237
- * deliberate "no durable store" choice that still satisfies the interface).
238
- * Enforces the same LRU row cap as the IndexedDB adapter; `clone` keeps callers
239
- * from mutating stored values.
240
- */
483
+ * In-memory {@link QueryCacheAdapter}. Doesn't survive a reload — it exists so
484
+ * the read-cache wiring can be exercised without IndexedDB (tests, SSR, or as a
485
+ * deliberate "no durable store" choice that still satisfies the interface).
486
+ * Enforces the same LRU row cap as the IndexedDB adapter; `clone` keeps callers
487
+ * from mutating stored values.
488
+ */
241
489
  declare const createInMemoryQueryCache: (options?: {
242
490
  maxEntries?: number;
243
491
  }) => QueryCacheAdapter;
244
492
  interface IndexedDbQueryCacheOptions {
245
- /** Database name; defaults to `"lunora"` (shared with the offline-mutation store). */
493
+ /** Database name; defaults to `"lunora-query-cache"` (its own DB, separate from the offline outbox). */
246
494
  databaseName?: string;
247
495
  /** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
248
496
  indexedDB?: IDBFactory;
@@ -252,25 +500,25 @@ interface IndexedDbQueryCacheOptions {
252
500
  storeName?: string;
253
501
  }
254
502
  /**
255
- * IndexedDB-backed {@link QueryCacheAdapter}. Each query is stored under its
256
- * composite key (`functionPath::argsKey::shardKey`) with a `ts` index driving
257
- * LRU eviction. The store handle is opened lazily and cached, so repeated ops
258
- * reuse one connection.
259
- *
260
- * The store lives in the same `lunora` database as the offline-mutation queue
261
- * (bumped to schema v2). Opening it upgrades a v1 database in place, adding the
262
- * `query-cache` store without touching `offline-mutations`. Throws eagerly if no
263
- * `IDBFactory` is available — callers in non-browser environments should use
264
- * {@link createInMemoryQueryCache}.
265
- */
503
+ * IndexedDB-backed {@link QueryCacheAdapter}. Each query is stored under its
504
+ * composite key (`functionPath::argsKey::shardKey`) with a `ts` index driving
505
+ * LRU eviction. The store handle is opened lazily and cached, so repeated ops
506
+ * reuse one connection.
507
+ *
508
+ * The store lives in its own `lunora-query-cache` database deliberately
509
+ * separate from the offline-mutation outbox's `lunora-outbox` database so the two
510
+ * independently-toggleable adapters never share (and drift on) a schema version.
511
+ * Throws eagerly if no `IDBFactory` is available — callers in non-browser
512
+ * environments should use {@link createInMemoryQueryCache}.
513
+ */
266
514
  declare const createIndexedDbQueryCache: (options?: IndexedDbQueryCacheOptions) => QueryCacheAdapter;
267
515
  /**
268
- * Exponential backoff calculator with optional jitter.
269
- *
270
- * `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
271
- * enabled the returned value is randomized in `[delay/2, delay]` so a fleet
272
- * of clients reconnecting at the same time spread out their retries.
273
- */
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
+ */
274
522
  interface ReconnectCalculator {
275
523
  /** Returns the delay to wait before the next reconnect attempt. */
276
524
  next: () => number;
@@ -278,4 +526,108 @@ interface ReconnectCalculator {
278
526
  reset: () => void;
279
527
  }
280
528
  declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
281
- export { type ArgsOf, type AsyncStorageLike, type AsyncStoragePersistenceOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, type FunctionReference, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, type MutationCallOptions, type MutationDelta, type MutationRunnerSinks, OfflineQueue, type OfflineQueueOptions, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, type ReconnectCalculator, type ReconnectOptions, type ReturnOf, applyDelta, createAsyncStoragePersistence, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutationRunner, createReconnect, isConflictError, isMutationDelta, queryCacheKey };
529
+ /**
530
+ * Capture a snapshot of the current live query value at call time and produce a
531
+ * `() => boolean` precondition that compares it against the value at replay time.
532
+ *
533
+ * 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.
537
+ * @example
538
+ * ```ts
539
+ * client.mutation(api.todos.update, { id, text }, {
540
+ * precondition: createSnapshotPrecondition(client, api.todos.list, { userId }),
541
+ * });
542
+ * ```
543
+ */
544
+ 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 };