@lunora/client 1.0.0-alpha.53 → 1.0.0-alpha.55
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.
- package/dist/auth/index.d.mts +2 -2
- package/dist/auth/index.d.ts +2 -2
- package/dist/index.d.mts +53 -10
- package/dist/index.d.ts +53 -10
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{LunoraClient-Cgu6xN-X.mjs → LunoraClient-C7T_1hO7.mjs} +1 -1
- package/dist/packem_shared/OfflineQueue-DG51qWl4.mjs +1 -0
- package/dist/packem_shared/createAsyncStoragePersistence-CNdM5o1u.mjs +1 -0
- package/dist/packem_shared/createAsyncStorageQueryCache-Di-S52wy.mjs +1 -0
- package/dist/packem_shared/createInMemoryPersistence-C0qm7c47.mjs +1 -0
- package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
- package/dist/packem_shared/{createServerClient-CNzt_8I6.mjs → createServerClient-MHXUwfgO.mjs} +1 -1
- package/dist/packem_shared/{lunora-client.d-DT9XhMHZ.d.ts → lunora-client.d-BKDWZU-D.d.ts} +1 -1
- package/dist/packem_shared/{lunora-client.d-Dkd6-fpN.d.mts → lunora-client.d-DGVdFJCO.d.mts} +1 -1
- package/dist/packem_shared/offline-queue-CzI2lYQ8.mjs +1 -0
- package/dist/packem_shared/{preload.d-CxLsgsd8.d.mts → preload.d-BJ_toV9J.d.mts} +2 -2
- package/dist/packem_shared/{preload.d-Ch-D-Pfo.d.ts → preload.d-DdzlpRXw.d.ts} +2 -2
- package/dist/packem_shared/single-blob-store-DrhzObic.mjs +1 -0
- package/dist/packem_shared/{types.d-CsuRAQvb.d.mts → types.d-P1jVmZim.d.mts} +6 -4
- package/dist/packem_shared/{types.d-CsuRAQvb.d.ts → types.d-P1jVmZim.d.ts} +6 -4
- package/dist/query/index.d.mts +3 -3
- package/dist/query/index.d.ts +3 -3
- package/dist/service.d.mts +1 -1
- package/dist/service.d.ts +1 -1
- package/dist/ssr/index.d.mts +4 -4
- package/dist/ssr/index.d.ts +4 -4
- package/dist/ssr/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/OfflineQueue-CoRNJFKm.mjs +0 -1
- package/dist/packem_shared/createAsyncStoragePersistence-yBu2KWAp.mjs +0 -1
- package/dist/packem_shared/createInMemoryPersistence-BPdQiujT.mjs +0 -1
- package/dist/packem_shared/createInMemoryQueryCache-HMIq2XtS.mjs +0 -1
- package/dist/packem_shared/offline-queue-BdQFXDz_.mjs +0 -1
package/dist/auth/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
2
|
-
import { U as User } from "../packem_shared/types.d-
|
|
1
|
+
import { L as LunoraClient } from "../packem_shared/lunora-client.d-DGVdFJCO.mjs";
|
|
2
|
+
import { U as User } from "../packem_shared/types.d-P1jVmZim.mjs";
|
|
3
3
|
import '@lunora/runtime';
|
|
4
4
|
interface IdentityStore {
|
|
5
5
|
/** Read the current resolved user, or `null` when signed out / not yet resolved. */
|
package/dist/auth/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
2
|
-
import { U as User } from "../packem_shared/types.d-
|
|
1
|
+
import { L as LunoraClient } from "../packem_shared/lunora-client.d-BKDWZU-D.js";
|
|
2
|
+
import { U as User } from "../packem_shared/types.d-P1jVmZim.js";
|
|
3
3
|
import '@lunora/runtime';
|
|
4
4
|
interface IdentityStore {
|
|
5
5
|
/** Read the current resolved user, or `null` when signed out / not yet resolved. */
|
package/dist/index.d.mts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, O as OfflineQueueOptions,
|
|
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, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus,
|
|
3
|
-
import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, L as LunoraClient } from "./packem_shared/lunora-client.d-
|
|
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-
|
|
5
|
-
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-
|
|
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-P1jVmZim.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-P1jVmZim.mjs";
|
|
3
|
+
import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, L as LunoraClient } from "./packem_shared/lunora-client.d-DGVdFJCO.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-DGVdFJCO.mjs";
|
|
5
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-BJ_toV9J.mjs";
|
|
6
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
7
|
declare const anyApi: Record<string, Record<string, unknown>>;
|
|
8
8
|
/**
|
|
@@ -117,11 +117,46 @@ interface AsyncStoragePersistenceOptions {
|
|
|
117
117
|
* so enqueue order is preserved and `load()` returns freshly-parsed records that
|
|
118
118
|
* callers can't alias.
|
|
119
119
|
*
|
|
120
|
-
* AsyncStorage has no transactions, so every read-modify-write
|
|
121
|
-
*
|
|
122
|
-
* a time and can't clobber each other's writes.
|
|
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
123
|
*/
|
|
124
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;
|
|
125
160
|
/** Default in-memory bookmark store. Survives the lifetime of the client. */
|
|
126
161
|
declare const createInMemoryBookmarkStorage: () => BookmarkStorage;
|
|
127
162
|
/**
|
|
@@ -552,6 +587,14 @@ interface QueuedMutation<T = unknown> {
|
|
|
552
587
|
* eviction), so the client can surface the dropped write on its
|
|
553
588
|
* terminal-verdict observer even when the entry has no live awaiter (a hydrated
|
|
554
589
|
* record). The `error` carries the `OFFLINE_QUEUE_OVERFLOW` code.
|
|
590
|
+
*
|
|
591
|
+
* The `sdks/*` ports deliberately do NOT mirror this shape — they return the
|
|
592
|
+
* discarded entry from `enqueue`/`hydrate`/`drainConflict`/`clear` instead,
|
|
593
|
+
* because they call the queue with a real lock held and settling a write needs
|
|
594
|
+
* that same lock, which self-deadlocks a non-reentrant one. Keep the callback
|
|
595
|
+
* here: this client is single-threaded, so the hazard does not exist, and an
|
|
596
|
+
* observer the queue fires itself is what covers the case a return value's
|
|
597
|
+
* consumer can quietly miss — a hydrated entry whose `reject` is a no-op.
|
|
555
598
|
*/
|
|
556
599
|
type EvictHandler = (entry: QueuedMutation, error: Error & {
|
|
557
600
|
code?: string;
|
|
@@ -696,7 +739,7 @@ interface IndexedDbQueryCacheOptions {
|
|
|
696
739
|
databaseName?: string;
|
|
697
740
|
/** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
|
|
698
741
|
indexedDB?: IDBFactory;
|
|
699
|
-
/** LRU row cap; defaults to 500. The oldest rows by `ts` are pruned on `put` once exceeded. */
|
|
742
|
+
/** LRU row cap; defaults to 500. Must be a positive integer. The oldest rows by `ts` are pruned on `put` once exceeded. */
|
|
700
743
|
maxEntries?: number;
|
|
701
744
|
/** Object-store name; defaults to `"query-cache"`. */
|
|
702
745
|
storeName?: string;
|
|
@@ -836,4 +879,4 @@ declare const sendToSw: (sw: ServiceWorker | null, message: ClientToSwMessage, e
|
|
|
836
879
|
* Create a reply for a client message (call from inside the SW).
|
|
837
880
|
*/
|
|
838
881
|
declare const createReply: (original: ClientToSwMessage, payload?: unknown) => SwToClientMessage;
|
|
839
|
-
export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, 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, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createReply, createSnapshotPrecondition, httpStream, isMutationDelta, maxSeq, queryCacheKey, reconcileOptimistic, sendToSw };
|
|
882
|
+
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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { o as PersistenceAdapter, B as BookmarkStorage, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf, O as OfflineQueueOptions,
|
|
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, a as Unsubscribe, U as User, g as WorkflowInstanceAction, f as WorkflowInstanceDetail, e as WorkflowInstancePage, d as WorkflowInstanceStatus,
|
|
3
|
-
import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, L as LunoraClient } from "./packem_shared/lunora-client.d-
|
|
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-
|
|
5
|
-
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-
|
|
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-P1jVmZim.js";
|
|
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-P1jVmZim.js";
|
|
3
|
+
import { C as ConnectionStatus, S as SubscriptionError, b as StreamIterable, L as LunoraClient } from "./packem_shared/lunora-client.d-BKDWZU-D.js";
|
|
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-BKDWZU-D.js";
|
|
5
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-DdzlpRXw.js";
|
|
6
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
7
|
declare const anyApi: Record<string, Record<string, unknown>>;
|
|
8
8
|
/**
|
|
@@ -117,11 +117,46 @@ interface AsyncStoragePersistenceOptions {
|
|
|
117
117
|
* so enqueue order is preserved and `load()` returns freshly-parsed records that
|
|
118
118
|
* callers can't alias.
|
|
119
119
|
*
|
|
120
|
-
* AsyncStorage has no transactions, so every read-modify-write
|
|
121
|
-
*
|
|
122
|
-
* a time and can't clobber each other's writes.
|
|
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
123
|
*/
|
|
124
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;
|
|
125
160
|
/** Default in-memory bookmark store. Survives the lifetime of the client. */
|
|
126
161
|
declare const createInMemoryBookmarkStorage: () => BookmarkStorage;
|
|
127
162
|
/**
|
|
@@ -552,6 +587,14 @@ interface QueuedMutation<T = unknown> {
|
|
|
552
587
|
* eviction), so the client can surface the dropped write on its
|
|
553
588
|
* terminal-verdict observer even when the entry has no live awaiter (a hydrated
|
|
554
589
|
* record). The `error` carries the `OFFLINE_QUEUE_OVERFLOW` code.
|
|
590
|
+
*
|
|
591
|
+
* The `sdks/*` ports deliberately do NOT mirror this shape — they return the
|
|
592
|
+
* discarded entry from `enqueue`/`hydrate`/`drainConflict`/`clear` instead,
|
|
593
|
+
* because they call the queue with a real lock held and settling a write needs
|
|
594
|
+
* that same lock, which self-deadlocks a non-reentrant one. Keep the callback
|
|
595
|
+
* here: this client is single-threaded, so the hazard does not exist, and an
|
|
596
|
+
* observer the queue fires itself is what covers the case a return value's
|
|
597
|
+
* consumer can quietly miss — a hydrated entry whose `reject` is a no-op.
|
|
555
598
|
*/
|
|
556
599
|
type EvictHandler = (entry: QueuedMutation, error: Error & {
|
|
557
600
|
code?: string;
|
|
@@ -696,7 +739,7 @@ interface IndexedDbQueryCacheOptions {
|
|
|
696
739
|
databaseName?: string;
|
|
697
740
|
/** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
|
|
698
741
|
indexedDB?: IDBFactory;
|
|
699
|
-
/** LRU row cap; defaults to 500. The oldest rows by `ts` are pruned on `put` once exceeded. */
|
|
742
|
+
/** LRU row cap; defaults to 500. Must be a positive integer. The oldest rows by `ts` are pruned on `put` once exceeded. */
|
|
700
743
|
maxEntries?: number;
|
|
701
744
|
/** Object-store name; defaults to `"query-cache"`. */
|
|
702
745
|
storeName?: string;
|
|
@@ -836,4 +879,4 @@ declare const sendToSw: (sw: ServiceWorker | null, message: ClientToSwMessage, e
|
|
|
836
879
|
* Create a reply for a client message (call from inside the SW).
|
|
837
880
|
*/
|
|
838
881
|
declare const createReply: (original: ClientToSwMessage, payload?: unknown) => SwToClientMessage;
|
|
839
|
-
export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, 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, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createReply, createSnapshotPrecondition, httpStream, isMutationDelta, maxSeq, queryCacheKey, reconcileOptimistic, sendToSw };
|
|
882
|
+
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 };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{anyApi as o}from"./packem_shared/anyApi-CBOws2ZA.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as
|
|
1
|
+
import{anyApi as o}from"./packem_shared/anyApi-CBOws2ZA.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as c,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as n}from"./packem_shared/createAsyncStoragePersistence-CNdM5o1u.mjs";import{createAsyncStorageQueryCache as f}from"./packem_shared/createAsyncStorageQueryCache-Di-S52wy.mjs";import{default as s}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as l}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as d}from"./packem_shared/createClientQuery-TKD_52cT.mjs";import{TabCoordinator as C}from"./packem_shared/TabCoordinator-DVKG2RlZ.mjs";import{a as S,i as A}from"./packem_shared/delta-merge-BoVuM-rE.mjs";import{CONFLICT_ERROR_CODE as Q,getErrorCode as _,getRetryAfterMs as h,isConflictError as I,isForbiddenError as M,isRateLimitedError as g,isUnauthorizedError as F}from"./packem_shared/CONFLICT_ERROR_CODE-LjU7z0mB.mjs";import{httpStream as O}from"./packem_shared/httpStream-x6q-x4yK.mjs";import{c as b}from"./packem_shared/local-store-Bb62Gev5.mjs";import{LunoraClient as U}from"./packem_shared/LunoraClient-C7T_1hO7.mjs";import{createMutatorRunner as B}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as N}from"./packem_shared/offline-queue-CzI2lYQ8.mjs";import{createInMemoryPersistence as w,createIndexedDbPersistence as z}from"./packem_shared/createInMemoryPersistence-C0qm7c47.mjs";import{preloadQuery as V,preloadedQueryResult as W}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as j,createIndexedDbQueryCache as G,queryCacheKey as H}from"./packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as Y}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as $}from"./packem_shared/createSnapshotPrecondition-_2YMNXlG.mjs";import{DEFAULT_MAX_BUFFER as re,createStream as oe}from"./packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as ae}from"./packem_shared/SubscriptionRegistry-BF75d3VP.mjs";import{ClientServiceWorker as pe}from"./packem_shared/ClientServiceWorker-DXnBXeWK.mjs";import{createReply as ne,sendToSw as ie}from"./packem_shared/createReply-CwFABEJs.mjs";export{Q as CONFLICT_ERROR_CODE,pe as ClientServiceWorker,re as DEFAULT_MAX_BUFFER,U as LunoraClient,N as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ae as SubscriptionRegistry,C as TabCoordinator,o as anyApi,S as applyDelta,n as createAsyncStoragePersistence,f as createAsyncStorageQueryCache,l as createCallRunner,d as createClientQuery,s as createInMemoryBookmarkStorage,w as createInMemoryPersistence,j as createInMemoryQueryCache,z as createIndexedDbPersistence,G as createIndexedDbQueryCache,b as createLocalStore,B as createMutatorRunner,Y as createReconnect,ne as createReply,$ as createSnapshotPrecondition,oe as createStream,_ as getErrorCode,h as getRetryAfterMs,O as httpStream,I as isConflictError,M as isForbiddenError,A as isMutationDelta,g as isRateLimitedError,F as isUnauthorizedError,c as maxSeq,V as preloadQuery,W as preloadedQueryResult,H as queryCacheKey,p as reconcileOptimistic,ie as sendToSw};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{i as z,a as V,P as j}from"./delta-merge-BoVuM-rE.mjs";import{d as b,e as D}from"./wire-codec-D4iww4NV.mjs";import{s as x}from"./wire-key-HxFZXRbI.mjs";import J from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{ClientQueryStore as Y}from"./createClientQuery-TKD_52cT.mjs";import{TabCoordinator as X}from"./TabCoordinator-DVKG2RlZ.mjs";import{httpStream as Z}from"./httpStream-x6q-x4yK.mjs";import{d as O,n as P,f as R,a as ee,c as te}from"./local-store-Bb62Gev5.mjs";import{O as se,n as N,i as re,r as ne}from"./offline-queue-BdQFXDz_.mjs";import{resolvePersistenceAdapter as ie}from"./createInMemoryPersistence-BPdQiujT.mjs";import{resolveQueryCacheAdapter as ae,queryCacheKey as H}from"./createInMemoryQueryCache-HMIq2XtS.mjs";import{createReconnect as K}from"./createReconnect-CjTmjJDH.mjs";import oe from"./createSnapshotPrecondition-_2YMNXlG.mjs";import{createStream as ce}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as g}from"./SubscriptionRegistry-BF75d3VP.mjs";const F=500,he=(h,e)=>{if(h.size<e)return;const t=h.keys().next().value;t!==void 0&&h.delete(t)};class C{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const de="/_lunora/rpc",B="/_lunora/rpc-batch",ue="/_lunora/ws",L=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,E=h=>{for(let e=h.length-1;e>=0;e-=1)h[e]?.()},le=(h,e)=>{for(const t of e)t.op==="delete"?h.delete(t.key):t.value!==void 0&&h.set(t.key,t.value)},fe="lunora-ping",me=3e4,pe=1e4,ye=250,Se=64,be="/_lunora/admin/shard-traffic",Te="/_lunora/admin/scheduled",ke="/_lunora/admin/scheduled/status",ve="/_lunora/admin/scheduled/ws",ge="/_lunora/admin/scheduled/cancel",Ce="/_lunora/admin/scheduled/dead",_e="/_lunora/admin/scheduled/dead/retry",we="/_lunora/admin/scheduled/dead/cancel",Ee="/_lunora/admin/workflows/instances",Ae="/_lunora/admin/workflows/instance",Ie="/_lunora/admin/workflows/status",M="/_lunora/admin/storage",Oe="/_lunora/admin/storage/url",Pe="/_lunora/admin/storage/buckets",Re="/_lunora/admin/functions",He="/_lunora/admin/cron-jobs",Fe="/_lunora/admin/cron-jobs/run",Le="/_lunora/admin/openapi",Me="/_lunora/admin/openrpc",Ue="/_lunora/admin/global/tables",xe="/_lunora/admin/global/table",Ne="/_lunora/admin/global/facet",Ke="/_lunora/admin/vector/indexes",Be="/_lunora/admin/vector/query",We="/_lunora/admin/logs/archive",qe="/_lunora/admin/kv/namespaces",De="/_lunora/admin/kv/keys",U="/_lunora/admin/kv/value",$e="/_lunora/admin/auth/users",Qe="/_lunora/admin/auth/sessions",Ge="/_lunora/admin/auth/users/create",ze="/_lunora/admin/auth/users/role",Ve="/_lunora/admin/auth/users/ban",je="/_lunora/admin/auth/users/unban",Je="/_lunora/admin/auth/users/password",Ye="/_lunora/admin/auth/users/remove",Xe="/_lunora/admin/auth/users/impersonate",Ze="/_lunora/admin/auth/sessions/revoke",et="/_lunora/admin/auth/sessions/revoke-all",tt="/_lunora/admin/auth/capabilities",st="/_lunora/admin/auth/users/update",rt="/_lunora/admin/auth/accounts",nt="/_lunora/admin/auth/accounts/unlink",it="/_lunora/admin/auth/passkeys",at="/_lunora/admin/auth/passkeys/delete",ot="/_lunora/admin/auth/two-factor/disable",ct="/_lunora/admin/auth/organizations",ht="/_lunora/admin/auth/organizations/members",dt="/_lunora/admin/auth/organizations/invitations",ut="/_lunora/admin/auth/organizations/members/remove",lt="/_lunora/admin/auth/organizations/invitations/cancel",ft="/_lunora/admin/auth/config",mt="/_lunora/admin/auth/organizations/create",pt="/_lunora/admin/auth/organizations/update",yt="/_lunora/admin/auth/organizations/remove",St="/_lunora/admin/auth/organizations/members/add",bt="/_lunora/admin/auth/organizations/members/invite",Tt="/_lunora/admin/auth/organizations/members/role",kt="/_lunora/admin/auth/organizations/teams",vt="/_lunora/admin/auth/organizations/teams/create",gt="/_lunora/admin/auth/organizations/teams/update",Ct="/_lunora/admin/auth/organizations/teams/remove",_t="/_lunora/admin/auth/organizations/teams/members",wt="/_lunora/admin/auth/organizations/teams/members/add",Et="/_lunora/admin/auth/organizations/teams/members/remove",At="/_lunora/admin/auth/organizations/roles",It="/_lunora/admin/auth/organizations/roles/create",Ot="/_lunora/admin/auth/organizations/roles/update",Pt="/_lunora/admin/auth/organizations/roles/remove",Rt="/api/auth",Ht="/get-session",W=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,k=(h,e)=>`${h.endsWith("/")?h.slice(0,-1):h}${e}`,y=(h,e)=>{const t=new URLSearchParams;for(const[r,n]of Object.entries(e))n!==void 0&&n!==""&&t.set(r,String(n));const s=t.toString();return s===""?h:`${h}?${s}`},Ft=[j],m=h=>h??"",$=(h,e)=>{const t=h.error,s=typeof t?.code=="string"?t.code:void 0,r=typeof t?.message=="string"?t.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??e}},Lt=h=>{const{code:e,messageText:t}=$(h,"stream error");return e===void 0?new Error(t):new f(e,t)},q=h=>{const{code:e,messageText:t}=$(h,"subscription error");return{message:t,...e===void 0?{}:{code:e}}},A=(h,e)=>{for(const t of h)try{t(e)}catch{}},Mt=new TextDecoder,Ut=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Mt.decode(h)},S=(h,e)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(e)),!0}catch{return!1}},_=h=>{const e=new Error(h.message??"request failed");return e.code=h.code,h.data!==void 0&&(e.data=b(h.data)),h.hint!==void 0&&(e.hint=h.hint),h.docsUrl!==void 0&&(e.docsUrl=h.docsUrl),e},v=(h,e)=>{try{return D(h)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},xt=(h,e)=>{const t=Array.from({length:e});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;const r=s.body;t[s.id]=r&&"error"in r&&r.error?{error:_(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Nt=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Kt=Promise.resolve();class Q{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new g;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new C;statusListeners=new C;tokenExpiredListeners=new C;mutationSettledListeners=new C;pendingChangeListeners=new C;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??k(W(e.url),ue),this.wsToken=e.wsToken;const t=e.authBasePath??Rt;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??J(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??me,this.connectTimeoutMs=e.connectTimeoutMs??pe,this.defaultConnectionContext=e.connectionContext,this.persistence=ie(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=ae(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Y,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Kt),this.offlineQueue=new se(e.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${N()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint();this.authToken=e,t!==void 0&&(this.authSubject=t);const n=this.identityFingerprint();if(n!==r&&(s?this.rejectQueuedForIdentityChange():(this.restampQueuedIdentity(r,n),this.restampWatermarks(r,n)),this.tabCoordinator)){const i=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),i&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(e)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new f("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const n=s?.shardKey??"",i=this.identityFingerprint();let a;const o=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:d=>{a=d}});if(a!==void 0&&a>(this.clientWatermarks.get(i??"")?.get(n)??0)){let d=this.clientWatermarks.get(i??"");d===void 0&&(d=new Map,this.clientWatermarks.set(i??"",d)),d.set(n,a)}return{applied:a===void 0||a===r,result:o}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const e={};this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{const t=await this.fetchImpl(k(this.url,`${this.authBasePath}${Ht}`),{credentials:"include",headers:e,method:"GET"});return t.ok?(await t.json())?.user??null:null}catch{return null}}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(const t of this.connections.values())if(t.socket)try{t.socket.close()}catch{}}}setConnectionContext(e,t={}){const s=m(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,t={}){const s=m(t.shardKey),r={context:e},n=this.connectionContextHolders.get(s);n?n.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let i=!1;return()=>{if(i)return;i=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(e,t,s={}){const r=m(s.shardKey);let n=this.whisperHandlers.get(r);n||(n=new Map,this.whisperHandlers.set(r,n));let i=n.get(e);const a=i===void 0;if(i||(i=new Set,n.set(e,i)),i.add(t),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&S(o,{topic:e,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),c=o?.get(e);if(!c?.delete(t)||c.size>0)return;o?.delete(e),o?.size===0&&this.whisperHandlers.delete(r);const d=this.getConnection(s.shardKey);d&&S(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,t,s={}){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&S(r,{data:v(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const n of s){const i=this.connections.get(n);e.push({confirmedMutationWatermark:t?.get(n)??0,hasSocket:i?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:i?.wasEverConnected??!1,wsState:i?.wsState??"idle"})}const r=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())r.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,i)=>(n.shardKey??"").localeCompare(i.shardKey??"")),subscriptions:r.toSorted((n,i)=>n.functionPath.localeCompare(i.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return oe(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){if(!this.readyResolved)return;const r=x(t),n=H(e,r,s),i=this.hydratedQueryCache.get(n);if(i!==void 0)return i.identity===this.identityFingerprint()?i.value:void 0}peekActiveQuerySnapshot(e,t,s){const r=g.key(e,t,s),n=this.subscriptions.get(r);return{present:n!==void 0,value:n?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const t=await this.fetchImpl(k(this.url,B),{body:JSON.stringify({calls:e.map((n,i)=>({args:v(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:i,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=t.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await t.json()}catch{throw new f("INTERNAL",`LunoraClient: batch response was not JSON (status ${t.status.toString()})`)}if(!t.ok||r.error&&!r.results)throw r.error?_(r.error):new f("INTERNAL",`LunoraClient: batch request failed (status ${t.status.toString()})`);for(const n of r.results??[]){const i=n.body?.commitCursor;typeof n.id=="number"&&typeof i=="number"&&this.recordShardCursor(e[n.id]?.shardKey,i)}return xt(r.results??[],e.length)}async mutation(e,t,s={}){this.assertOpen();const r=t,n=s.mutationId??N(),{confirms:i,rollbacks:a}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,a,i);const{hasSocket:o,wasEverConnected:c,wsState:d}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:u}=this.offlineQueue,l=c||u,p=this.WebSocketImpl!==void 0&&l;if(d!=="open"&&!o&&p||d==="connecting"&&l)return this.enqueueOfflineMutation(e,r,s.shardKey,n,a,i,s.precondition);try{let w;const G=await this.rpc(e.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:I=>{w=I}});for(const I of i)I(w);return G}catch(w){throw E(a),w}}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey)}async importRows(e,t,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(c=>({rows:c})),i=t.length;let a=0,o=0;for(let c=0;c<i;c+=r){const d=t.slice(c,c+r),u=o;await this.mutation(e,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(u)}`},shardKey:s.shardKey}),o+=1,a+=d.length,s.onProgress?.({done:a,total:i})}return{chunks:o,imported:a}}async shardTraffic(e){this.assertOpen();const t=await this.adminFetch(be,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(Te,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const e=await this.adminFetch(ke,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(ge,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(Ce,"GET")).records??[]}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(_e,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(we,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await this.adminFetch(`${Ee}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Ae}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Ie,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=k(W(this.url),ve),s=K(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,i=!1;const a=()=>{i||(n=setTimeout(d,s.next()))},o=u=>{if(i||this.WebSocketImpl===void 0)return;const l=u===void 0?t:`${t}?token=${encodeURIComponent(u)}`;this.openManagedSocket(r,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:p=>{try{const T=JSON.parse(typeof p.data=="string"?p.data:"");T.type==="jobs"&&Array.isArray(T.records)&&e(T.records)}catch{}},onOpen:()=>{s.reset()}})},c=async u=>{let l;try{l=await u()}catch{a();return}o(l)},d=()=>{if(i||this.WebSocketImpl===void 0)return;const{wsToken:u}=this;if(typeof u=="function"){c(u).catch(()=>{});return}o(u)};return d(),()=>{i=!0,n!==void 0&&clearTimeout(n),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Re,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(He,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();const t=await this.adminFetch(Fe,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Le,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Me,"GET")}async listStorageObjects(e={}){this.assertOpen();const t=y(M,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,t){this.assertOpen();const s=`${M}?key=${encodeURIComponent(e)}${L(t?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted??!0,key:r.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Pe,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();const t=`${M}?key=${encodeURIComponent(e.key)}${L(e.bucket)}`,s=await this.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,t){this.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Oe}?key=${encodeURIComponent(e)}${r}${L(t?.bucket)}`,i=await this.adminFetch(n,"GET");if(typeof i.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return i.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Ue,"GET")}async readGlobalTablePage(e){this.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${xe}?${t.toString()}`,"GET")}async facetGlobalColumn(e){this.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${Ne}?${t.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Ke,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Be,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();const t=await this.adminFetch(We,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(qe,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();const t=y(De,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(t,"GET")}async getKvValue(e){this.assertOpen();const t=y(U,{key:e.key,namespace:e.namespace});return await this.adminFetch(t,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(U,"PUT",e)}async deleteKvKey(e){this.assertOpen();const t=y(U,{key:e.key,namespace:e.namespace});await this.adminFetch(t,"DELETE")}async listAuthUsers(e={}){this.assertOpen();const t=y($e,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return await this.adminFetch(Ge,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(ze,"POST",e)}async banAuthUser(e){return await this.adminFetch(Ve,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(je,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Je,"POST",e)}async removeAuthUser(e){await this.adminFetch(Ye,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Xe,"POST",e)}async revokeAuthSession(e){await this.adminFetch(Ze,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(et,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(tt,"GET")}async updateAuthUser(e){return await this.adminFetch(st,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(y(rt,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(nt,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(y(it,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(at,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(ot,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(y(ct,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){const t=y(ht,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){const t=y(dt,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async removeAuthOrgMember(e){await this.adminFetch(ut,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(lt,"POST",e)}async getAuthConfig(){return await this.adminFetch(ft,"GET")}async createAuthOrganization(e){return await this.adminFetch(mt,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(pt,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(yt,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(St,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(bt,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(Tt,"POST",e)}async listAuthOrgTeams(e){const t=y(kt,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(vt,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(gt,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Ct,"POST",e)}async listAuthOrgTeamMembers(e){const t=y(_t,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(wt,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Et,"POST",e)}async listAuthOrgRoles(e){const t=y(At,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return await this.adminFetch(It,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Ot,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Pt,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=y(Qe,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const n=t??{},i=g.key(e.__lunoraRef,n,r.shardKey);let a=this.subscriptions.get(i);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const u=`sub_${this.nextSubId.toString()}`,l=x(n),p=this.takeHydratedCache(e.__lunoraRef,l,r.shardKey);a={acked:!1,args:n,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:u,lastValue:p?.value,optimisticLayers:[],serverBase:p?.value,serverCursor:p?.serverCursor,shardKey:r.shardKey,...p?.serverEpoch===void 0?{}:{serverEpoch:p.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),r.onCheckpoint&&a.checkpointCallbacks.add(r.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const d=a;return()=>{d.callbacks.delete(o),c&&d.errorCallbacks.delete(c),r.onCheckpoint&&d.checkpointCallbacks.delete(r.onCheckpoint),d.callbacks.size===0&&(this.sendOrQueueUnsubscribe(d.shardKey,d.id,"unsubscribe"),this.subscriptions.remove(d))}}subscribeShape(e,t,s={}){this.assertOpen(),this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:v(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(r,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(n.shardKey,r,"shape_unsubscribe")}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new f("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,i=t??{},{handle:a,iterable:o}=ce({maxBuffer:s.maxBuffer,onCancel:()=>{const l=this.getConnection(n);l&&S(l,{id:r,type:"unsubscribe"}),this.streams.delete(r)}});this.ensureSocket(n);const c=this.getConnection(n),d={id:r,query:{args:v(i,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"};if(this.streams.set(r,{durable:s.durable===!0,handle:a,lastSeq:0,message:d,shardKey:n}),!(c?.wsState==="open"&&S(c,d))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=Se;){const p=c.pendingStreams.shift()?.id,T=p?this.streams.get(p):void 0;T&&(T.handle.fail(new f("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(p))}c.pendingStreams.push(d)}return o}httpStream(e,t,s={}){if(this.closed)throw new f("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Z(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new f("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new f("INTERNAL","LunoraClient is closed")}teardownConnection(e){if(e.reconnectTimer!==void 0&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new X({channelName:e,onBecomeLeader:()=>{for(const t of this.subscriptions.all())this.ensureSocket(t.shardKey),this.sendSubscribeIfOpen(t);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[t,s]of this.connections)this.teardownConnection(s),this.connections.delete(t);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(t,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=t==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=t,t==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(t,s,r,n,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;const a=this.subscriptions.get(t);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,n!==void 0&&(a.serverEpoch=n),O(a,r)),P(a,R(s,a.optimisticLayers)))},onSubscriptionError:(t,s)=>{const r=this.subscriptions.get(t);r&&A(r.errorCallbacks,s)},onSubscriptionSettled:(t,s,r,n,i,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(t);if(o){this.ackAndAdvanceCursor(o,s,r),n!==void 0&&i===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,n));for(const c of o.checkpointCallbacks)c({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async enqueueOfflineMutation(e,t,s,r,n,i,a){const o=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const c=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(d){throw E(n),d instanceof Error?d:new Error(String(d))}for(const d of i)d(void 0);return}return new Promise((c,d)=>{const u={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const p of i)p(l)},reject:l=>{this.queuedIdentities.delete(r),E(n),d(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(u),this.queuedOfflineShardKeys.add(s),u.id!==void 0&&this.queuedIdentities.set(u.id,o)})}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load();for(const{key:t,...s}of e){if(re(this.persistenceVersion,s.version)){this.queryCache.remove(t).catch(()=>{});continue}this.hydratedQueryCache.set(t,s)}}catch{}}takeHydratedCache(e,t,s){const r=H(e,t,s),n=this.hydratedQueryCache.get(r);if(n!==void 0)return this.hydratedQueryCache.delete(r),n.identity===this.identityFingerprint()?n:void 0}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=H(e.fn.__lunoraRef,e.argsKey,e.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:e.serverCursor,ts:Date.now(),value:t,...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},ye)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(([s,r])=>e.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,r){const n=[],i=[];if(!r)return{confirms:n,rollbacks:i};const a=g.key(e,t,s),o=this.subscriptions.get(a);if(o){const c=ee(o,r);c&&(n.push(c.confirm),i.push(c.rollback))}return{confirms:n,rollbacks:i}}applyOptimisticUpdate(e,t,s,r,n){const{confirms:i,rollbacks:a,store:o}=te(this.subscriptions,s);try{e(o,t)}catch{E(a);return}r.push(...a),n.push(...i)}getConnection(e){return this.connections.get(m(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!S(r,{id:t,type:s})&&r.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}const t=this.getConnection(e);return{hasSocket:t?.socket!==void 0,wasEverConnected:t?.wasEverConnected??!1,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=m(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:K(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(t));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){const n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,t,s,r={}){if(!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");const n=this.rpcRequestHeaders(r,s),i=await this.fetchImpl(k(this.url,de),{body:JSON.stringify({args:v(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(r.captureBookmark){const o=i.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await i.json()}catch{const o=i.statusText?` ${i.statusText}`:"";throw new f("INTERNAL",`LunoraClient: response was not JSON (status ${i.status.toString()}${o})`)}if("error"in a)throw _(a.error);if(!i.ok){const o=i.statusText?` ${i.statusText}`:"";throw new f("INTERNAL",`LunoraClient: request failed (status ${i.status.toString()}${o})`)}return r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(i,s),this.recordShardCursor(s,a.commitCursor),b(a.result)}async adminFetch(e,t,s,r){if(!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);const i=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:i?(a=s,r!==void 0&&(n["content-type"]=r)):(a=JSON.stringify(s),n["content-type"]="application/json");const o=await this.fetchImpl(k(this.url,e),{body:a,headers:n,method:t});let c;try{c=await o.json()}catch{const d=o.statusText?` ${o.statusText}`:"";throw new f("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${d})`)}if(typeof c=="object"&&c!==null&&"error"in c){const d=c.error,u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const d=o.statusText?` ${o.statusText}`:"";throw new f("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${d})`)}return c}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(m(e.shardKey));S(e,{caps:Ft,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())m(t.shardKey)===m(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let r;try{r=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,r)}openManagedSocket(e,t,s,r){const{WebSocketImpl:n}=this;if(n===void 0)throw new f("INTERNAL","no WebSocket implementation available");const i=new n(t);e.socket=i;const a=()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===i&&(e.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===i){try{i.close()}catch{}o()}},s)),i.addEventListener("open",()=>{e.socket===i&&(e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now(),r.onOpen(),this.startHeartbeat(e,o))}),i.addEventListener("message",c=>{e.socket===i&&(e.lastFrameAt=Date.now(),r.onMessage(c))}),i.addEventListener("close",c=>{e.socket===i&&o(c)}),i.addEventListener("error",()=>{e.socket===i&&o()})}openSocket(e,t,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(e,this.wsUrlFor(t,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:r=>{this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t);for(const n of this.subscriptions.all())m(n.shardKey)===m(t)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:i,type:a}of n)S(e,{id:i,type:a})}if(e.pendingStreams&&e.pendingStreams.length>0){const n=e.pendingStreams;e.pendingStreams=[];for(const i of n)S(e,i)}const r=this.whisperHandlers.get(m(t));if(r)for(const n of r.keys())S(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}})}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey);const t=new Set((e.pendingStreams??[]).map(r=>r.id));for(const[r,n]of this.streams)if(!(m(n.shardKey)!==m(e.shardKey)||t.has(r))){if(n.durable){const i={...n.message,sinceChunk:n.lastSeq};n.message=i,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==r),i];continue}n.handle.fail(new f("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,t){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;const{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}t();return}try{s.send(fe)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){const t=m(e);for(const s of this.subscriptions.all())m(s.shardKey)===t&&(s.acked=!1)}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return;const s=e.fn.__lunoraTable??e.fn.__lunoraRef;S(t,{id:e.id,query:{args:D(e.args),functionPath:e.fn.__lunoraRef,table:s,...e.serverCursor===void 0?{}:{sinceSeq:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&S(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Ut(e);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type){case"ack":{const n=this.subscriptions.getById(r.id);n&&(n.acked=!0);return}case"chunk":{const{data:n,id:i,seq:a}=r,o=this.streams.get(i);o&&typeof a=="number"&&(o.lastSeq=a,o.durable=!0),o?.handle.push(b(n));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"pokeEnd":{this.handlePokeEnd(r);break}case"pokePart":{this.handlePokePart(r);break}case"pokeStart":{this.handlePokeStart(r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,t);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Lt(e)),this.streams.delete(s);return}const n=s===void 0?void 0:this.subscriptions.getById(s);if(n){A(n.errorCallbacks,q(e));return}const i=s===void 0?void 0:this.shapeSubscriptions.get(s);i&&A(i.errorCallbacks,q(e))}handlePokeStart(e){he(this.pokeBuffers,Q.MAX_POKE_BUFFERS),this.pokeBuffers.set(e.pokeId,{baseCheckpoint:e.baseCheckpoint,epoch:e.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(e){const t=this.pokeBuffers.get(e.pokeId);if(!t)return;const s=t.parts.get(e.shapeId)??[];for(const r of e.rowsPatch)s.push(r.value===void 0?r:{...r,value:b(r.value)});t.parts.set(e.shapeId,s),e.lastMutationId!==void 0&&t.lastMutationId.set(e.shapeId,e.lastMutationId)}handlePokeEnd(e){const t=this.pokeBuffers.get(e.pokeId);if(t){this.pokeBuffers.delete(e.pokeId);for(const[s,r]of t.parts){const n=this.shapeSubscriptions.get(s);if(!n)continue;const i=t.epoch!==void 0&&n.serverEpoch!==void 0&&t.epoch!==n.serverEpoch,a=t.baseCheckpoint!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==t.baseCheckpoint;if(i||a){n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,this.emitShapeRows(n),this.sendShapeSubscribeIfOpen(n);continue}le(n.rows,r),e.checkpoint!==void 0&&(n.serverCursor=e.checkpoint),e.epoch!==void 0&&(n.serverEpoch=e.epoch);const o=t.lastMutationId.get(s);o!==void 0&&(n.lastMutationId=o),this.emitShapeRows(n),n.onCheckpoint?.({checkpoint:n.serverCursor,mutationId:n.lastMutationId})}}}emitShapeRows(e){const t=[...e.rows.values()];for(const s of e.callbacks)try{s(t)}catch{}}handleDataMessage(e){const{id:t}=e,s=t?this.subscriptions.getById(t):void 0;if(!s)return;const r=this.resolveDataPayload(e,s);if(s.serverBase=r,e.cursor!==void 0&&(s.serverCursor=e.cursor),e.epoch!==void 0&&(s.serverEpoch=e.epoch),e.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId);for(const n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),O(s,s.serverCursor),P(s,R(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const n=g.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(n,r,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t){this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&(t.lastMutationId=e.lastMutationId);for(const s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=g.key(t.fn.__lunoraRef,t.args,t.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),O(e,e.serverCursor)&&P(e,R(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,t){if("data"in e&&e.data!==void 0)return b(e.data);const s=b(e.delta);if(z(s)&&t.serverBase!==void 0){const r=V(t.serverBase,s);if(r!==void 0)return r}return s}dispatchWhisper(e,t){const s=this.whisperHandlers.get(m(t))?.get(e.topic);if(!s)return;const r=b(e.data);for(const n of s)try{n(r,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.streams.delete(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,A(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{ne(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let r=0;r<e.length;r+=1){const n=e.charCodeAt(r);t^=n,t=Math.imul(t,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}rejectQueuedForIdentityChange(){const e=this.offlineQueue.drain();for(const t of e){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",t.reject(s),this.emitItemSettled(t,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(e,t){for(const[s,r]of this.queuedIdentities)r===e&&this.queuedIdentities.set(s,t)}restampWatermarks(e,t){const s=e??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const n=t??"",i=this.clientWatermarks.get(n);if(i===void 0)this.clientWatermarks.set(n,r);else for(const[a,o]of r)i.set(a,o)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=this.offlineQueue.drainConflict();for(const c of t){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",d)}const s=m(e),r=this.offlineQueue.drain(c=>m(c.shardKey)===s);if(r.length===0)return;const n=this.identityFingerprint(),i=[];for(const c of r)this.passesReplayIdentityGate(c,n)&&i.push(c);if(i.length===0)return;const a=this.encodableOrSettleTerminal(i);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=F){const d=a.slice(c,c+F),u=await this.replayBatched(d);if(o.push(...u.requeue),u.stop){o.push(...a.slice(c+F));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{v(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return t}passesReplayIdentityGate(e,t){const s=e.id===void 0?void 0:this.queuedIdentities.get(e.id),r=s===void 0?e.identity:s;if(r!==void 0&&r!==t&&!this.isSameCredentialUnderTokenHash(r)){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const n=new Error("offline mutation skipped: auth identity changed before replay");return n.code="OFFLINE_IDENTITY_CHANGED",e.reject(n),this.emitItemSettled(e,"rejected",n),!1}return this.queuedIdentities.delete(e.id??""),!0}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e){for(let t=0;t<e.length;t+=1){const s=e[t];if(s)try{let r;const n=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:i=>{r=i}});this.settleReplaySuccess(s,n,r)}catch(r){if(r.code!==void 0){this.settleReplayTerminal(s,r);continue}this.offlineQueue.requeue(e.slice(t));return}}}async replayBatched(e){if(!this.fetchImpl)return{requeue:e,stop:!0};let t;try{t=await this.fetchImpl(k(this.url,B),{body:JSON.stringify({calls:e.map((n,i)=>({args:v(n.args,`args for '${n.functionPath}'`),functionPath:n.functionPath,id:i,clientId:n.clientId??this.clientId,mutationId:n.id,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:e,stop:!0}}const s=t.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await t.json()}catch{return{requeue:e,stop:!0}}if(!r.results){if(r.error){const n=_(r.error);for(const i of e)this.settleReplayTerminal(i,n);return{requeue:[],stop:!1}}return{requeue:e,stop:!0}}return{requeue:this.settleReplayBatchSlots(e,r.results),stop:!1}}settleReplayBatchSlots(e,t){const s=new Map;for(const n of t)typeof n.id=="number"&&n.body!==void 0&&s.set(n.id,n.body);const r=[];for(const[n,i]of e.entries()){const a=s.get(n);a===void 0?r.push(i):"error"in a?Nt.has(a.error.code)?r.push(i):this.settleReplayTerminal(i,_(a.error)):this.settleReplaySuccess(i,b(a.result),a.commitCursor)}return r}}export{Q as LunoraClient};
|
|
1
|
+
import{LunoraError as f}from"@lunora/errors";import{i as z,a as V,P as j}from"./delta-merge-BoVuM-rE.mjs";import{d as b,e as D}from"./wire-codec-D4iww4NV.mjs";import{s as x}from"./wire-key-HxFZXRbI.mjs";import J from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{ClientQueryStore as Y}from"./createClientQuery-TKD_52cT.mjs";import{TabCoordinator as X}from"./TabCoordinator-DVKG2RlZ.mjs";import{httpStream as Z}from"./httpStream-x6q-x4yK.mjs";import{d as O,n as P,f as R,a as ee,c as te}from"./local-store-Bb62Gev5.mjs";import{O as se,n as N,i as re,r as ne}from"./offline-queue-CzI2lYQ8.mjs";import{resolvePersistenceAdapter as ie}from"./createInMemoryPersistence-C0qm7c47.mjs";import{resolveQueryCacheAdapter as ae,queryCacheKey as H}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as K}from"./createReconnect-CjTmjJDH.mjs";import oe from"./createSnapshotPrecondition-_2YMNXlG.mjs";import{createStream as ce}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as g}from"./SubscriptionRegistry-BF75d3VP.mjs";const F=500,he=(h,e)=>{if(h.size<e)return;const t=h.keys().next().value;t!==void 0&&h.delete(t)};class C{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const de="/_lunora/rpc",B="/_lunora/rpc-batch",ue="/_lunora/ws",L=h=>h===void 0||h===""?"":`&bucket=${encodeURIComponent(h)}`,E=h=>{for(let e=h.length-1;e>=0;e-=1)h[e]?.()},le=(h,e)=>{for(const t of e)t.op==="delete"?h.delete(t.key):t.value!==void 0&&h.set(t.key,t.value)},fe="lunora-ping",me=3e4,pe=1e4,ye=250,Se=64,be="/_lunora/admin/shard-traffic",Te="/_lunora/admin/scheduled",ke="/_lunora/admin/scheduled/status",ve="/_lunora/admin/scheduled/ws",ge="/_lunora/admin/scheduled/cancel",Ce="/_lunora/admin/scheduled/dead",_e="/_lunora/admin/scheduled/dead/retry",we="/_lunora/admin/scheduled/dead/cancel",Ee="/_lunora/admin/workflows/instances",Ae="/_lunora/admin/workflows/instance",Ie="/_lunora/admin/workflows/status",M="/_lunora/admin/storage",Oe="/_lunora/admin/storage/url",Pe="/_lunora/admin/storage/buckets",Re="/_lunora/admin/functions",He="/_lunora/admin/cron-jobs",Fe="/_lunora/admin/cron-jobs/run",Le="/_lunora/admin/openapi",Me="/_lunora/admin/openrpc",Ue="/_lunora/admin/global/tables",xe="/_lunora/admin/global/table",Ne="/_lunora/admin/global/facet",Ke="/_lunora/admin/vector/indexes",Be="/_lunora/admin/vector/query",We="/_lunora/admin/logs/archive",qe="/_lunora/admin/kv/namespaces",De="/_lunora/admin/kv/keys",U="/_lunora/admin/kv/value",$e="/_lunora/admin/auth/users",Qe="/_lunora/admin/auth/sessions",Ge="/_lunora/admin/auth/users/create",ze="/_lunora/admin/auth/users/role",Ve="/_lunora/admin/auth/users/ban",je="/_lunora/admin/auth/users/unban",Je="/_lunora/admin/auth/users/password",Ye="/_lunora/admin/auth/users/remove",Xe="/_lunora/admin/auth/users/impersonate",Ze="/_lunora/admin/auth/sessions/revoke",et="/_lunora/admin/auth/sessions/revoke-all",tt="/_lunora/admin/auth/capabilities",st="/_lunora/admin/auth/users/update",rt="/_lunora/admin/auth/accounts",nt="/_lunora/admin/auth/accounts/unlink",it="/_lunora/admin/auth/passkeys",at="/_lunora/admin/auth/passkeys/delete",ot="/_lunora/admin/auth/two-factor/disable",ct="/_lunora/admin/auth/organizations",ht="/_lunora/admin/auth/organizations/members",dt="/_lunora/admin/auth/organizations/invitations",ut="/_lunora/admin/auth/organizations/members/remove",lt="/_lunora/admin/auth/organizations/invitations/cancel",ft="/_lunora/admin/auth/config",mt="/_lunora/admin/auth/organizations/create",pt="/_lunora/admin/auth/organizations/update",yt="/_lunora/admin/auth/organizations/remove",St="/_lunora/admin/auth/organizations/members/add",bt="/_lunora/admin/auth/organizations/members/invite",Tt="/_lunora/admin/auth/organizations/members/role",kt="/_lunora/admin/auth/organizations/teams",vt="/_lunora/admin/auth/organizations/teams/create",gt="/_lunora/admin/auth/organizations/teams/update",Ct="/_lunora/admin/auth/organizations/teams/remove",_t="/_lunora/admin/auth/organizations/teams/members",wt="/_lunora/admin/auth/organizations/teams/members/add",Et="/_lunora/admin/auth/organizations/teams/members/remove",At="/_lunora/admin/auth/organizations/roles",It="/_lunora/admin/auth/organizations/roles/create",Ot="/_lunora/admin/auth/organizations/roles/update",Pt="/_lunora/admin/auth/organizations/roles/remove",Rt="/api/auth",Ht="/get-session",W=h=>h.startsWith("https://")?`wss://${h.slice(8)}`:h.startsWith("http://")?`ws://${h.slice(7)}`:h,k=(h,e)=>`${h.endsWith("/")?h.slice(0,-1):h}${e}`,y=(h,e)=>{const t=new URLSearchParams;for(const[r,n]of Object.entries(e))n!==void 0&&n!==""&&t.set(r,String(n));const s=t.toString();return s===""?h:`${h}?${s}`},Ft=[j],m=h=>h??"",$=(h,e)=>{const t=h.error,s=typeof t?.code=="string"?t.code:void 0,r=typeof t?.message=="string"?t.message:void 0;return{code:s,messageText:(typeof h.message=="string"?h.message:void 0)??r??e}},Lt=h=>{const{code:e,messageText:t}=$(h,"stream error");return e===void 0?new Error(t):new f(e,t)},q=h=>{const{code:e,messageText:t}=$(h,"subscription error");return{message:t,...e===void 0?{}:{code:e}}},A=(h,e)=>{for(const t of h)try{t(e)}catch{}},Mt=new TextDecoder,Ut=h=>{if(typeof h=="string")return h;if(h instanceof ArrayBuffer)return Mt.decode(h)},S=(h,e)=>{if(!h.socket||h.wsState!=="open")return!1;try{return h.socket.send(JSON.stringify(e)),!0}catch{return!1}},_=h=>{const e=new Error(h.message??"request failed");return e.code=h.code,h.data!==void 0&&(e.data=b(h.data)),h.hint!==void 0&&(e.hint=h.hint),h.docsUrl!==void 0&&(e.docsUrl=h.docsUrl),e},v=(h,e)=>{try{return D(h)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},xt=(h,e)=>{const t=Array.from({length:e});for(const s of h){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;const r=s.body;t[s.id]=r&&"error"in r&&r.error?{error:_(r.error),ok:!1}:{ok:!0,value:b(r?.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Nt=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Kt=Promise.resolve();class Q{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new g;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new C;statusListeners=new C;tokenExpiredListeners=new C;mutationSettledListeners=new C;pendingChangeListeners=new C;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??k(W(e.url),ue),this.wsToken=e.wsToken;const t=e.authBasePath??Rt;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??J(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??me,this.connectTimeoutMs=e.connectTimeoutMs??pe,this.defaultConnectionContext=e.connectionContext,this.persistence=ie(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=ae(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Y,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Kt),this.offlineQueue=new se(e.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${N()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint();this.authToken=e,t!==void 0&&(this.authSubject=t);const n=this.identityFingerprint();if(n!==r&&(s?this.rejectQueuedForIdentityChange():(this.restampQueuedIdentity(r,n),this.restampWatermarks(r,n)),this.tabCoordinator)){const i=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),i&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(e)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new f("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const n=s?.shardKey??"",i=this.identityFingerprint();let a;const o=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:d=>{a=d}});if(a!==void 0&&a>(this.clientWatermarks.get(i??"")?.get(n)??0)){let d=this.clientWatermarks.get(i??"");d===void 0&&(d=new Map,this.clientWatermarks.set(i??"",d)),d.set(n,a)}return{applied:a===void 0||a===r,result:o}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;const e={};this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{const t=await this.fetchImpl(k(this.url,`${this.authBasePath}${Ht}`),{credentials:"include",headers:e,method:"GET"});return t.ok?(await t.json())?.user??null:null}catch{return null}}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(const t of this.connections.values())if(t.socket)try{t.socket.close()}catch{}}}setConnectionContext(e,t={}){const s=m(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,t={}){const s=m(t.shardKey),r={context:e},n=this.connectionContextHolders.get(s);n?n.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let i=!1;return()=>{if(i)return;i=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(e,t,s={}){const r=m(s.shardKey);let n=this.whisperHandlers.get(r);n||(n=new Map,this.whisperHandlers.set(r,n));let i=n.get(e);const a=i===void 0;if(i||(i=new Set,n.set(e,i)),i.add(t),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&S(o,{topic:e,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),c=o?.get(e);if(!c?.delete(t)||c.size>0)return;o?.delete(e),o?.size===0&&this.whisperHandlers.delete(r);const d=this.getConnection(s.shardKey);d&&S(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,t,s={}){this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&S(r,{data:v(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const n of s){const i=this.connections.get(n);e.push({confirmedMutationWatermark:t?.get(n)??0,hasSocket:i?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:i?.wasEverConnected??!1,wsState:i?.wsState??"idle"})}const r=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())r.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,i)=>(n.shardKey??"").localeCompare(i.shardKey??"")),subscriptions:r.toSorted((n,i)=>n.functionPath.localeCompare(i.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return oe(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){if(!this.readyResolved)return;const r=x(t),n=H(e,r,s),i=this.hydratedQueryCache.get(n);if(i!==void 0)return i.identity===this.identityFingerprint()?i.value:void 0}peekActiveQuerySnapshot(e,t,s){const r=g.key(e,t,s),n=this.subscriptions.get(r);return{present:n!==void 0,value:n?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const t=await this.fetchImpl(k(this.url,B),{body:JSON.stringify({calls:e.map((n,i)=>({args:v(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:i,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=t.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await t.json()}catch{throw new f("INTERNAL",`LunoraClient: batch response was not JSON (status ${t.status.toString()})`)}if(!t.ok||r.error&&!r.results)throw r.error?_(r.error):new f("INTERNAL",`LunoraClient: batch request failed (status ${t.status.toString()})`);for(const n of r.results??[]){const i=n.body?.commitCursor;typeof n.id=="number"&&typeof i=="number"&&this.recordShardCursor(e[n.id]?.shardKey,i)}return xt(r.results??[],e.length)}async mutation(e,t,s={}){this.assertOpen();const r=t,n=s.mutationId??N(),{confirms:i,rollbacks:a}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,a,i);const{hasSocket:o,wasEverConnected:c,wsState:d}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:u}=this.offlineQueue,l=c||u,p=this.WebSocketImpl!==void 0&&l;if(d!=="open"&&!o&&p||d==="connecting"&&l)return this.enqueueOfflineMutation(e,r,s.shardKey,n,a,i,s.precondition);try{let w;const G=await this.rpc(e.__lunoraRef,r,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:I=>{w=I}});for(const I of i)I(w);return G}catch(w){throw E(a),w}}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey)}async importRows(e,t,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(c=>({rows:c})),i=t.length;let a=0,o=0;for(let c=0;c<i;c+=r){const d=t.slice(c,c+r),u=o;await this.mutation(e,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(u)}`},shardKey:s.shardKey}),o+=1,a+=d.length,s.onProgress?.({done:a,total:i})}return{chunks:o,imported:a}}async shardTraffic(e){this.assertOpen();const t=await this.adminFetch(be,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(Te,"GET")).records??[]}async schedulerStatus(){this.assertOpen();const e=await this.adminFetch(ke,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(ge,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(Ce,"GET")).records??[]}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(_e,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(we,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await this.adminFetch(`${Ee}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Ae}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Ie,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=k(W(this.url),ve),s=K(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,i=!1;const a=()=>{i||(n=setTimeout(d,s.next()))},o=u=>{if(i||this.WebSocketImpl===void 0)return;const l=u===void 0?t:`${t}?token=${encodeURIComponent(u)}`;this.openManagedSocket(r,l,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:p=>{try{const T=JSON.parse(typeof p.data=="string"?p.data:"");T.type==="jobs"&&Array.isArray(T.records)&&e(T.records)}catch{}},onOpen:()=>{s.reset()}})},c=async u=>{let l;try{l=await u()}catch{a();return}o(l)},d=()=>{if(i||this.WebSocketImpl===void 0)return;const{wsToken:u}=this;if(typeof u=="function"){c(u).catch(()=>{});return}o(u)};return d(),()=>{i=!0,n!==void 0&&clearTimeout(n),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Re,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(He,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();const t=await this.adminFetch(Fe,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Le,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Me,"GET")}async listStorageObjects(e={}){this.assertOpen();const t=y(M,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,t){this.assertOpen();const s=`${M}?key=${encodeURIComponent(e)}${L(t?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted??!0,key:r.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Pe,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();const t=`${M}?key=${encodeURIComponent(e.key)}${L(e.bucket)}`,s=await this.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,t){this.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Oe}?key=${encodeURIComponent(e)}${r}${L(t?.bucket)}`,i=await this.adminFetch(n,"GET");if(typeof i.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return i.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Ue,"GET")}async readGlobalTablePage(e){this.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${xe}?${t.toString()}`,"GET")}async facetGlobalColumn(e){this.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${Ne}?${t.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Ke,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Be,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();const t=await this.adminFetch(We,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(qe,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();const t=y(De,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(t,"GET")}async getKvValue(e){this.assertOpen();const t=y(U,{key:e.key,namespace:e.namespace});return await this.adminFetch(t,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(U,"PUT",e)}async deleteKvKey(e){this.assertOpen();const t=y(U,{key:e.key,namespace:e.namespace});await this.adminFetch(t,"DELETE")}async listAuthUsers(e={}){this.assertOpen();const t=y($e,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return await this.adminFetch(Ge,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(ze,"POST",e)}async banAuthUser(e){return await this.adminFetch(Ve,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(je,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(Je,"POST",e)}async removeAuthUser(e){await this.adminFetch(Ye,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Xe,"POST",e)}async revokeAuthSession(e){await this.adminFetch(Ze,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(et,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(tt,"GET")}async updateAuthUser(e){return await this.adminFetch(st,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(y(rt,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(nt,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(y(it,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(at,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(ot,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(y(ct,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){const t=y(ht,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){const t=y(dt,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async removeAuthOrgMember(e){await this.adminFetch(ut,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(lt,"POST",e)}async getAuthConfig(){return await this.adminFetch(ft,"GET")}async createAuthOrganization(e){return await this.adminFetch(mt,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(pt,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(yt,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(St,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(bt,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(Tt,"POST",e)}async listAuthOrgTeams(e){const t=y(kt,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(vt,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(gt,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Ct,"POST",e)}async listAuthOrgTeamMembers(e){const t=y(_t,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(wt,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Et,"POST",e)}async listAuthOrgRoles(e){const t=y(At,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return await this.adminFetch(It,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Ot,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Pt,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=y(Qe,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const n=t??{},i=g.key(e.__lunoraRef,n,r.shardKey);let a=this.subscriptions.get(i);const o=s,c=r.onError;if(!a){this.nextSubId+=1;const u=`sub_${this.nextSubId.toString()}`,l=x(n),p=this.takeHydratedCache(e.__lunoraRef,l,r.shardKey);a={acked:!1,args:n,argsKey:l,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:u,lastValue:p?.value,optimisticLayers:[],serverBase:p?.value,serverCursor:p?.serverCursor,shardKey:r.shardKey,...p?.serverEpoch===void 0?{}:{serverEpoch:p.serverEpoch}},this.subscriptions.add(a)}if(a.callbacks.add(o),c&&a.errorCallbacks.add(c),r.onCheckpoint&&a.checkpointCallbacks.add(r.onCheckpoint),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const d=a;return()=>{d.callbacks.delete(o),c&&d.errorCallbacks.delete(c),r.onCheckpoint&&d.checkpointCallbacks.delete(r.onCheckpoint),d.callbacks.size===0&&(this.sendOrQueueUnsubscribe(d.shardKey,d.id,"unsubscribe"),this.subscriptions.remove(d))}}subscribeShape(e,t,s={}){this.assertOpen(),this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:v(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(r,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(n.shardKey,r,"shape_unsubscribe")}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new f("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,i=t??{},{handle:a,iterable:o}=ce({maxBuffer:s.maxBuffer,onCancel:()=>{const l=this.getConnection(n);l&&S(l,{id:r,type:"unsubscribe"}),this.streams.delete(r)}});this.ensureSocket(n);const c=this.getConnection(n),d={id:r,query:{args:v(i,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"};if(this.streams.set(r,{durable:s.durable===!0,handle:a,lastSeq:0,message:d,shardKey:n}),!(c?.wsState==="open"&&S(c,d))&&c){for(c.pendingStreams=c.pendingStreams??[];c.pendingStreams.length>=Se;){const p=c.pendingStreams.shift()?.id,T=p?this.streams.get(p):void 0;T&&(T.handle.fail(new f("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(p))}c.pendingStreams.push(d)}return o}httpStream(e,t,s={}){if(this.closed)throw new f("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Z(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new f("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new f("INTERNAL","LunoraClient is closed")}teardownConnection(e){if(e.reconnectTimer!==void 0&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new X({channelName:e,onBecomeLeader:()=>{for(const t of this.subscriptions.all())this.ensureSocket(t.shardKey),this.sendSubscribeIfOpen(t);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[t,s]of this.connections)this.teardownConnection(s),this.connections.delete(t);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(t,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=t==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=t,t==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(t,s,r,n,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;const a=this.subscriptions.get(t);a&&(a.serverBase=s,r!==void 0&&(a.serverCursor=r,n!==void 0&&(a.serverEpoch=n),O(a,r)),P(a,R(s,a.optimisticLayers)))},onSubscriptionError:(t,s)=>{const r=this.subscriptions.get(t);r&&A(r.errorCallbacks,s)},onSubscriptionSettled:(t,s,r,n,i,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(t);if(o){this.ackAndAdvanceCursor(o,s,r),n!==void 0&&i===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,n));for(const c of o.checkpointCallbacks)c({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}async enqueueOfflineMutation(e,t,s,r,n,i,a){const o=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;const c=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(c)}`,identity:o,mutationId:c,shardKey:s})}catch(d){throw E(n),d instanceof Error?d:new Error(String(d))}for(const d of i)d(void 0);return}return new Promise((c,d)=>{const u={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,id:r,clientId:this.clientId,identity:o,precondition:a,onCommit:l=>{for(const p of i)p(l)},reject:l=>{this.queuedIdentities.delete(r),E(n),d(l instanceof Error?l:new Error(String(l)))},resolve:c,shardKey:s};this.offlineQueue.enqueue(u),this.queuedOfflineShardKeys.add(s),u.id!==void 0&&this.queuedIdentities.set(u.id,o)})}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load();for(const{key:t,...s}of e){if(re(this.persistenceVersion,s.version)){this.queryCache.remove(t).catch(()=>{});continue}this.hydratedQueryCache.set(t,s)}}catch{}}takeHydratedCache(e,t,s){const r=H(e,t,s),n=this.hydratedQueryCache.get(r);if(n!==void 0)return this.hydratedQueryCache.delete(r),n.identity===this.identityFingerprint()?n:void 0}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=H(e.fn.__lunoraRef,e.argsKey,e.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:e.serverCursor,ts:Date.now(),value:t,...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},ye)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,r])=>e.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,r){const n=[],i=[];if(!r)return{confirms:n,rollbacks:i};const a=g.key(e,t,s),o=this.subscriptions.get(a);if(o){const c=ee(o,r);c&&(n.push(c.confirm),i.push(c.rollback))}return{confirms:n,rollbacks:i}}applyOptimisticUpdate(e,t,s,r,n){const{confirms:i,rollbacks:a,store:o}=te(this.subscriptions,s);try{e(o,t)}catch{E(a);return}r.push(...a),n.push(...i)}getConnection(e){return this.connections.get(m(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!S(r,{id:t,type:s})&&r.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}const t=this.getConnection(e);return{hasSocket:t?.socket!==void 0,wasEverConnected:t?.wasEverConnected??!1,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=m(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:K(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"},r=this.shardCursors.get(this.cursorKeyFor(t));if(r!==void 0&&(s["x-lunora-min-seq"]=r.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){const n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,t,s,r={}){if(!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");const n=this.rpcRequestHeaders(r,s),i=await this.fetchImpl(k(this.url,de),{body:JSON.stringify({args:v(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(r.captureBookmark){const o=i.headers.get("x-d1-bookmark");o&&this.bookmark.set(o)}let a;try{a=await i.json()}catch{const o=i.statusText?` ${i.statusText}`:"";throw new f("INTERNAL",`LunoraClient: response was not JSON (status ${i.status.toString()}${o})`)}if("error"in a)throw _(a.error);if(!i.ok){const o=i.statusText?` ${i.statusText}`:"";throw new f("INTERNAL",`LunoraClient: request failed (status ${i.status.toString()}${o})`)}return r.onMutationAck?.(a.lastMutationId),r.onCommitCursor?.(a.commitCursor),this.learnDefaultShardKey(i,s),this.recordShardCursor(s,a.commitCursor),b(a.result)}async adminFetch(e,t,s,r){if(!this.fetchImpl)throw new f("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);const i=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:i?(a=s,r!==void 0&&(n["content-type"]=r)):(a=JSON.stringify(s),n["content-type"]="application/json");const o=await this.fetchImpl(k(this.url,e),{body:a,headers:n,method:t});let c;try{c=await o.json()}catch{const d=o.statusText?` ${o.statusText}`:"";throw new f("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${d})`)}if(typeof c=="object"&&c!==null&&"error"in c){const d=c.error,u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const d=o.statusText?` ${o.statusText}`:"";throw new f("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${d})`)}return c}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(m(e.shardKey));S(e,{caps:Ft,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())m(t.shardKey)===m(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let r;try{r=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,r)}openManagedSocket(e,t,s,r){const{WebSocketImpl:n}=this;if(n===void 0)throw new f("INTERNAL","no WebSocket implementation available");const i=new n(t);e.socket=i;const a=()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===i&&(e.socket=void 0)},o=c=>{a(),r.onClose(c)};s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===i){try{i.close()}catch{}o()}},s)),i.addEventListener("open",()=>{e.socket===i&&(e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now(),r.onOpen(),this.startHeartbeat(e,o))}),i.addEventListener("message",c=>{e.socket===i&&(e.lastFrameAt=Date.now(),r.onMessage(c))}),i.addEventListener("close",c=>{e.socket===i&&o(c)}),i.addEventListener("error",()=>{e.socket===i&&o()})}openSocket(e,t,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(e,this.wsUrlFor(t,s),this.connectTimeoutMs,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:r=>{this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t);for(const n of this.subscriptions.all())m(n.shardKey)===m(t)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:i,type:a}of n)S(e,{id:i,type:a})}if(e.pendingStreams&&e.pendingStreams.length>0){const n=e.pendingStreams;e.pendingStreams=[];for(const i of n)S(e,i)}const r=this.whisperHandlers.get(m(t));if(r)for(const n of r.keys())S(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}})}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey);const t=new Set((e.pendingStreams??[]).map(r=>r.id));for(const[r,n]of this.streams)if(!(m(n.shardKey)!==m(e.shardKey)||t.has(r))){if(n.durable){const i={...n.message,sinceChunk:n.lastSeq};n.message=i,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==r),i];continue}n.handle.fail(new f("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(r)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,t){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;const{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}t();return}try{s.send(fe)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){const t=m(e);for(const s of this.subscriptions.all())m(s.shardKey)===t&&(s.acked=!1)}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return;const s=e.fn.__lunoraTable??e.fn.__lunoraRef;S(t,{id:e.id,query:{args:D(e.args),functionPath:e.fn.__lunoraRef,table:s,...e.serverCursor===void 0?{}:{sinceSeq:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&S(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Ut(e);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}switch(r.type){case"ack":{const n=this.subscriptions.getById(r.id);n&&(n.acked=!0);return}case"chunk":{const{data:n,id:i,seq:a}=r,o=this.streams.get(i);o&&typeof a=="number"&&(o.lastSeq=a,o.durable=!0),o?.handle.push(b(n));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"pokeEnd":{this.handlePokeEnd(r);break}case"pokePart":{this.handlePokePart(r);break}case"pokeStart":{this.handlePokeStart(r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,t);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Lt(e)),this.streams.delete(s);return}const n=s===void 0?void 0:this.subscriptions.getById(s);if(n){A(n.errorCallbacks,q(e));return}const i=s===void 0?void 0:this.shapeSubscriptions.get(s);i&&A(i.errorCallbacks,q(e))}handlePokeStart(e){he(this.pokeBuffers,Q.MAX_POKE_BUFFERS),this.pokeBuffers.set(e.pokeId,{baseCheckpoint:e.baseCheckpoint,epoch:e.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(e){const t=this.pokeBuffers.get(e.pokeId);if(!t)return;const s=t.parts.get(e.shapeId)??[];for(const r of e.rowsPatch)s.push(r.value===void 0?r:{...r,value:b(r.value)});t.parts.set(e.shapeId,s),e.lastMutationId!==void 0&&t.lastMutationId.set(e.shapeId,e.lastMutationId)}handlePokeEnd(e){const t=this.pokeBuffers.get(e.pokeId);if(t){this.pokeBuffers.delete(e.pokeId);for(const[s,r]of t.parts){const n=this.shapeSubscriptions.get(s);if(!n)continue;const i=t.epoch!==void 0&&n.serverEpoch!==void 0&&t.epoch!==n.serverEpoch,a=t.baseCheckpoint!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==t.baseCheckpoint;if(i||a){n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,this.emitShapeRows(n),this.sendShapeSubscribeIfOpen(n);continue}le(n.rows,r),e.checkpoint!==void 0&&(n.serverCursor=e.checkpoint),e.epoch!==void 0&&(n.serverEpoch=e.epoch);const o=t.lastMutationId.get(s);o!==void 0&&(n.lastMutationId=o),this.emitShapeRows(n),n.onCheckpoint?.({checkpoint:n.serverCursor,mutationId:n.lastMutationId})}}}emitShapeRows(e){const t=[...e.rows.values()];for(const s of e.callbacks)try{s(t)}catch{}}handleDataMessage(e){const{id:t}=e,s=t?this.subscriptions.getById(t):void 0;if(!s)return;const r=this.resolveDataPayload(e,s);if(s.serverBase=r,e.cursor!==void 0&&(s.serverCursor=e.cursor),e.epoch!==void 0&&(s.serverEpoch=e.epoch),e.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId);for(const n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),O(s,s.serverCursor),P(s,R(r,s.optimisticLayers)),this.tabCoordinator?.isLeader()){const n=g.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(n,r,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t){this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&(t.lastMutationId=e.lastMutationId);for(const s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=g.key(t.fn.__lunoraRef,t.args,t.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),O(e,e.serverCursor)&&P(e,R(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,t){if("data"in e&&e.data!==void 0)return b(e.data);const s=b(e.delta);if(z(s)&&t.serverBase!==void 0){const r=V(t.serverBase,s);if(r!==void 0)return r}return s}dispatchWhisper(e,t){const s=this.whisperHandlers.get(m(t))?.get(e.topic);if(!s)return;const r=b(e.data);for(const n of s)try{n(r,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.streams.delete(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,A(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{ne(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let r=0;r<e.length;r+=1){const n=e.charCodeAt(r);t^=n,t=Math.imul(t,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}rejectQueuedForIdentityChange(){const e=this.offlineQueue.drain();for(const t of e){this.queuedIdentities.delete(t.id??""),this.unpersist(t.id);const s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",t.reject(s),this.emitItemSettled(t,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(e,t){for(const[s,r]of this.queuedIdentities)r===e&&this.queuedIdentities.set(s,t)}restampWatermarks(e,t){const s=e??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const n=t??"",i=this.clientWatermarks.get(n);if(i===void 0)this.clientWatermarks.set(n,r);else for(const[a,o]of r)i.set(a,o)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=this.offlineQueue.drainConflict();for(const c of t){this.unpersist(c.id),this.queuedIdentities.delete(c.id??"");const d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(c,"rejected",d)}const s=m(e),r=this.offlineQueue.drain(c=>m(c.shardKey)===s);if(r.length===0)return;const n=this.identityFingerprint(),i=[];for(const c of r)this.passesReplayIdentityGate(c,n)&&i.push(c);if(i.length===0)return;const a=this.encodableOrSettleTerminal(i);if(a.length===0)return;if(a.length===1){await this.replaySequential(a);return}const o=[];for(let c=0;c<a.length;c+=F){const d=a.slice(c,c+F),u=await this.replayBatched(d);if(o.push(...u.requeue),u.stop){o.push(...a.slice(c+F));break}}o.length>0&&this.offlineQueue.requeue(o)}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{v(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return t}passesReplayIdentityGate(e,t){const s=e.id===void 0?void 0:this.queuedIdentities.get(e.id),r=s===void 0?e.identity:s;if(r!==void 0&&r!==t&&!this.isSameCredentialUnderTokenHash(r)){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);const n=new Error("offline mutation skipped: auth identity changed before replay");return n.code="OFFLINE_IDENTITY_CHANGED",e.reject(n),this.emitItemSettled(e,"rejected",n),!1}return this.queuedIdentities.delete(e.id??""),!0}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e){for(let t=0;t<e.length;t+=1){const s=e[t];if(s)try{let r;const n=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:i=>{r=i}});this.settleReplaySuccess(s,n,r)}catch(r){if(r.code!==void 0){this.settleReplayTerminal(s,r);continue}this.offlineQueue.requeue(e.slice(t));return}}}async replayBatched(e){if(!this.fetchImpl)return{requeue:e,stop:!0};let t;try{t=await this.fetchImpl(k(this.url,B),{body:JSON.stringify({calls:e.map((n,i)=>({args:v(n.args,`args for '${n.functionPath}'`),functionPath:n.functionPath,id:i,clientId:n.clientId??this.clientId,mutationId:n.id,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:e,stop:!0}}const s=t.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let r;try{r=await t.json()}catch{return{requeue:e,stop:!0}}if(!r.results){if(r.error){const n=_(r.error);for(const i of e)this.settleReplayTerminal(i,n);return{requeue:[],stop:!1}}return{requeue:e,stop:!0}}return{requeue:this.settleReplayBatchSlots(e,r.results),stop:!1}}settleReplayBatchSlots(e,t){const s=new Map;for(const n of t)typeof n.id=="number"&&n.body!==void 0&&s.set(n.id,n.body);const r=[];for(const[n,i]of e.entries()){const a=s.get(n);a===void 0?r.push(i):"error"in a?Nt.has(a.error.code)?r.push(i):this.settleReplayTerminal(i,_(a.error)):this.settleReplaySuccess(i,b(a.result),a.commitCursor)}return r}}export{Q as LunoraClient};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{O as s,n,r as o}from"./offline-queue-CzI2lYQ8.mjs";export{s as OfflineQueue,n as nextId,o as reportPersistenceError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{s as o}from"./single-blob-store-DrhzObic.mjs";const c="lunora:offline-mutations",m=s=>{const a=o(s.storage,s.key??c),r=async()=>{const e=await a.read();return Array.isArray(e)?e:[]};return{append:e=>a.serialize(async()=>{const t=await r();t.push(e),await a.write(t)}),clear:a.clear,load:()=>a.serialize(r),remove:e=>a.serialize(async()=>{const t=await r(),i=t.filter(n=>n.id!==e);i.length!==t.length&&await a.write(i)})}};export{m as createAsyncStoragePersistence};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d,e as y}from"./wire-codec-D4iww4NV.mjs";import{assertMaxEntries as u}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{s as f}from"./single-blob-store-DrhzObic.mjs";const m="lunora:query-cache",w=50,p=s=>{const c=u(s.maxEntries??w,"createAsyncStorageQueryCache"),t=f(s.storage,s.key??m),o=async()=>{const e=d(await t.read());return typeof e=="object"&&e!==null&&!Array.isArray(e)?new Map(Object.entries(e)):new Map},n=e=>t.write(y(Object.fromEntries(e))),i=e=>{if(e.size<=c)return;const a=[...e.values()].toSorted((r,l)=>r.ts-l.ts);for(const r of a){if(e.size<=c)break;e.delete(r.key)}};return{clear:t.clear,load:()=>t.serialize(async()=>[...(await o()).values()]),put:(e,a)=>t.serialize(async()=>{const r=await o();r.set(e,{...a,key:e}),i(r),await n(r)}),remove:e=>t.serialize(async()=>{const a=await o();a.delete(e)&&await n(a)})}};export{p as createAsyncStorageQueryCache};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{p as s,c as m,a as f}from"./idb-utility-C8WS390w.mjs";const x=()=>{const e=new Map,a=r=>({...r,args:{...r.args}});return{append:r=>(e.set(r.id,a(r)),Promise.resolve()),clear:()=>(e.clear(),Promise.resolve()),load:()=>Promise.resolve([...e.values()].map(r=>a(r))),remove:r=>(e.delete(r),Promise.resolve())}},y="lunora-outbox",D="offline-mutations",d="by_id",p=(e={})=>{const a=e.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!a)throw new u("INTERNAL","createIndexedDbPersistence: no IndexedDB available — pass `indexedDB` or use createInMemoryPersistence()");const r=e.databaseName??y,c=e.storeName??D,l=f(a,r,1,t=>{t.objectStoreNames.contains(c)||t.createObjectStore(c,{autoIncrement:!0}).createIndex(d,"id",{unique:!0})}),o=m(l,c);return{append:async t=>{await o("readwrite",n=>s(n.add(t)))},clear:async()=>{await o("readwrite",t=>s(t.clear()))},load:async()=>o("readonly",t=>s(t.getAll())),remove:async t=>{await o("readwrite",async n=>{const i=await s(n.index(d).getKey(t));i!==void 0&&await s(n.delete(i))})}}},b=(e,a=!0)=>{if(e!==!1){if(e)return e;if(!(!a||typeof indexedDB>"u"))return p()}};export{x as createInMemoryPersistence,p as createIndexedDbPersistence,b as resolvePersistenceAdapter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{p as u,c as h,a as I}from"./idb-utility-C8WS390w.mjs";const T=(e,o,a)=>`${e}::${o}::${a??""}`,w=500,E=(e,o)=>{if(!Number.isInteger(e)||e<1)throw new v("INTERNAL",`${o}: maxEntries must be a positive integer, got ${String(e)}`);return e},B=(e={})=>{const o=E(e.maxEntries??w,"createInMemoryQueryCache"),a=new Map,s=r=>({...r,value:structuredClone(r.value)}),l=()=>{if(a.size<=o)return;const r=[...a.values()].toSorted((n,y)=>n.ts-y.ts);for(const n of r){if(a.size<=o)break;a.delete(n.key)}};return{clear:()=>(a.clear(),Promise.resolve()),load:()=>Promise.resolve([...a.values()].map(r=>s(r))),put:(r,n)=>(a.set(r,s({...n,key:r})),l(),Promise.resolve()),remove:r=>(a.delete(r),Promise.resolve())}},A="lunora-query-cache",b="query-cache",f="by_ts",p=1,N=(e={})=>{const o=e.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!o)throw new v("INTERNAL","createIndexedDbQueryCache: no IndexedDB available — pass `indexedDB` or use createInMemoryQueryCache()");const a=e.databaseName??A,s=e.storeName??b,l=E(e.maxEntries??w,"createIndexedDbQueryCache"),r=I(o,a,p,t=>{t.objectStoreNames.contains(s)||t.createObjectStore(s,{keyPath:"key"}).createIndex(f,"ts",{unique:!1})}),n=h(r,s),y=async t=>{let c=await u(t.count())-l;c<=0||await new Promise((D,x)=>{const d=t.index(f).openCursor();d.addEventListener("success",()=>{const m=d.result;if(!m||c<=0){D();return}m.delete(),c-=1,m.continue()}),d.addEventListener("error",()=>{x(d.error??new Error("IndexedDB eviction failed"))})})};return{clear:async()=>{await n("readwrite",t=>u(t.clear()))},load:async()=>n("readonly",t=>u(t.getAll())),put:async(t,i)=>{await n("readwrite",async c=>{await u(c.put({...i,key:t})),await y(c)})},remove:async t=>{await n("readwrite",i=>u(i.delete(t)))}}},L=e=>{if(e!==!1){if(e)return e;if(!(typeof indexedDB>"u"))return N()}};export{E as assertMaxEntries,B as createInMemoryQueryCache,N as createIndexedDbQueryCache,T as queryCacheKey,L as resolveQueryCacheAdapter};
|
package/dist/packem_shared/{createServerClient-CNzt_8I6.mjs → createServerClient-MHXUwfgO.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraClient as r}from"./LunoraClient-
|
|
1
|
+
import{LunoraClient as r}from"./LunoraClient-C7T_1hO7.mjs";const c=e=>{const t=new r({fetch:e.fetch,url:e.url});return e.token!==void 0&&t.setAuthToken(e.token),t};export{c as createServerClient};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-
|
|
1
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-P1jVmZim.js";
|
|
2
2
|
import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
|
|
3
3
|
/**
|
|
4
4
|
* Reactive key-value store for local-only client state.
|
package/dist/packem_shared/{lunora-client.d-Dkd6-fpN.d.mts → lunora-client.d-DGVdFJCO.d.mts}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-
|
|
1
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClientOptions, a as Unsubscribe, U as User, W as WsTokenProvider, S as ShardTrafficResult, b as ScheduleRecord, c as SchedulerStatus, d as WorkflowInstanceStatus, e as WorkflowInstancePage, f as WorkflowInstanceDetail, g as WorkflowInstanceAction, h as FunctionDescriptor, i as StorageListPage, G as GlobalTableInfo, j as GlobalFilterClause, k as GlobalTablePage, l as GlobalFacetResult, H as HttpStreamRef, m as HttpStreamArgsOf, n as HttpStreamChunkOf } from "./types.d-P1jVmZim.mjs";
|
|
2
2
|
import { CronJobInfo, VectorIndexSummary, VectorQueryMatch, PipelineLogQuery, PipelineLogPage, KvNamespaceSummary, KvKeyListResult, KvValueResult, AuthUser, AuthPage, AuthImpersonation, AuthCapabilities, AuthConfigInfo, AuthSession } from '@lunora/runtime';
|
|
3
3
|
/**
|
|
4
4
|
* Reactive key-value store for local-only client state.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let h=0;const a=()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();h+=1;const r=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${h.toString(36)}_${r}`},f=(r,e)=>r!==void 0&&e!==r,u=a,o=(r,e,t,s)=>{if(r){r({error:t,mutationId:s,operation:e});return}console.warn(`[lunora] offline-queue persistence ${e} failed`,t)};class m{queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},t={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=t.persistence,this.onEvict=t.onEvict,this.onSizeChange=t.onSizeChange,this.version=t.version}get size(){return this.items.length}enqueue(e){const t=e;t.id??=u(),this.items.push(t),this.persistence?.append({args:t.args,clientId:t.clientId,functionPath:t.functionPath,id:t.id,identity:t.identity,shardKey:t.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{o(this.onPersistenceError,"append",s,t.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(i){throw o(this.onPersistenceError,"load",i),i}const t=[],s=new Set(this.items.map(i=>i.id));for(const i of e)if(!s.has(i.id)){if(f(this.version,i.version)){this.persistence.remove(i.id).catch(d=>{o(this.onPersistenceError,"remove",d,i.id)});continue}s.add(i.id),t.push({args:i.args,clientId:i.clientId,functionPath:i.functionPath,id:i.id,identity:i.identity,reject:()=>{},resolve:()=>{},shardKey:i.shardKey})}this.items.unshift(...t),this.evictOverflow(),this.notifySize();const n=new Set(this.items),c=new Set;for(const i of t)n.has(i)&&c.add(i.shardKey);return[...c]}drain(e){if(!e){const n=[...this.items];return this.items.length=0,this.notifySize(),n}const t=[],s=[];for(const n of this.items)(e(n)?t:s).push(n);return this.items.length=0,this.items.push(...s),this.notifySize(),t}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){const e=[],t=[];for(const s of this.items)if(s.precondition!==void 0&&!s.precondition()){const n=new Error("offline mutation skipped: precondition failed before replay");n.code="OFFLINE_PRECONDITION_FAILED",s.reject(n),e.push(s)}else t.push(s);return e.length>0&&(this.items.length=0,this.items.push(...t),this.notifySize()),e}clear(){for(const e of this.items){const t=new Error("CLIENT_CLOSED");t.code="CLIENT_CLOSED",e.reject(t)}this.items.length=0,this.notifySize()}evictOverflow(){for(;this.items.length>this.maxItems;){const e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(s=>{o(this.onPersistenceError,"remove",s,e.id)});const t=new Error("offline queue overflow");t.code="OFFLINE_QUEUE_OVERFLOW",e.reject(t),this.onEvict?.(e,t)}}}notifySize(){this.onSizeChange?.(this.items.length)}}export{m as O,f as i,u as n,o as r};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LunoraClient } from "./lunora-client.d-
|
|
2
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-
|
|
1
|
+
import { L as LunoraClient } from "./lunora-client.d-DGVdFJCO.mjs";
|
|
2
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-P1jVmZim.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Run a query once on the server (during SSR) and capture its result in a
|
|
5
5
|
* serializable {@link Preloaded} token. Embed the token in the rendered HTML and
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { L as LunoraClient } from "./lunora-client.d-
|
|
2
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-
|
|
1
|
+
import { L as LunoraClient } from "./lunora-client.d-BKDWZU-D.js";
|
|
2
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./types.d-P1jVmZim.js";
|
|
3
3
|
/**
|
|
4
4
|
* Run a query once on the server (during SSR) and capture its result in a
|
|
5
5
|
* serializable {@link Preloaded} token. Embed the token in the rendered HTML and
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const s=(t,r)=>{let n=Promise.resolve();const i=e=>{const o=n.then(e,e);return n=o.then(()=>{},()=>{}),o};return{clear:()=>i(()=>t.removeItem(r)),read:async()=>{const e=await t.getItem(r);if(e!==null)try{return JSON.parse(e)}catch{return}},serialize:i,write:e=>t.setItem(r,JSON.stringify(e))}};export{s};
|
|
@@ -255,6 +255,10 @@ interface CachedQuery {
|
|
|
255
255
|
*/
|
|
256
256
|
version?: string;
|
|
257
257
|
}
|
|
258
|
+
/** A stored read-cache row: the {@link CachedQuery} plus the key it is stored under. */
|
|
259
|
+
interface StoredQuery extends CachedQuery {
|
|
260
|
+
key: string;
|
|
261
|
+
}
|
|
258
262
|
/**
|
|
259
263
|
* Durable store for the client read cache (Pillar 2): query results survive a
|
|
260
264
|
* reload so reads hydrate from disk and render immediately while the socket
|
|
@@ -266,9 +270,7 @@ interface QueryCacheAdapter {
|
|
|
266
270
|
/** Drop every cached query (e.g. on logout / identity change). */
|
|
267
271
|
clear: () => Promise<void>;
|
|
268
272
|
/** Load every cached query — called once at startup to hydrate reads. */
|
|
269
|
-
load: () => Promise<
|
|
270
|
-
key: string;
|
|
271
|
-
})[]>;
|
|
273
|
+
load: () => Promise<StoredQuery[]>;
|
|
272
274
|
/** Upsert one cached query by key (called when a subscription value advances). */
|
|
273
275
|
put: (key: string, entry: CachedQuery) => Promise<void>;
|
|
274
276
|
/** Remove one cached query by key. */
|
|
@@ -973,4 +975,4 @@ interface WorkflowInstancePage {
|
|
|
973
975
|
perPage: number;
|
|
974
976
|
totalCount?: number;
|
|
975
977
|
}
|
|
976
|
-
export { ArgsOf as A, BookmarkStorage as B, CachedQuery as C, RpcEnvelope as D, RpcResponseBody as E, FunctionReference as F, GlobalTableInfo as G, HttpStreamRef as H, SchedulerPoolStatus as I, ServerMessage as J, ServerPokeEndMessage as K, LunoraClientOptions as L, ServerPokePartMessage as M, ServerPokeStartMessage as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, ShardTrafficResult as S, ShardTrafficEntry as T, User as U, StorageObject as V, WsTokenProvider as W,
|
|
978
|
+
export { ArgsOf as A, BookmarkStorage as B, CachedQuery as C, RpcEnvelope as D, RpcResponseBody as E, FunctionReference as F, GlobalTableInfo as G, HttpStreamRef as H, SchedulerPoolStatus as I, ServerMessage as J, ServerPokeEndMessage as K, LunoraClientOptions as L, ServerPokePartMessage as M, ServerPokeStartMessage as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, ShardTrafficResult as S, ShardTrafficEntry as T, User as U, StorageObject as V, WsTokenProvider as W, StoredQuery as X, WorkflowInstanceSummary as Y, WorkflowStepDetail as Z, Unsubscribe as a, ScheduleRecord as b, SchedulerStatus as c, WorkflowInstanceStatus as d, WorkflowInstancePage as e, WorkflowInstanceDetail as f, WorkflowInstanceAction as g, FunctionDescriptor as h, StorageListPage as i, GlobalFilterClause as j, GlobalTablePage as k, GlobalFacetResult as l, HttpStreamArgsOf as m, HttpStreamChunkOf as n, PersistenceAdapter as o, ReconnectOptions as p, ClientMessage as q, ClientShapeSubscribeMessage as r, ClientShapeUnsubscribeMessage as s, FunctionArgumentDescriptor as t, GlobalFacetValue as u, HttpStreamCallArgs as v, OutboxMutation as w, OutboxSink as x, PersistedMutation as y, RowOp as z };
|
|
@@ -255,6 +255,10 @@ interface CachedQuery {
|
|
|
255
255
|
*/
|
|
256
256
|
version?: string;
|
|
257
257
|
}
|
|
258
|
+
/** A stored read-cache row: the {@link CachedQuery} plus the key it is stored under. */
|
|
259
|
+
interface StoredQuery extends CachedQuery {
|
|
260
|
+
key: string;
|
|
261
|
+
}
|
|
258
262
|
/**
|
|
259
263
|
* Durable store for the client read cache (Pillar 2): query results survive a
|
|
260
264
|
* reload so reads hydrate from disk and render immediately while the socket
|
|
@@ -266,9 +270,7 @@ interface QueryCacheAdapter {
|
|
|
266
270
|
/** Drop every cached query (e.g. on logout / identity change). */
|
|
267
271
|
clear: () => Promise<void>;
|
|
268
272
|
/** Load every cached query — called once at startup to hydrate reads. */
|
|
269
|
-
load: () => Promise<
|
|
270
|
-
key: string;
|
|
271
|
-
})[]>;
|
|
273
|
+
load: () => Promise<StoredQuery[]>;
|
|
272
274
|
/** Upsert one cached query by key (called when a subscription value advances). */
|
|
273
275
|
put: (key: string, entry: CachedQuery) => Promise<void>;
|
|
274
276
|
/** Remove one cached query by key. */
|
|
@@ -973,4 +975,4 @@ interface WorkflowInstancePage {
|
|
|
973
975
|
perPage: number;
|
|
974
976
|
totalCount?: number;
|
|
975
977
|
}
|
|
976
|
-
export { ArgsOf as A, BookmarkStorage as B, CachedQuery as C, RpcEnvelope as D, RpcResponseBody as E, FunctionReference as F, GlobalTableInfo as G, HttpStreamRef as H, SchedulerPoolStatus as I, ServerMessage as J, ServerPokeEndMessage as K, LunoraClientOptions as L, ServerPokePartMessage as M, ServerPokeStartMessage as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, ShardTrafficResult as S, ShardTrafficEntry as T, User as U, StorageObject as V, WsTokenProvider as W,
|
|
978
|
+
export { ArgsOf as A, BookmarkStorage as B, CachedQuery as C, RpcEnvelope as D, RpcResponseBody as E, FunctionReference as F, GlobalTableInfo as G, HttpStreamRef as H, SchedulerPoolStatus as I, ServerMessage as J, ServerPokeEndMessage as K, LunoraClientOptions as L, ServerPokePartMessage as M, ServerPokeStartMessage as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, ShardTrafficResult as S, ShardTrafficEntry as T, User as U, StorageObject as V, WsTokenProvider as W, StoredQuery as X, WorkflowInstanceSummary as Y, WorkflowStepDetail as Z, Unsubscribe as a, ScheduleRecord as b, SchedulerStatus as c, WorkflowInstanceStatus as d, WorkflowInstancePage as e, WorkflowInstanceDetail as f, WorkflowInstanceAction as g, FunctionDescriptor as h, StorageListPage as i, GlobalFilterClause as j, GlobalTablePage as k, GlobalFacetResult as l, HttpStreamArgsOf as m, HttpStreamChunkOf as n, PersistenceAdapter as o, ReconnectOptions as p, ClientMessage as q, ClientShapeSubscribeMessage as r, ClientShapeUnsubscribeMessage as s, FunctionArgumentDescriptor as t, GlobalFacetValue as u, HttpStreamCallArgs as v, OutboxMutation as w, OutboxSink as x, PersistedMutation as y, RowOp as z };
|
package/dist/query/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-DGVdFJCO.mjs";
|
|
2
2
|
export type {
|
|
3
3
|
/**
|
|
4
4
|
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
@@ -10,8 +10,8 @@ export type {
|
|
|
10
10
|
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
11
11
|
* store / signal / cache.
|
|
12
12
|
*/
|
|
13
|
-
a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-
|
|
14
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-
|
|
13
|
+
a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-DGVdFJCO.mjs";
|
|
14
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-P1jVmZim.mjs";
|
|
15
15
|
import '@lunora/runtime';
|
|
16
16
|
/**
|
|
17
17
|
* The sentinel a framework adapter resolves its reactive args to when it wants
|
package/dist/query/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { S as SubscriptionError, L as LunoraClient } from "../packem_shared/lunora-client.d-BKDWZU-D.js";
|
|
2
2
|
export type {
|
|
3
3
|
/**
|
|
4
4
|
* `@lunora/client/query` — the framework-neutral live-query state machine shared
|
|
@@ -10,8 +10,8 @@ export type {
|
|
|
10
10
|
* framework — each adapter supplies thin sinks that write into its own ref /
|
|
11
11
|
* store / signal / cache.
|
|
12
12
|
*/
|
|
13
|
-
a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-
|
|
14
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-
|
|
13
|
+
a as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-BKDWZU-D.js";
|
|
14
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf, a as Unsubscribe } from "../packem_shared/types.d-P1jVmZim.js";
|
|
15
15
|
import '@lunora/runtime';
|
|
16
16
|
/**
|
|
17
17
|
* The sentinel a framework adapter resolves its reactive args to when it wants
|
package/dist/service.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-
|
|
1
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-P1jVmZim.mjs";
|
|
2
2
|
/**
|
|
3
3
|
* The wire endpoint every Lunora Worker serves. Matches `createWorker`'s RPC
|
|
4
4
|
* route; the envelope shape below is that route's documented contract.
|
package/dist/service.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-
|
|
1
|
+
import { F as FunctionReference, A as ArgsOf, R as ReturnOf } from "./packem_shared/types.d-P1jVmZim.js";
|
|
2
2
|
/**
|
|
3
3
|
* The wire endpoint every Lunora Worker serves. Matches `createWorker`'s RPC
|
|
4
4
|
* route; the envelope shape below is that route's documented contract.
|
package/dist/ssr/index.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { P as Preloaded } from "../packem_shared/types.d-
|
|
2
|
-
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-
|
|
3
|
-
import { L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { P as Preloaded } from "../packem_shared/types.d-P1jVmZim.mjs";
|
|
2
|
+
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-P1jVmZim.mjs";
|
|
3
|
+
import { L as LunoraClient } from "../packem_shared/lunora-client.d-DGVdFJCO.mjs";
|
|
4
4
|
export {
|
|
5
5
|
/**
|
|
6
6
|
* `@lunora/client/ssr` — the framework-neutral server contract that every Lunora
|
|
@@ -21,7 +21,7 @@ p as preloadQuery,
|
|
|
21
21
|
* WebSocket or touches a UI framework, so it is safe to import from any SSR
|
|
22
22
|
* loader.
|
|
23
23
|
*/
|
|
24
|
-
a as preloadedQueryResult } from "../packem_shared/preload.d-
|
|
24
|
+
a as preloadedQueryResult } from "../packem_shared/preload.d-BJ_toV9J.mjs";
|
|
25
25
|
import '@lunora/runtime';
|
|
26
26
|
/**
|
|
27
27
|
* Structural shape of a better-auth `getSession` call's resolved value.
|
package/dist/ssr/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { P as Preloaded } from "../packem_shared/types.d-
|
|
2
|
-
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-
|
|
3
|
-
import { L as LunoraClient } from "../packem_shared/lunora-client.d-
|
|
1
|
+
import { P as Preloaded } from "../packem_shared/types.d-P1jVmZim.js";
|
|
2
|
+
export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/types.d-P1jVmZim.js";
|
|
3
|
+
import { L as LunoraClient } from "../packem_shared/lunora-client.d-BKDWZU-D.js";
|
|
4
4
|
export {
|
|
5
5
|
/**
|
|
6
6
|
* `@lunora/client/ssr` — the framework-neutral server contract that every Lunora
|
|
@@ -21,7 +21,7 @@ p as preloadQuery,
|
|
|
21
21
|
* WebSocket or touches a UI framework, so it is safe to import from any SSR
|
|
22
22
|
* loader.
|
|
23
23
|
*/
|
|
24
|
-
a as preloadedQueryResult } from "../packem_shared/preload.d-
|
|
24
|
+
a as preloadedQueryResult } from "../packem_shared/preload.d-DdzlpRXw.js";
|
|
25
25
|
import '@lunora/runtime';
|
|
26
26
|
/**
|
|
27
27
|
* Structural shape of a better-auth `getSession` call's resolved value.
|
package/dist/ssr/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-
|
|
1
|
+
import{getServerSession as o}from"../packem_shared/getServerSession-BaOoo1p6.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-MHXUwfgO.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-uFy24PCR.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{O as s,n,r as o}from"./offline-queue-BdQFXDz_.mjs";export{s as OfflineQueue,n as nextId,o as reportPersistenceError};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const u="lunora:offline-mutations",y=o=>{const{storage:r}=o,a=o.key??u;let i=Promise.resolve();const n=t=>{const e=i.then(t,t);return i=e.then(()=>{},()=>{}),e},s=async()=>{const t=await r.getItem(a);if(t===null)return[];try{const e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}},c=t=>r.setItem(a,JSON.stringify(t));return{append:t=>n(async()=>{const e=await s();e.push(t),await c(e)}),clear:()=>n(()=>r.removeItem(a)),load:()=>n(s),remove:t=>n(async()=>{const e=await s(),l=e.filter(m=>m.id!==t);l.length!==e.length&&await c(l)})}};export{y as createAsyncStoragePersistence};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as u}from"@lunora/errors";import{p as s,c as f,a as y}from"./idb-utility-C8WS390w.mjs";const x=()=>{const r=new Map,a=e=>({args:{...e.args},functionPath:e.functionPath,id:e.id,identity:e.identity,shardKey:e.shardKey});return{append:e=>(r.set(e.id,a(e)),Promise.resolve()),clear:()=>(r.clear(),Promise.resolve()),load:()=>Promise.resolve([...r.values()].map(e=>a(e))),remove:e=>(r.delete(e),Promise.resolve())}},m="lunora-outbox",D="offline-mutations",c="by_id",p=(r={})=>{const a=r.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!a)throw new u("INTERNAL","createIndexedDbPersistence: no IndexedDB available — pass `indexedDB` or use createInMemoryPersistence()");const e=r.databaseName??m,d=r.storeName??D,l=y(a,e,1,t=>{t.objectStoreNames.contains(d)||t.createObjectStore(d,{autoIncrement:!0}).createIndex(c,"id",{unique:!0})}),o=f(l,d);return{append:async t=>{await o("readwrite",n=>s(n.add(t)))},clear:async()=>{await o("readwrite",t=>s(t.clear()))},load:async()=>o("readonly",t=>s(t.getAll())),remove:async t=>{await o("readwrite",async n=>{const i=await s(n.index(c).getKey(t));i!==void 0&&await s(n.delete(i))})}}},P=(r,a=!0)=>{if(r!==!1){if(r)return r;if(!(!a||typeof indexedDB>"u"))return p()}};export{x as createInMemoryPersistence,p as createIndexedDbPersistence,P as resolvePersistenceAdapter};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as D}from"@lunora/errors";import{p as d,c as x,a as A}from"./idb-utility-C8WS390w.mjs";const B=(t,o,a)=>`${t}::${o}::${a??""}`,v=500,T=(t={})=>{const o=t.maxEntries??v,a=new Map,s=e=>({...e,value:structuredClone(e.value)}),l=()=>{if(a.size<=o)return;const e=[...a.values()].toSorted((n,y)=>n.ts-y.ts);for(const n of e){if(a.size<=o)break;a.delete(n.key)}};return{clear:()=>(a.clear(),Promise.resolve()),load:()=>Promise.resolve([...a.values()].map(e=>s(e))),put:(e,n)=>(a.set(e,s({...n,key:e})),l(),Promise.resolve()),remove:e=>(a.delete(e),Promise.resolve())}},h="lunora-query-cache",p="query-cache",f="by_ts",I=1,S=(t={})=>{const o=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!o)throw new D("INTERNAL","createIndexedDbQueryCache: no IndexedDB available — pass `indexedDB` or use createInMemoryQueryCache()");const a=t.databaseName??h,s=t.storeName??p,l=t.maxEntries??v,e=A(o,a,I,r=>{r.objectStoreNames.contains(s)||r.createObjectStore(s,{keyPath:"key"}).createIndex(f,"ts",{unique:!1})}),n=x(e,s),y=async r=>{let c=await d(r.count())-l;c<=0||await new Promise((E,w)=>{const u=r.index(f).openCursor();u.addEventListener("success",()=>{const m=u.result;if(!m||c<=0){E();return}m.delete(),c-=1,m.continue()}),u.addEventListener("error",()=>{w(u.error??new Error("IndexedDB eviction failed"))})})};return{clear:async()=>{await n("readwrite",r=>d(r.clear()))},load:async()=>n("readonly",r=>d(r.getAll())),put:async(r,i)=>{await n("readwrite",async c=>{await d(c.put({...i,key:r})),await y(c)})},remove:async r=>{await n("readwrite",i=>d(i.delete(r)))}}},C=t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return S()}};export{T as createInMemoryQueryCache,S as createIndexedDbQueryCache,B as queryCacheKey,C as resolveQueryCacheAdapter};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
let h=0;const d=()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();h+=1;const r=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),t=>t.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${h.toString(36)}_${r}`},a=(r,t)=>r!==void 0&&t!==r,f=d,c=(r,t,e,s)=>{if(r){r({error:e,mutationId:s,operation:t});return}console.warn(`[lunora] offline-queue persistence ${t} failed`,e)};class u{queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(t={},e={}){this.maxItems=t.maxItems??1e3,this.queueBeforeFirstConnect=t.queueBeforeFirstConnect??!1,this.onPersistenceError=t.onPersistenceError,this.persistence=e.persistence,this.onEvict=e.onEvict,this.onSizeChange=e.onSizeChange,this.version=e.version}get size(){return this.items.length}enqueue(t){const e=t;e.id??=f(),this.items.push(e),this.persistence?.append({args:e.args,clientId:e.clientId,functionPath:e.functionPath,id:e.id,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{c(this.onPersistenceError,"append",s,e.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let t;try{t=await this.persistence.load()}catch(i){throw c(this.onPersistenceError,"load",i),i}const e=[];for(const i of t)if(!(this.items.some(o=>o.id===i.id)||e.some(o=>o.id===i.id))){if(a(this.version,i.version)){this.persistence.remove(i.id).catch(o=>{c(this.onPersistenceError,"remove",o,i.id)});continue}e.push({args:i.args,clientId:i.clientId,functionPath:i.functionPath,id:i.id,identity:i.identity,reject:()=>{},resolve:()=>{},shardKey:i.shardKey})}this.items.unshift(...e),this.evictOverflow(),this.notifySize();const s=new Set(this.items),n=new Set;for(const i of e)s.has(i)&&n.add(i.shardKey);return[...n]}drain(t){if(!t){const n=[...this.items];return this.items.length=0,this.notifySize(),n}const e=[],s=[];for(const n of this.items)(t(n)?e:s).push(n);return this.items.length=0,this.items.push(...s),this.notifySize(),e}requeue(t){t.length!==0&&(this.items.unshift(...t),this.notifySize())}drainConflict(){const t=[],e=[];for(const s of this.items)if(s.precondition!==void 0&&!s.precondition()){const n=new Error("offline mutation skipped: precondition failed before replay");n.code="OFFLINE_PRECONDITION_FAILED",s.reject(n),t.push(s)}else e.push(s);return t.length>0&&(this.items.length=0,this.items.push(...e),this.notifySize()),t}clear(){for(const t of this.items){const e=new Error("CLIENT_CLOSED");e.code="CLIENT_CLOSED",t.reject(e)}this.items.length=0,this.notifySize()}evictOverflow(){for(;this.items.length>this.maxItems;){const t=this.items.shift();if(t){t.id&&this.persistence?.remove(t.id).catch(s=>{c(this.onPersistenceError,"remove",s,t.id)});const e=new Error("offline queue overflow");e.code="OFFLINE_QUEUE_OVERFLOW",t.reject(e),this.onEvict?.(t,e)}}}notifySize(){this.onSizeChange?.(this.items.length)}}export{u as O,a as i,f as n,c as r};
|