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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/auth/index.d.mts +1 -1
  2. package/dist/auth/index.d.ts +1 -1
  3. package/dist/auth/index.mjs +1 -60
  4. package/dist/index.d.mts +3 -3
  5. package/dist/index.d.ts +3 -3
  6. package/dist/index.mjs +1 -21
  7. package/dist/packem_shared/CONFLICT_ERROR_CODE-B2SU0CaJ.mjs +1 -0
  8. package/dist/packem_shared/ClientServiceWorker-CRQ5yl7-.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_MAX_BUFFER-TBn2s7Rz.mjs +1 -0
  10. package/dist/packem_shared/LunoraClient-DDEoZdgP.mjs +1 -0
  11. package/dist/packem_shared/OfflineQueue-B603_q8m.mjs +1 -0
  12. package/dist/packem_shared/SKIP-CArzT3Vl.mjs +1 -0
  13. package/dist/packem_shared/SubscriptionRegistry-CdrOD7sZ.mjs +1 -0
  14. package/dist/packem_shared/TabCoordinator-ijLic02x.mjs +1 -0
  15. package/dist/packem_shared/applyDelta-DXqQORbM.mjs +1 -0
  16. package/dist/packem_shared/createAsyncStoragePersistence-BRLqeXsC.mjs +1 -0
  17. package/dist/packem_shared/createClientQuery-CrdRoicO.mjs +1 -0
  18. package/dist/packem_shared/createInMemoryBookmarkStorage-DCd5Ej-t.mjs +1 -0
  19. package/dist/packem_shared/createInMemoryPersistence-CQYXy8UP.mjs +1 -0
  20. package/dist/packem_shared/createInMemoryQueryCache-DjCKrLjk.mjs +1 -0
  21. package/dist/packem_shared/createLocalStore-B3Tw_Tw1.mjs +1 -0
  22. package/dist/packem_shared/createMutationRunner-lQXH8Amk.mjs +1 -0
  23. package/dist/packem_shared/createMutatorRunner-BVzo0FBZ.mjs +1 -0
  24. package/dist/packem_shared/createReconnect-CFT7YRSR.mjs +1 -0
  25. package/dist/packem_shared/createReply-DF0jRsv-.mjs +1 -0
  26. package/dist/packem_shared/createServerClient-B7KqO8tv.mjs +1 -0
  27. package/dist/packem_shared/createSnapshotPrecondition-DOKRAJ4b.mjs +1 -0
  28. package/dist/packem_shared/deserializePreloaded-CHfOFpka.mjs +1 -0
  29. package/dist/packem_shared/getServerSession-CGjgRBAE.mjs +1 -0
  30. package/dist/packem_shared/httpStream-Cz4_QyjV.mjs +11 -0
  31. package/dist/packem_shared/idb-utility-C-DR8nG1.mjs +1 -0
  32. package/dist/packem_shared/local-store-C53xDvEr.mjs +1 -0
  33. package/dist/packem_shared/{lunora-client.d-B1iZb2Ph.d.mts → lunora-client.d-Bt65hm_E.d.mts} +135 -1
  34. package/dist/packem_shared/{lunora-client.d-B1iZb2Ph.d.ts → lunora-client.d-Bt65hm_E.d.ts} +135 -1
  35. package/dist/packem_shared/offline-queue-D73Dq95V.mjs +1 -0
  36. package/dist/packem_shared/{preload.d-CLwoXl3R.d.mts → preload.d-BmztUzzG.d.mts} +1 -1
  37. package/dist/packem_shared/{preload.d-Cqb4Kh2I.d.ts → preload.d-DGGRMWB5.d.ts} +1 -1
  38. package/dist/packem_shared/preloadQuery-DjwSjFwt.mjs +1 -0
  39. package/dist/packem_shared/wire-key-D_zOxXK4.mjs +1 -0
  40. package/dist/pagination/index.mjs +1 -61
  41. package/dist/query/index.d.mts +2 -2
  42. package/dist/query/index.d.ts +2 -2
  43. package/dist/query/index.mjs +1 -1
  44. package/dist/ssr/index.d.mts +3 -3
  45. package/dist/ssr/index.d.ts +3 -3
  46. package/dist/ssr/index.mjs +1 -4
  47. package/dist/upload.mjs +1 -24
  48. package/package.json +1 -1
  49. package/dist/packem_shared/CONFLICT_ERROR_CODE-B8gQ8tyU.mjs +0 -33
  50. package/dist/packem_shared/ClientServiceWorker-C3PAFwy0.mjs +0 -100
  51. package/dist/packem_shared/DEFAULT_MAX_BUFFER-7hFnzNk9.mjs +0 -110
  52. package/dist/packem_shared/LunoraClient-DKATLGHY.mjs +0 -3631
  53. package/dist/packem_shared/OfflineQueue-BgarnAub.mjs +0 -1
  54. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  55. package/dist/packem_shared/SubscriptionRegistry-CxS_Inha.mjs +0 -31
  56. package/dist/packem_shared/TabCoordinator-D_5oNTTt.mjs +0 -258
  57. package/dist/packem_shared/applyDelta-CRKZ1PBt.mjs +0 -81
  58. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  59. package/dist/packem_shared/createClientQuery-dJZg1ohm.mjs +0 -80
  60. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  61. package/dist/packem_shared/createInMemoryPersistence-DZ2VHWgm.mjs +0 -79
  62. package/dist/packem_shared/createInMemoryQueryCache-DiaGZkA2.mjs +0 -112
  63. package/dist/packem_shared/createLocalStore-BtqUmOQA.mjs +0 -2
  64. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  65. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  66. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  67. package/dist/packem_shared/createReply-lI4tVS2w.mjs +0 -36
  68. package/dist/packem_shared/createServerClient-Bp2r9tcB.mjs +0 -11
  69. package/dist/packem_shared/createSnapshotPrecondition-CxQ1T4ZP.mjs +0 -18
  70. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  71. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  72. package/dist/packem_shared/httpStream-DIdL8NEw.mjs +0 -168
  73. package/dist/packem_shared/idb-utility-DrSVX43Q.mjs +0 -48
  74. package/dist/packem_shared/local-store-DIq-UWfD.mjs +0 -106
  75. package/dist/packem_shared/offline-queue-N-1JvYb4.mjs +0 -211
  76. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  77. package/dist/packem_shared/wire-key-Djie6aaR.mjs +0 -266
@@ -1234,6 +1234,7 @@ declare const createStream: <T>(options: {
1234
1234
  handle: StreamHandle<T>;
1235
1235
  iterable: StreamIterable<T>;
1236
1236
  };
1237
+ type WSState = "idle" | "connecting" | "open" | "closed";
1237
1238
  /**
1238
1239
  * Aggregate live-socket health across every shard connection, for a UI status
1239
1240
  * indicator. `idle` = no socket opened yet; `connecting` = at least one socket
@@ -1241,6 +1242,56 @@ declare const createStream: <T>(options: {
1241
1242
  * `offline` = sockets exist but all are down (between reconnect attempts).
1242
1243
  */
1243
1244
  type ConnectionStatus = "connected" | "connecting" | "idle" | "offline";
1245
+ /** One shard's socket + watermark state in a {@link LunoraClient.debug} snapshot. */
1246
+ interface ClientDebugShard {
1247
+ /**
1248
+ * Highest custom-mutator watermark the server has echoed for this client on this
1249
+ * shard. A write whose `clientSeq` is above this has been sent but not confirmed
1250
+ * — the first thing to check when an optimistic overlay won't clear.
1251
+ */
1252
+ confirmedMutationWatermark: number;
1253
+ /** Whether a `WebSocket` object currently exists (distinct from it being open). */
1254
+ hasSocket: boolean;
1255
+ /** `undefined` for the default (unsharded) connection. */
1256
+ shardKey: string | undefined;
1257
+ /** Whether this shard's socket has ever completed a handshake — gates offline queueing. */
1258
+ wasEverConnected: boolean;
1259
+ wsState: WSState;
1260
+ }
1261
+ /** One live query or shape subscription in a {@link LunoraClient.debug} snapshot. */
1262
+ interface ClientDebugSubscription {
1263
+ /** Whether the server has acknowledged the subscription on the current socket. */
1264
+ acked: boolean;
1265
+ /** `namespace:fn` for a query, `shape:&lt;name>` for a replication shape. */
1266
+ functionPath: string;
1267
+ id: string;
1268
+ kind: "query" | "shape";
1269
+ /** Highest custom-mutator watermark echoed on THIS subscription (absent until a `settled`/poke frame arrives). */
1270
+ lastMutationId?: number;
1271
+ /** Per-call optimistic layers still folded onto this subscription's value — a non-zero count with no pending write is a leak. */
1272
+ pendingOptimisticLayers: number;
1273
+ /** Replicated rowset size (shapes only). */
1274
+ rowCount?: number;
1275
+ /** The `__cdc_log` cursor the current value reflects. */
1276
+ serverCursor?: number;
1277
+ shardKey: string | undefined;
1278
+ /** How many callers share this subscription (subscriptions are deduped by `(fn, args, shard)`). */
1279
+ subscriberCount: number;
1280
+ }
1281
+ /**
1282
+ * Everything the sync engine believes at one instant — see
1283
+ * {@link LunoraClient.debug} for why this exists.
1284
+ */
1285
+ interface ClientDebugSnapshot {
1286
+ /** The watermark key the server's custom-mutator protocol advances per `clientSeq`. */
1287
+ clientId: string;
1288
+ closed: boolean;
1289
+ connectionStatus: ConnectionStatus;
1290
+ /** Writes waiting in the built-in offline queue (not the `@lunora/db` outbox). */
1291
+ pendingWrites: number;
1292
+ shards: ClientDebugShard[];
1293
+ subscriptions: ClientDebugSubscription[];
1294
+ }
1244
1295
  /**
1245
1296
  * Terminal verdict for a mutation that passed through the offline queue,
1246
1297
  * delivered to {@link LunoraClient.onMutationSettled}.
@@ -1703,6 +1754,28 @@ declare class LunoraClient {
1703
1754
  * `LunoraDb.pendingCount()` instead (this counts only the built-in queue).
1704
1755
  */
1705
1756
  pendingCount(): number;
1757
+ /**
1758
+ * A point-in-time snapshot of everything the sync engine believes right now:
1759
+ * per-shard sockets and watermarks, every live query and shape subscription with
1760
+ * its cursor and ack state, and the offline-queue depth.
1761
+ *
1762
+ * This exists because the alternative is `console.log`. When an optimistic
1763
+ * overlay doesn't clear, the questions are always the same — *is the socket open?
1764
+ * what watermark has the server confirmed for this shard? has this shape been
1765
+ * poked since my write? is anything stuck in the queue?* — and none of them were
1766
+ * answerable from outside the client, so every adopter ends up instrumenting the
1767
+ * library by hand or building a bespoke policy layer around a symptom.
1768
+ *
1769
+ * Read it from a devtools console, log it next to a bug report, or render it in a
1770
+ * debug panel. Pull-only and allocation-cheap; nothing here is reactive, so poll
1771
+ * it or read it on demand.
1772
+ *
1773
+ * ```ts
1774
+ * const { shards, subscriptions } = client.debug();
1775
+ * // shards: [{ shardKey: "user-1", wsState: "open", confirmedMutationWatermark: 42, … }]
1776
+ * ```
1777
+ */
1778
+ debug(): ClientDebugSnapshot;
1706
1779
  /**
1707
1780
  * Subscribe to changes in {@link pendingCount}. Invokes `listener` immediately
1708
1781
  * with the current count, then whenever the queue depth changes (a write is
@@ -1856,6 +1929,67 @@ declare class LunoraClient {
1856
1929
  action<F extends FunctionReference>(function_: F, args: ArgsOf<F>, options?: {
1857
1930
  shardKey?: string;
1858
1931
  }): Promise<ReturnOf<F>>;
1932
+ /**
1933
+ * Bulk-import `rows` through a mutation that accepts a batch, chunked so a large
1934
+ * dataset lands in a bounded number of round-trips.
1935
+ *
1936
+ * **Offline caveat:** each chunk is sent with {@link LunoraClient.mutation}, which
1937
+ * resolves once the write is durably queued rather than once the server has applied
1938
+ * it. So an import run while offline resolves `{ chunks, imported }` with nothing
1939
+ * committed yet — the counts describe what was *handed over*, and the outbox
1940
+ * replays them on reconnect. Don't report "migration complete" on this alone.
1941
+ *
1942
+ * This is the one-shot migration / seed path: "I have 20k rows client-side and a
1943
+ * server mutation that inserts many at once". Doing it by hand goes wrong in two
1944
+ * predictable ways — a serial per-row loop pays one round-trip *and* one watermark
1945
+ * wait per row (a 200-row import becomes 200 sequential hops), while a single
1946
+ * giant call blows the DO's batch limit. So: chunk, send sequentially, and give
1947
+ * each chunk a stable idempotency key derived from `importId` + its index, so a
1948
+ * resumed or retried import doesn't double-insert the chunks that already landed.
1949
+ *
1950
+ * The server mutation is yours (Lunora can't guess the table or the row shape);
1951
+ * back it with `ctx.db.insertMany(...)`, or `insertManyUnsafe(...)` for data you
1952
+ * vouch for. `chunkSize` defaults to 500, matching the DO's default batch cap.
1953
+ *
1954
+ * ```ts
1955
+ * await client.importRows(api.migrate.importNodes, nodes, {
1956
+ * importId: `migrate-${userId}`,
1957
+ * onProgress: ({ done, total }) => setProgress(done / total),
1958
+ * shardKey: userId,
1959
+ * toArgs: (chunk) => ({ nodes: chunk }),
1960
+ * });
1961
+ * ```
1962
+ */
1963
+ importRows(function_: FunctionReference, rows: ReadonlyArray<unknown>, options?: {
1964
+ /** Rows per call. Defaults to 500 — the DO's default batch cap. */
1965
+ chunkSize?: number;
1966
+ /**
1967
+ * Stable id for this import run. Each chunk is sent under
1968
+ * `${importId}:${chunkIndex}` as its mutation id, so a retry or a resumed
1969
+ * import is deduped server-side instead of inserting the chunk twice.
1970
+ * Omit only for a throwaway import where double-insertion is acceptable.
1971
+ */
1972
+ importId?: string;
1973
+ /**
1974
+ * Called after each chunk is accepted — for a progress bar.
1975
+ *
1976
+ * "Accepted" is not always "committed": while offline (or mid-reconnect) a
1977
+ * `mutation` resolves as soon as the write is durably **queued**, so a fully
1978
+ * offline import reports completion with nothing yet applied server-side.
1979
+ * Gate a migration's "done" state on connectivity, not just on this.
1980
+ */
1981
+ onProgress?: (progress: {
1982
+ done: number;
1983
+ total: number;
1984
+ }) => void;
1985
+ /** Routes every chunk to one shard's DO. */
1986
+ shardKey?: string;
1987
+ /** Build the mutation args for one chunk. Defaults to `{ rows: chunk }`. */
1988
+ toArgs?: (chunk: ReadonlyArray<unknown>) => Record<string, unknown>;
1989
+ }): Promise<{
1990
+ chunks: number;
1991
+ imported: number;
1992
+ }>;
1859
1993
  /**
1860
1994
  * Read the cross-shard request distribution for a `.shardBy(...)` table —
1861
1995
  * the feed the studio's `hot_shard` advisor lint consumes. Hits the
@@ -2842,4 +2976,4 @@ declare class LunoraClient {
2842
2976
  */
2843
2977
  private settleReplayBatchSlots;
2844
2978
  }
2845
- export { ServerPokePartMessage as $, ArgsOf as A, BookmarkStorage as B, CONFLICT_ERROR_CODE as C, DEFAULT_MAX_BUFFER as D, OptimisticUpdate as E, FunctionReference as F, GlobalFacetResult as G, HttpStreamRef as H, OutboxMutation as I, OutboxSink as J, PersistedMutation as K, LunoraClient as L, MutationCallOptions as M, RowOp as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, SubscriptionError as S, RpcEnvelope as T, User as U, RpcResponseBody as V, ScheduleRecord as W, SchedulerPoolStatus as X, SchedulerStatus as Y, ServerMessage as Z, ServerPokeEndMessage as _, Unsubscribe as a, ServerPokeStartMessage as a0, ShardTrafficEntry as a1, ShardTrafficResult as a2, StorageListPage as a3, StorageObject as a4, StreamHandle as a5, SubscriptionCallback as a6, SubscriptionRegistry as a7, SubscriptionState as a8, SyncWatermark as a9, WorkflowInstanceAction as aa, WorkflowInstanceDetail as ab, WorkflowInstancePage as ac, WorkflowInstanceStatus as ad, WorkflowInstanceSummary as ae, WorkflowStepDetail as af, WsTokenProvider as ag, createClientQuery as ah, createLocalStore as ai, createStream as aj, getErrorCode as ak, getRetryAfterMs as al, isConflictError as am, isForbiddenError as an, isRateLimitedError as ao, isUnauthorizedError as ap, SubscriptionErrorCallback as b, PersistenceAdapter as c, HttpStreamArgsOf as d, HttpStreamChunkOf as e, StreamIterable as f, ReconnectOptions as g, BatchSlot as h, CachedQuery as i, ClientMessage as j, ClientQueryRef as k, ClientShapeSubscribeMessage as l, ClientShapeUnsubscribeMessage as m, ConnectionStatus as n, FunctionArgumentDescriptor as o, FunctionDescriptor as p, GlobalFacetValue as q, GlobalFilterClause as r, GlobalTableInfo as s, GlobalTablePage as t, HttpStreamCallArgs as u, LunoraClientError as v, LunoraClientOptions as w, LunoraErrorCode as x, MutationSettledEvent as y, OptimisticLocalStore as z };
2979
+ export { SchedulerStatus as $, ArgsOf as A, BookmarkStorage as B, CONFLICT_ERROR_CODE as C, DEFAULT_MAX_BUFFER as D, LunoraErrorCode as E, FunctionReference as F, GlobalFacetResult as G, HttpStreamRef as H, MutationSettledEvent as I, OptimisticLocalStore as J, OptimisticUpdate as K, LunoraClient as L, MutationCallOptions as M, OutboxMutation as N, OfflineQueueOptions as O, Preloaded as P, QueryCacheAdapter as Q, ReturnOf as R, SubscriptionError as S, OutboxSink as T, User as U, PersistedMutation as V, RowOp as W, RpcEnvelope as X, RpcResponseBody as Y, ScheduleRecord as Z, SchedulerPoolStatus as _, Unsubscribe as a, ServerMessage as a0, ServerPokeEndMessage as a1, ServerPokePartMessage as a2, ServerPokeStartMessage as a3, ShardTrafficEntry as a4, ShardTrafficResult as a5, StorageListPage as a6, StorageObject as a7, StreamHandle as a8, SubscriptionCallback as a9, SubscriptionRegistry as aa, SubscriptionState as ab, SyncWatermark as ac, WorkflowInstanceAction as ad, WorkflowInstanceDetail as ae, WorkflowInstancePage as af, WorkflowInstanceStatus as ag, WorkflowInstanceSummary as ah, WorkflowStepDetail as ai, WsTokenProvider as aj, createClientQuery as ak, createLocalStore as al, createStream as am, getErrorCode as an, getRetryAfterMs as ao, isConflictError as ap, isForbiddenError as aq, isRateLimitedError as ar, isUnauthorizedError as as, SubscriptionErrorCallback as b, PersistenceAdapter as c, HttpStreamArgsOf as d, HttpStreamChunkOf as e, StreamIterable as f, ReconnectOptions as g, BatchSlot as h, CachedQuery as i, ClientDebugShard as j, ClientDebugSnapshot as k, ClientDebugSubscription as l, ClientMessage as m, ClientQueryRef as n, ClientShapeSubscribeMessage as o, ClientShapeUnsubscribeMessage as p, ConnectionStatus as q, FunctionArgumentDescriptor as r, FunctionDescriptor as s, GlobalFacetValue as t, GlobalFilterClause as u, GlobalTableInfo as v, GlobalTablePage as w, HttpStreamCallArgs as x, LunoraClientError as y, LunoraClientOptions as z };
@@ -0,0 +1 @@
1
+ const c=(n,e)=>n!==void 0&&e!==n;let h=0;const a=()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();h+=1;const n=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?[...crypto.getRandomValues(new Uint8Array(8))].map(e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`m_${Date.now().toString(36)}_${h.toString(36)}_${n}`},r=(n,e,t,s)=>{if(n){n({error:t,mutationId:s,operation:e});return}console.warn(`[lunora] offline-queue persistence ${e} failed`,t)};class d{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;for(t.id??=a(),this.items.push(t),this.persistence?.append({args:t.args,functionPath:t.functionPath,id:t.id,identity:t.identity,shardKey:t.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{r(this.onPersistenceError,"append",s,t.id)});this.items.length>this.maxItems;){const s=this.items.shift();if(s){s.id&&this.persistence?.remove(s.id).catch(o=>{r(this.onPersistenceError,"remove",o,s.id)});const i=new Error("offline queue overflow");i.code="OFFLINE_QUEUE_OVERFLOW",s.reject(i),this.onEvict?.(s,i)}}this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(i){throw r(this.onPersistenceError,"load",i),i}const t=new Set,s=[];for(const i of e)if(!(this.items.some(o=>o.id===i.id)||s.some(o=>o.id===i.id))){if(c(this.version,i.version)){this.persistence.remove(i.id).catch(o=>{r(this.onPersistenceError,"remove",o,i.id)});continue}s.push({args:i.args,functionPath:i.functionPath,id:i.id,identity:i.identity,reject:()=>{},resolve:()=>{},shardKey:i.shardKey}),t.add(i.shardKey)}return this.items.unshift(...s),this.notifySize(),[...t]}drain(e){if(!e){const i=[...this.items];return this.items.length=0,this.notifySize(),i}const t=[],s=[];for(const i of this.items)(e(i)?t:s).push(i);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 i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",s.reject(i),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()}notifySize(){this.onSizeChange?.(this.items.length)}}export{d as c,c as d,r as s,a as u};
@@ -1,4 +1,4 @@
1
- import { F as FunctionReference, L as LunoraClient, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./lunora-client.d-B1iZb2Ph.mjs";
1
+ import { F as FunctionReference, L as LunoraClient, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./lunora-client.d-Bt65hm_E.mjs";
2
2
  /**
3
3
  * Run a query once on the server (during SSR) and capture its result in a
4
4
  * serializable {@link Preloaded} token. Embed the token in the rendered HTML and
@@ -1,4 +1,4 @@
1
- import { F as FunctionReference, L as LunoraClient, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./lunora-client.d-B1iZb2Ph.js";
1
+ import { F as FunctionReference, L as LunoraClient, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./lunora-client.d-Bt65hm_E.js";
2
2
  /**
3
3
  * Run a query once on the server (during SSR) and capture its result in a
4
4
  * serializable {@link Preloaded} token. Embed the token in the rendered HTML and
@@ -0,0 +1 @@
1
+ const l=async(e,a,r,u={})=>{const o=await e.query(a,r,u);return{__lunoraPreloaded:!0,args:r??{},functionPath:a.__lunoraRef,shardKey:u.shardKey,value:o}},t=e=>e.value;export{l as preloadQuery,t as preloadedQueryResult};
@@ -0,0 +1 @@
1
+ const m=(e,t)=>e<t?-1:e>t?1:0,p=e=>{if(e===void 0)return"null";if(typeof e=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(o=>p(o)).join(",")}]`;const t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype){const o=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${o} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const i=e,c=Object.keys(i).toSorted(m),n=[];for(const o of c){const r=i[o];r!==void 0&&n.push(`${JSON.stringify(o)}:${p(r)}`)}return`{${n.join(",")}}`},b=e=>{let t="";for(let i=0;i<e.length;i+=32768)t+=String.fromCharCode(...e.subarray(i,i+32768));return btoa(t)},A=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let c=0;c<t.length;c+=1)i[c]=t.codePointAt(c)??0;return i},s="$lunora.wire$";const g="__proto__",d={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},w={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[s,"undefined"];if(e===null)return null;const i=typeof e;if(i==="bigint")return[s,"bigint",e.toString()];if(i==="number"){const r=e;return Number.isNaN(r)?[s,"nan"]:r===1/0?[s,"inf"]:r===-1/0?[s,"-inf"]:r}if(i!=="object")return e;if(e instanceof Date)return[s,"date",l(e.getTime(),t+1)];if(e instanceof Error){const r=e,a={};for(const y of Object.keys(r))r[y]!==void 0&&(a[y]=l(r[y],t+1));const f=[s,"error",r.name,r.message,a];return r.cause!==void 0&&f.push(l(r.cause,t+1)),f}if(e instanceof URL)return[s,"url",e.href];if(e instanceof Map)return[s,"map",[...e.entries()].map(([r,a])=>[l(r,t+1),l(a,t+1)])];if(e instanceof Set)return[s,"set",[...e].map(r=>l(r,t+1))];if(e instanceof ArrayBuffer)return[s,"bytes",b(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,a=r.constructor.name,f=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return a==="Uint8Array"?[s,"bytes",b(f)]:[s,"bytes",b(f),a]}if(Array.isArray(e)){const r=e.map(a=>l(a,t+1));return r.length>0&&r[0]===s?[s,"arr",r]:r}const c=Object.getPrototypeOf(e);if(c!==null&&c!==Object.prototype){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const n=e,o={};for(const r of Object.keys(n)){const a=n[r];a!==void 0&&(o[r]=l(a,t+1))}return o},u=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===s)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(n=>u(n,t+1));case"bigint":{const n=e[2];if(typeof n!="string"||n.length>1024||!/^-?\d+$/.test(n))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(n)}case"date":return new Date(u(e[2],t+1));case"map":return new Map(e[2].map(([n,o])=>[u(n,t+1),u(o,t+1)]));case"set":return new Set(e[2].map(n=>u(n,t+1)));case"url":return new URL(e[2]);case"error":{const n=e[2],o=e[3],r=(Object.hasOwn(w,n)?w[n]:void 0)??Error,a=new r(o);a.name!==n&&Object.defineProperty(a,"name",{configurable:!0,value:n,writable:!0});const f=u(e[4],t+1);for(const y of Object.keys(f))y===g?Object.defineProperty(a,y,{configurable:!0,enumerable:!0,value:f[y],writable:!0}):a[y]=f[y];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:u(e[5],t+1),writable:!0}),a}case"bytes":{const n=A(e[2]),o=e[3]??"Uint8Array";if(o==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const r=Object.hasOwn(d,o)?d[o]:void 0;return r?new r(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(n=>u(n,t+1))}return e.map(n=>u(n,t+1))}const i=e,c={};for(const n of Object.keys(i)){const o=u(i[n],t+1);n===g?Object.defineProperty(c,n,{configurable:!0,enumerable:!0,value:o,writable:!0}):c[n]=o}return c},h=e=>p(l(e));export{u as c,l as f,h as t};
@@ -1,61 +1 @@
1
- const SPLIT_FACTOR = 2;
2
- const JOIN_FACTOR = 0.5;
3
- const initialPages = (numberItems) => [
4
- // eslint-disable-next-line unicorn/no-null -- `lower: null` is the feed head, `upper: null` the open-ended tail — both are wire-shape cursors.
5
- { lower: null, numItems: numberItems, upper: null }
6
- ];
7
- const rebalance = (pages, results) => {
8
- for (const [index, page] of pages.entries()) {
9
- if (page.upper === null) {
10
- continue;
11
- }
12
- const result = results[index];
13
- if (!result) {
14
- continue;
15
- }
16
- const size = result.page.length;
17
- if (size > SPLIT_FACTOR * page.numItems && result.splitCursor) {
18
- const split = result.splitCursor;
19
- const next = [...pages];
20
- next.splice(index, 1, { lower: page.lower, numItems: page.numItems, upper: split }, { lower: split, numItems: page.numItems, upper: page.upper });
21
- return next;
22
- }
23
- if (size < JOIN_FACTOR * page.numItems && index + 1 < pages.length) {
24
- const neighbour = pages[index + 1];
25
- if (!neighbour) {
26
- continue;
27
- }
28
- const next = [...pages];
29
- next.splice(index, 2, { lower: page.lower, numItems: page.numItems, upper: neighbour.upper });
30
- return next;
31
- }
32
- }
33
- return void 0;
34
- };
35
- const derivePaginationStatus = (skipped, pageResults) => {
36
- if (skipped || !pageResults[0]) {
37
- return { nextCursor: void 0, status: "LoadingFirstPage" };
38
- }
39
- const tail = pageResults.at(-1);
40
- if (!tail) {
41
- return { nextCursor: void 0, status: "LoadingMore" };
42
- }
43
- if (tail.isDone || tail.continueCursor === null) {
44
- return { nextCursor: void 0, status: "Exhausted" };
45
- }
46
- return { nextCursor: tail.continueCursor, status: "CanLoadMore" };
47
- };
48
- const applyLoadMore = (pages, cursor, numberItems) => {
49
- if (cursor === void 0 || cursor === null) {
50
- return void 0;
51
- }
52
- const next = [...pages];
53
- const tail = next.at(-1);
54
- if (tail) {
55
- next[next.length - 1] = { lower: tail.lower, numItems: tail.numItems, upper: cursor };
56
- }
57
- next.push({ lower: cursor, numItems: numberItems, upper: null });
58
- return next;
59
- };
60
-
61
- export { JOIN_FACTOR, SPLIT_FACTOR, applyLoadMore, derivePaginationStatus, initialPages, rebalance };
1
+ const l=2,a=.5,p=r=>[{lower:null,numItems:r,upper:null}],m=(r,s)=>{for(const[n,e]of r.entries()){if(e.upper===null)continue;const t=s[n];if(!t)continue;const i=t.page.length;if(i>2*e.numItems&&t.splitCursor){const u=t.splitCursor,o=[...r];return o.splice(n,1,{lower:e.lower,numItems:e.numItems,upper:u},{lower:u,numItems:e.numItems,upper:e.upper}),o}if(i<.5*e.numItems&&n+1<r.length){const u=r[n+1];if(!u)continue;const o=[...r];return o.splice(n,2,{lower:e.lower,numItems:e.numItems,upper:u.upper}),o}}},c=(r,s)=>{if(r||!s[0])return{nextCursor:void 0,status:"LoadingFirstPage"};const n=s.at(-1);return n?n.isDone||n.continueCursor===null?{nextCursor:void 0,status:"Exhausted"}:{nextCursor:n.continueCursor,status:"CanLoadMore"}:{nextCursor:void 0,status:"LoadingMore"}},I=(r,s,n)=>{if(s==null)return;const e=[...r],t=e.at(-1);return t&&(e[e.length-1]={lower:t.lower,numItems:t.numItems,upper:s}),e.push({lower:s,numItems:n,upper:null}),e};export{a as JOIN_FACTOR,l as SPLIT_FACTOR,I as applyLoadMore,c as derivePaginationStatus,p as initialPages,m as rebalance};
@@ -1,5 +1,5 @@
1
- import { S as SubscriptionError, F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-B1iZb2Ph.mjs";
2
- export type { b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-B1iZb2Ph.mjs";
1
+ import { S as SubscriptionError, F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-Bt65hm_E.mjs";
2
+ export type { b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Bt65hm_E.mjs";
3
3
  import '@lunora/runtime';
4
4
  /**
5
5
  * The sentinel a framework adapter resolves its reactive args to when it wants
@@ -1,5 +1,5 @@
1
- import { S as SubscriptionError, F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-B1iZb2Ph.js";
2
- export type { b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-B1iZb2Ph.js";
1
+ import { S as SubscriptionError, F as FunctionReference, A as ArgsOf, R as ReturnOf, L as LunoraClient, a as Unsubscribe } from "../packem_shared/lunora-client.d-Bt65hm_E.js";
2
+ export type { b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-Bt65hm_E.js";
3
3
  import '@lunora/runtime';
4
4
  /**
5
5
  * The sentinel a framework adapter resolves its reactive args to when it wants
@@ -1 +1 @@
1
- export { SKIP, createQuerySubscription, toSubscriptionError } from '../packem_shared/SKIP-vItZChkw.mjs';
1
+ import{SKIP as t,createQuerySubscription as e,toSubscriptionError as i}from"../packem_shared/SKIP-CArzT3Vl.mjs";export{t as SKIP,e as createQuerySubscription,i as toSubscriptionError};
@@ -1,6 +1,6 @@
1
- import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-B1iZb2Ph.mjs";
2
- export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/lunora-client.d-B1iZb2Ph.mjs";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-CLwoXl3R.mjs";
1
+ import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-Bt65hm_E.mjs";
2
+ export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/lunora-client.d-Bt65hm_E.mjs";
3
+ export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-BmztUzzG.mjs";
4
4
  import '@lunora/runtime';
5
5
  /**
6
6
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1,6 +1,6 @@
1
- import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-B1iZb2Ph.js";
2
- export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/lunora-client.d-B1iZb2Ph.js";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-Cqb4Kh2I.js";
1
+ import { P as Preloaded, L as LunoraClient } from "../packem_shared/lunora-client.d-Bt65hm_E.js";
2
+ export type { A as ArgsOf, F as FunctionReference, R as ReturnOf } from "../packem_shared/lunora-client.d-Bt65hm_E.js";
3
+ export { p as preloadQuery, a as preloadedQueryResult } from "../packem_shared/preload.d-DGGRMWB5.js";
4
4
  import '@lunora/runtime';
5
5
  /**
6
6
  * Structural shape of a better-auth `getSession` call's resolved value.
@@ -1,4 +1 @@
1
- export { getServerSession } from '../packem_shared/getServerSession-8jXewqxd.mjs';
2
- export { deserializePreloaded, serializePreloaded } from '../packem_shared/deserializePreloaded-C0eJTY_W.mjs';
3
- export { createServerClient } from '../packem_shared/createServerClient-Bp2r9tcB.mjs';
4
- export { preloadQuery, preloadedQueryResult } from '../packem_shared/preloadQuery-lobFkD2Z.mjs';
1
+ import{getServerSession as o}from"../packem_shared/getServerSession-CGjgRBAE.mjs";import{deserializePreloaded as l,serializePreloaded as t}from"../packem_shared/deserializePreloaded-CHfOFpka.mjs";import{createServerClient as i}from"../packem_shared/createServerClient-B7KqO8tv.mjs";import{preloadQuery as s,preloadedQueryResult as f}from"../packem_shared/preloadQuery-DjwSjFwt.mjs";export{i as createServerClient,l as deserializePreloaded,o as getServerSession,s as preloadQuery,f as preloadedQueryResult,t as serializePreloaded};
package/dist/upload.mjs CHANGED
@@ -1,24 +1 @@
1
- import { createMultipartAdapter, createChunkedRestAdapter, createTusAdapter } from '@visulima/storage-client';
2
- export { LocalStorageUrlStorage, MemoryUrlStorage, RestrictionError, UploadControl, UploadError, createChunkedRestAdapter, createMultipartAdapter, createTusAdapter, putFile, validateFile, validateFiles } from '@visulima/storage-client';
3
-
4
- const createUpload = (options) => {
5
- const protocol = options.protocol ?? "tus";
6
- const { chunkSize, control, endpoint, headers, maxRetries, metadata, restrictions, retry } = options;
7
- if (protocol === "multipart") {
8
- const multipartOptions = { endpoint, headers, maxRetries, metadata, restrictions, retry };
9
- return createMultipartAdapter(multipartOptions);
10
- }
11
- const resumableOptions = {
12
- chunkSize,
13
- control,
14
- endpoint,
15
- headers,
16
- maxRetries,
17
- metadata,
18
- restrictions,
19
- retry
20
- };
21
- return protocol === "chunked-rest" ? createChunkedRestAdapter(resumableOptions) : createTusAdapter(resumableOptions);
22
- };
23
-
24
- export { createUpload };
1
+ import{createMultipartAdapter as l,createChunkedRestAdapter as u,createTusAdapter as m}from"@visulima/storage-client";import{LocalStorageUrlStorage as x,MemoryUrlStorage as S,RestrictionError as U,UploadControl as y,UploadError as f,createChunkedRestAdapter as g,createMultipartAdapter as C,createTusAdapter as F,putFile as M,validateFile as v,validateFiles as z}from"@visulima/storage-client";const A=e=>{const t=e.protocol??"tus",{chunkSize:c,control:p,endpoint:r,headers:a,maxRetries:o,metadata:i,restrictions:d,retry:n}=e;if(t==="multipart")return l({endpoint:r,headers:a,maxRetries:o,metadata:i,restrictions:d,retry:n});const s={chunkSize:c,control:p,endpoint:r,headers:a,maxRetries:o,metadata:i,restrictions:d,retry:n};return t==="chunked-rest"?u(s):m(s)};export{x as LocalStorageUrlStorage,S as MemoryUrlStorage,U as RestrictionError,y as UploadControl,f as UploadError,g as createChunkedRestAdapter,C as createMultipartAdapter,F as createTusAdapter,A as createUpload,M as putFile,v as validateFile,z as validateFiles};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/client",
3
- "version": "1.0.0-alpha.28",
3
+ "version": "1.0.0-alpha.29",
4
4
  "description": "Lunora browser SDK: WebSocket transport, optimistic updates, and an offline mutation queue",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1,33 +0,0 @@
1
- const LUNORA_ERROR_CODES = [
2
- "BAD_REQUEST",
3
- "CONFLICT",
4
- "COUNT_RLS_UNSUPPORTED",
5
- "FORBIDDEN",
6
- "INTERNAL_SERVER_ERROR",
7
- "MASK_UNSUPPORTED",
8
- "NOT_FOUND",
9
- "NOT_IMPLEMENTED",
10
- "RELATION_PREDICATE_UNSUPPORTED",
11
- "TOO_MANY_REQUESTS",
12
- "UNAUTHORIZED",
13
- "UNPROCESSABLE"
14
- ];
15
- const KNOWN_ERROR_CODES = new Set(LUNORA_ERROR_CODES);
16
- const CONFLICT_ERROR_CODE = "CONFLICT";
17
- const isConflictError = (error) => error instanceof Error && error.code === CONFLICT_ERROR_CODE;
18
- const isForbiddenError = (error) => error instanceof Error && error.code === "FORBIDDEN";
19
- const isUnauthorizedError = (error) => error instanceof Error && error.code === "UNAUTHORIZED";
20
- const isRateLimitedError = (error) => error instanceof Error && error.code === "TOO_MANY_REQUESTS";
21
- const getErrorCode = (error) => {
22
- if (!(error instanceof Error)) {
23
- return void 0;
24
- }
25
- const { code } = error;
26
- return typeof code === "string" && KNOWN_ERROR_CODES.has(code) ? code : void 0;
27
- };
28
- const getRetryAfterMs = (error) => {
29
- const value = error?.data?.retryAfterMs;
30
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
31
- };
32
-
33
- export { CONFLICT_ERROR_CODE, getErrorCode, getRetryAfterMs, isConflictError, isForbiddenError, isRateLimitedError, isUnauthorizedError };
@@ -1,100 +0,0 @@
1
- class ClientServiceWorker {
2
- swUrl;
3
- scope;
4
- #registration = void 0;
5
- #status = "unregistered";
6
- #onStatusChange;
7
- #messageHandlers = /* @__PURE__ */ new Set();
8
- constructor(options) {
9
- this.swUrl = options.swUrl;
10
- this.scope = options.scope ?? "/";
11
- this.#onStatusChange = options.onStatusChange;
12
- }
13
- // ── Status ──────────────────────────────────────────────────────────
14
- /** Current registration status. */
15
- get status() {
16
- return this.#status;
17
- }
18
- /** The underlying `ServiceWorkerRegistration`, if registered. */
19
- get registration() {
20
- return this.#registration;
21
- }
22
- /** Whether the SW is currently controlling this page. */
23
- get active() {
24
- return this.#registration?.active !== null && this.#registration?.active !== void 0;
25
- }
26
- // ── Registration ────────────────────────────────────────────────────
27
- /**
28
- * Register the service worker.
29
- *
30
- * Returns `false` when the browser does not support service workers.
31
- */
32
- async register() {
33
- if (!("serviceWorker" in navigator)) {
34
- this.#setStatus("unsupported");
35
- return false;
36
- }
37
- this.#setStatus("registering");
38
- try {
39
- this.#registration = await navigator.serviceWorker.register(this.swUrl, {
40
- scope: this.scope
41
- });
42
- this.#setStatus("active");
43
- navigator.serviceWorker.addEventListener("message", this.#onMessage);
44
- } catch {
45
- this.#setStatus("error");
46
- return false;
47
- }
48
- return true;
49
- }
50
- /**
51
- * Remove the active service worker registration and clear listeners.
52
- *
53
- * Returns `false` when no registration is currently held.
54
- */
55
- async unregister() {
56
- if (!this.#registration) {
57
- return false;
58
- }
59
- navigator.serviceWorker.removeEventListener("message", this.#onMessage);
60
- const ok = await this.#registration.unregister();
61
- this.#registration = void 0;
62
- this.#setStatus("unregistered");
63
- return ok;
64
- }
65
- // ── Messaging ───────────────────────────────────────────────────────
66
- /**
67
- * Send a message to the active service worker.
68
- */
69
- postMessage(message) {
70
- const active = this.#registration?.active;
71
- if (active) {
72
- active.postMessage(message);
73
- }
74
- }
75
- /**
76
- * Register a handler for messages **from** the service worker.
77
- * @returns Unsubscribe function.
78
- */
79
- onMessage(handler) {
80
- this.#messageHandlers.add(handler);
81
- return () => {
82
- this.#messageHandlers.delete(handler);
83
- };
84
- }
85
- // ── Internals ───────────────────────────────────────────────────────
86
- #setStatus(status) {
87
- this.#status = status;
88
- this.#onStatusChange?.(status);
89
- }
90
- #onMessage = (event) => {
91
- for (const handler of this.#messageHandlers) {
92
- try {
93
- handler(event);
94
- } catch {
95
- }
96
- }
97
- };
98
- }
99
-
100
- export { ClientServiceWorker };
@@ -1,110 +0,0 @@
1
- import { LunoraError } from '@lunora/errors';
2
-
3
- const DEFAULT_MAX_BUFFER = 1024;
4
- const createStream = (options) => {
5
- const maxBuffer = options.maxBuffer ?? DEFAULT_MAX_BUFFER;
6
- const buffer = [];
7
- const pending = [];
8
- let done = false;
9
- let failure;
10
- let cancelled = false;
11
- const flushOne = () => {
12
- const waiter = pending.shift();
13
- if (!waiter) {
14
- return false;
15
- }
16
- if (failure) {
17
- waiter.reject(failure);
18
- return true;
19
- }
20
- if (buffer.length > 0) {
21
- const value = buffer.shift();
22
- waiter.resolve({ done: false, value });
23
- return true;
24
- }
25
- if (done) {
26
- waiter.resolve({ done: true, value: void 0 });
27
- return true;
28
- }
29
- pending.unshift(waiter);
30
- return false;
31
- };
32
- const handle = {
33
- complete() {
34
- if (done || failure) {
35
- return;
36
- }
37
- done = true;
38
- while (flushOne()) {
39
- }
40
- },
41
- fail(error) {
42
- if (done || failure) {
43
- return;
44
- }
45
- failure = error;
46
- buffer.length = 0;
47
- while (flushOne()) {
48
- }
49
- },
50
- push(value) {
51
- if (done || failure || cancelled) {
52
- return;
53
- }
54
- if (buffer.length >= maxBuffer) {
55
- handle.fail(
56
- new LunoraError(
57
- "STREAM_BACKPRESSURE",
58
- `stream buffer overflow (max=${maxBuffer.toString()}); the consumer cannot keep up with the producer`
59
- )
60
- );
61
- return;
62
- }
63
- buffer.push(value);
64
- flushOne();
65
- }
66
- };
67
- const cancel = () => {
68
- if (cancelled) {
69
- return;
70
- }
71
- cancelled = true;
72
- done = true;
73
- buffer.length = 0;
74
- try {
75
- options.onCancel();
76
- } catch {
77
- }
78
- while (flushOne()) {
79
- }
80
- };
81
- const iterable = {
82
- cancel,
83
- [Symbol.asyncIterator]() {
84
- return {
85
- next() {
86
- if (failure) {
87
- return Promise.reject(failure);
88
- }
89
- if (buffer.length > 0) {
90
- const value = buffer.shift();
91
- return Promise.resolve({ done: false, value });
92
- }
93
- if (done) {
94
- return Promise.resolve({ done: true, value: void 0 });
95
- }
96
- return new Promise((resolve, reject) => {
97
- pending.push({ reject, resolve });
98
- });
99
- },
100
- return() {
101
- cancel();
102
- return Promise.resolve({ done: true, value: void 0 });
103
- }
104
- };
105
- }
106
- };
107
- return { handle, iterable };
108
- };
109
-
110
- export { DEFAULT_MAX_BUFFER, createStream };