@lunora/client 0.0.0 → 1.0.0-alpha.10

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 (45) hide show
  1. package/LICENSE.md +105 -0
  2. package/README.md +113 -9
  3. package/__assets__/package-og.svg +14 -0
  4. package/dist/auth/index.d.mts +20 -0
  5. package/dist/auth/index.d.ts +20 -0
  6. package/dist/auth/index.mjs +60 -0
  7. package/dist/index.d.mts +385 -0
  8. package/dist/index.d.ts +385 -0
  9. package/dist/index.mjs +15 -0
  10. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +4 -0
  11. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +107 -0
  12. package/dist/packem_shared/LunoraClient-CgZ6FhKP.mjs +2721 -0
  13. package/dist/packem_shared/OfflineQueue-BI0FNNvc.mjs +1 -0
  14. package/dist/packem_shared/SKIP-vItZChkw.mjs +50 -0
  15. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +1 -0
  16. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +61 -0
  17. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +45 -0
  18. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +11 -0
  19. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +105 -0
  20. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +138 -0
  21. package/dist/packem_shared/createLocalStore-IOur0jHF.mjs +1 -0
  22. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +21 -0
  23. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +31 -0
  24. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +22 -0
  25. package/dist/packem_shared/createServerClient-BxkNcRlR.mjs +11 -0
  26. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +4 -0
  27. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +13 -0
  28. package/dist/packem_shared/local-store-BNgN3Dw3.mjs +111 -0
  29. package/dist/packem_shared/lunora-client.d-B5vWSgvD.d.mts +2196 -0
  30. package/dist/packem_shared/lunora-client.d-B5vWSgvD.d.ts +2196 -0
  31. package/dist/packem_shared/offline-queue-7Wc4onA0.mjs +164 -0
  32. package/dist/packem_shared/preload.d-3XJD-2hM.d.mts +20 -0
  33. package/dist/packem_shared/preload.d-CKZR675M.d.ts +20 -0
  34. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +13 -0
  35. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +55 -0
  36. package/dist/pagination/index.d.mts +82 -0
  37. package/dist/pagination/index.d.ts +82 -0
  38. package/dist/pagination/index.mjs +61 -0
  39. package/dist/query/index.d.mts +62 -0
  40. package/dist/query/index.d.ts +62 -0
  41. package/dist/query/index.mjs +1 -0
  42. package/dist/ssr/index.d.mts +115 -0
  43. package/dist/ssr/index.d.ts +115 -0
  44. package/dist/ssr/index.mjs +4 -0
  45. package/package.json +53 -17
@@ -0,0 +1,164 @@
1
+ const isStaleVersion = (current, stamped) => current !== void 0 && stamped !== current;
2
+
3
+ let idCounter = 0;
4
+ const nextId = () => {
5
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
6
+ return crypto.randomUUID();
7
+ }
8
+ idCounter += 1;
9
+ const entropy = typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function" ? [...crypto.getRandomValues(new Uint8Array(8))].map((byte) => byte.toString(16).padStart(2, "0")).join("") : (
10
+ // eslint-disable-next-line sonarjs/pseudo-random -- non-cryptographic uniqueness entropy, not a security token; only reached when neither crypto.randomUUID nor crypto.getRandomValues exists
11
+ Math.random().toString(16).slice(2, 12)
12
+ );
13
+ return `m_${Date.now().toString(36)}_${idCounter.toString(36)}_${entropy}`;
14
+ };
15
+ const reportPersistenceError = (handler, operation, error, mutationId) => {
16
+ if (handler) {
17
+ handler({ error, mutationId, operation });
18
+ return;
19
+ }
20
+ console.warn(`[lunora] offline-queue persistence ${operation} failed`, error);
21
+ };
22
+ class OfflineQueue {
23
+ /** Opt-in to queueing mutations before the targeted shard's first connect. */
24
+ queueBeforeFirstConnect;
25
+ maxItems;
26
+ onPersistenceError;
27
+ persistence;
28
+ onEvict;
29
+ onSizeChange;
30
+ /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
31
+ version;
32
+ items = [];
33
+ constructor(options = {}, deps = {}) {
34
+ this.maxItems = options.maxItems ?? 1e3;
35
+ this.queueBeforeFirstConnect = options.queueBeforeFirstConnect ?? false;
36
+ this.onPersistenceError = options.onPersistenceError;
37
+ this.persistence = deps.persistence;
38
+ this.onEvict = deps.onEvict;
39
+ this.onSizeChange = deps.onSizeChange;
40
+ this.version = deps.version;
41
+ }
42
+ get size() {
43
+ return this.items.length;
44
+ }
45
+ enqueue(entry) {
46
+ const item = entry;
47
+ item.id ??= nextId();
48
+ this.items.push(item);
49
+ this.persistence?.append({
50
+ args: item.args,
51
+ functionPath: item.functionPath,
52
+ id: item.id,
53
+ identity: item.identity,
54
+ shardKey: item.shardKey,
55
+ ...this.version === void 0 ? {} : { version: this.version }
56
+ }).catch((error) => {
57
+ reportPersistenceError(this.onPersistenceError, "append", error, item.id);
58
+ });
59
+ while (this.items.length > this.maxItems) {
60
+ const dropped = this.items.shift();
61
+ if (dropped) {
62
+ if (dropped.id) {
63
+ this.persistence?.remove(dropped.id).catch((error2) => {
64
+ reportPersistenceError(this.onPersistenceError, "remove", error2, dropped.id);
65
+ });
66
+ }
67
+ const error = new Error("offline queue overflow");
68
+ error.code = "OFFLINE_QUEUE_OVERFLOW";
69
+ dropped.reject(error);
70
+ this.onEvict?.(dropped, error);
71
+ }
72
+ }
73
+ this.notifySize();
74
+ }
75
+ /**
76
+ * Restore mutations persisted in a prior session and re-queue them in FIFO
77
+ * order. Restored entries already live in durable storage, so they are not
78
+ * re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
79
+ * gone after a reload). No-op when no persistence adapter is configured.
80
+ * Returns the distinct shard keys of the restored writes so the caller can
81
+ * open their sockets to trigger a flush.
82
+ */
83
+ async hydrate() {
84
+ if (!this.persistence) {
85
+ return [];
86
+ }
87
+ const persisted = await this.persistence.load();
88
+ const shardKeys = /* @__PURE__ */ new Set();
89
+ for (const mutation of persisted) {
90
+ if (this.items.some((item) => item.id === mutation.id)) {
91
+ continue;
92
+ }
93
+ if (isStaleVersion(this.version, mutation.version)) {
94
+ this.persistence.remove(mutation.id).catch((error) => {
95
+ reportPersistenceError(this.onPersistenceError, "remove", error, mutation.id);
96
+ });
97
+ continue;
98
+ }
99
+ this.items.push({
100
+ args: mutation.args,
101
+ functionPath: mutation.functionPath,
102
+ id: mutation.id,
103
+ identity: mutation.identity,
104
+ reject: () => void 0,
105
+ resolve: () => void 0,
106
+ shardKey: mutation.shardKey
107
+ });
108
+ shardKeys.add(mutation.shardKey);
109
+ }
110
+ this.notifySize();
111
+ return [...shardKeys];
112
+ }
113
+ /**
114
+ * Remove and return queued mutations. With no `predicate`, drains the whole
115
+ * queue. With one, drains only matching entries (preserving FIFO order) and
116
+ * leaves the rest queued — used to flush a single shard's writes when its
117
+ * socket reconnects while other shards are still down.
118
+ */
119
+ drain(predicate) {
120
+ if (!predicate) {
121
+ const drained2 = [...this.items];
122
+ this.items.length = 0;
123
+ this.notifySize();
124
+ return drained2;
125
+ }
126
+ const drained = [];
127
+ const kept = [];
128
+ for (const item of this.items) {
129
+ (predicate(item) ? drained : kept).push(item);
130
+ }
131
+ this.items.length = 0;
132
+ this.items.push(...kept);
133
+ this.notifySize();
134
+ return drained;
135
+ }
136
+ /**
137
+ * Return previously-drained mutations to the front of the queue, preserving
138
+ * their FIFO order, without re-persisting them — they were never unpersisted,
139
+ * so durable storage still holds them. Used when a flush aborts on a transient
140
+ * transport failure: the unreplayed writes stay queued for the next reconnect.
141
+ */
142
+ requeue(items) {
143
+ if (items.length === 0) {
144
+ return;
145
+ }
146
+ this.items.unshift(...items);
147
+ this.notifySize();
148
+ }
149
+ clear() {
150
+ for (const item of this.items) {
151
+ const error = new Error("CLIENT_CLOSED");
152
+ error.code = "CLIENT_CLOSED";
153
+ item.reject(error);
154
+ }
155
+ this.items.length = 0;
156
+ this.notifySize();
157
+ }
158
+ /** Notify the size observer (the client's pending-sync count) after any change. */
159
+ notifySize() {
160
+ this.onSizeChange?.(this.items.length);
161
+ }
162
+ }
163
+
164
+ export { OfflineQueue as O, isStaleVersion as i, nextId as n, reportPersistenceError as r };
@@ -0,0 +1,20 @@
1
+ import { F as FunctionReference, L as LunoraClient, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./lunora-client.d-B5vWSgvD.mjs";
2
+ /**
3
+ * Run a query once on the server (during SSR) and capture its result in a
4
+ * serializable {@link Preloaded} token. Embed the token in the rendered HTML and
5
+ * pass it to `usePreloadedQuery` on the client: the first client render shows
6
+ * the server value with no loading flash, then a live subscription takes over.
7
+ *
8
+ * The query is executed through the supplied {@link LunoraClient} over the same
9
+ * HTTP RPC path the browser uses, so the SSR client only needs a `fetch`
10
+ * implementation that can reach the worker — no in-process Durable Object access.
11
+ */
12
+ declare const preloadQuery: <F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F>, options?: {
13
+ shardKey?: string;
14
+ }) => Promise<Preloaded<ReturnOf<F>>>;
15
+ /**
16
+ * Read the captured value out of a {@link Preloaded} token without subscribing.
17
+ * Useful on the server (or in tests) when you only need the data, not a live feed.
18
+ */
19
+ declare const preloadedQueryResult: <T>(preloaded: Preloaded<T>) => T;
20
+ export { preloadedQueryResult as a, preloadQuery as p };
@@ -0,0 +1,20 @@
1
+ import { F as FunctionReference, L as LunoraClient, A as ArgsOf, R as ReturnOf, P as Preloaded } from "./lunora-client.d-B5vWSgvD.js";
2
+ /**
3
+ * Run a query once on the server (during SSR) and capture its result in a
4
+ * serializable {@link Preloaded} token. Embed the token in the rendered HTML and
5
+ * pass it to `usePreloadedQuery` on the client: the first client render shows
6
+ * the server value with no loading flash, then a live subscription takes over.
7
+ *
8
+ * The query is executed through the supplied {@link LunoraClient} over the same
9
+ * HTTP RPC path the browser uses, so the SSR client only needs a `fetch`
10
+ * implementation that can reach the worker — no in-process Durable Object access.
11
+ */
12
+ declare const preloadQuery: <F extends FunctionReference>(client: LunoraClient, function_: F, args: ArgsOf<F>, options?: {
13
+ shardKey?: string;
14
+ }) => Promise<Preloaded<ReturnOf<F>>>;
15
+ /**
16
+ * Read the captured value out of a {@link Preloaded} token without subscribing.
17
+ * Useful on the server (or in tests) when you only need the data, not a live feed.
18
+ */
19
+ declare const preloadedQueryResult: <T>(preloaded: Preloaded<T>) => T;
20
+ export { preloadedQueryResult as a, preloadQuery as p };
@@ -0,0 +1,13 @@
1
+ const preloadQuery = async (client, function_, args, options = {}) => {
2
+ const value = await client.query(function_, args, options);
3
+ return {
4
+ __lunoraPreloaded: true,
5
+ args: args ?? {},
6
+ functionPath: function_.__lunoraRef,
7
+ shardKey: options.shardKey,
8
+ value
9
+ };
10
+ };
11
+ const preloadedQueryResult = (preloaded) => preloaded.value;
12
+
13
+ export { preloadQuery, preloadedQueryResult };
@@ -0,0 +1,55 @@
1
+ const compareKeys = (a, b) => {
2
+ if (a < b) {
3
+ return -1;
4
+ }
5
+ return a > b ? 1 : 0;
6
+ };
7
+ const stableStringify = (value) => {
8
+ if (value === void 0) {
9
+ return "null";
10
+ }
11
+ if (value === null || typeof value !== "object") {
12
+ return JSON.stringify(value);
13
+ }
14
+ if (Array.isArray(value)) {
15
+ return `[${value.map((item) => stableStringify(item)).join(",")}]`;
16
+ }
17
+ const record = value;
18
+ const keys = Object.keys(record).toSorted(compareKeys);
19
+ const parts = [];
20
+ for (const key of keys) {
21
+ const raw = record[key];
22
+ if (raw === void 0) {
23
+ continue;
24
+ }
25
+ parts.push(`${JSON.stringify(key)}:${stableStringify(raw)}`);
26
+ }
27
+ return `{${parts.join(",")}}`;
28
+ };
29
+
30
+ class SubscriptionRegistry {
31
+ static key(functionPath, args, shardKey) {
32
+ return `${functionPath}::${stableStringify(args)}::${shardKey ?? ""}`;
33
+ }
34
+ byKey = /* @__PURE__ */ new Map();
35
+ byId = /* @__PURE__ */ new Map();
36
+ get(key) {
37
+ return this.byKey.get(key);
38
+ }
39
+ getById(id) {
40
+ return this.byId.get(id);
41
+ }
42
+ add(state) {
43
+ this.byKey.set(SubscriptionRegistry.key(state.fn.__lunoraRef, state.args, state.shardKey), state);
44
+ this.byId.set(state.id, state);
45
+ }
46
+ remove(state) {
47
+ this.byKey.delete(SubscriptionRegistry.key(state.fn.__lunoraRef, state.args, state.shardKey));
48
+ this.byId.delete(state.id);
49
+ }
50
+ all() {
51
+ return [...this.byKey.values()];
52
+ }
53
+ }
54
+
55
+ export { SubscriptionRegistry as S, stableStringify as s };
@@ -0,0 +1,82 @@
1
+ /**
2
+ * `@lunora/client/pagination` — the framework-agnostic pagination state machine
3
+ * shared by every Lunora UI adapter (React, Vue, Svelte, Solid).
4
+ *
5
+ * Owns cursor tracking, page-size rebalancing (split/join), `initialPages`,
6
+ * `rebalance`, and the shared types (`Page`, `PaginationResult`,
7
+ * `PaginationStatus`, `PaginatedCoreResult`). Nothing here imports a UI
8
+ * framework — each adapter wires the pure functions into its own reactive
9
+ * primitives.
10
+ */
11
+ /** Grow factor: a bounded page is split when it exceeds this multiple of its target size. */
12
+ declare const SPLIT_FACTOR = 2;
13
+ /** Shrink factor: a bounded page with a neighbour is joined when it falls below this multiple of its target size. */
14
+ declare const JOIN_FACTOR = .5;
15
+ /** A loaded page: a fixed `(lower, upper]` range plus the size it targets. */
16
+ interface Page {
17
+ lower: null | string;
18
+ numItems: number;
19
+ upper: null | string;
20
+ }
21
+ /** One page returned by a paginated query — the shape `.paginate()` yields. */
22
+ interface PaginationResult<T = unknown> {
23
+ continueCursor: null | string;
24
+ isDone: boolean;
25
+ page: T[];
26
+ /**
27
+ * Reactive-pagination only: the midpoint cursor of a bounded
28
+ * `(cursor, endCursor]` page, used to split an over-grown page into two
29
+ * adjacent ranges. Absent on legacy (open-ended) pages.
30
+ */
31
+ splitCursor?: null | string;
32
+ }
33
+ /**
34
+ * Lifecycle of a `usePaginatedQuery` feed.
35
+ *
36
+ * - `LoadingFirstPage` — the first page is in flight; `results` is empty.
37
+ * - `CanLoadMore` — the loaded tail has a cursor; calling `loadMore` fetches the next page.
38
+ * - `LoadingMore` — a `loadMore` page is in flight; earlier results stay visible.
39
+ * - `Exhausted` — every page has loaded and the server reported `isDone`.
40
+ */
41
+ type PaginationStatus = "CanLoadMore" | "Exhausted" | "LoadingFirstPage" | "LoadingMore";
42
+ interface PaginatedCoreResult<T> {
43
+ /** Request another page off the open-ended tail. A no-op unless `status === "CanLoadMore"`. */
44
+ loadMore: (numberItems: number) => void;
45
+ /** Per-page resolved results in order; entries are `undefined` until a page resolves. */
46
+ pageResults: (PaginationResult<T> | undefined)[];
47
+ status: PaginationStatus;
48
+ }
49
+ /** First-page seed: a single open-ended range starting at the feed head. */
50
+ declare const initialPages: (numberItems: number) => Page[];
51
+ /**
52
+ * Run the SPLIT/JOIN maintenance pass over the current page list given freshly
53
+ * resolved results. Returns a new page list when a boundary changed, or
54
+ * `undefined` when the layout is already balanced (so the caller can skip a
55
+ * setState).
56
+ *
57
+ * Only ONE structural edit is applied per pass (the first split or join found),
58
+ * letting the subsequent re-render's resolved results drive the next pass — this
59
+ * keeps each transition observable and avoids reasoning about several
60
+ * simultaneous boundary moves.
61
+ */
62
+ declare const rebalance: (pages: Page[], results: (PaginationResult | undefined)[]) => Page[] | undefined;
63
+ /**
64
+ * Derive the feed `status` and the next-page cursor from the current page list
65
+ * and resolved page results. Framework adapters call this each render/effect to
66
+ * compute what to expose to callers.
67
+ */
68
+ declare const derivePaginationStatus: <T>(skipped: boolean, pageResults: (PaginationResult<T> | undefined)[]) => {
69
+ nextCursor: null | string | undefined;
70
+ status: PaginationStatus;
71
+ };
72
+ /**
73
+ * Apply a `loadMore` to the current page list. Pins the open-ended tail at
74
+ * `cursor` (making it a fixed bounded range) and appends a fresh open-ended
75
+ * page starting at `cursor`. The shared boundary keeps the feed gap- and
76
+ * dup-free.
77
+ *
78
+ * Returns the new page list, or `undefined` when the given `cursor` is not
79
+ * valid (null or undefined — caller should no-op).
80
+ */
81
+ declare const applyLoadMore: (pages: Page[], cursor: null | string | undefined, numberItems: number) => Page[] | undefined;
82
+ export { JOIN_FACTOR, type Page, type PaginatedCoreResult, type PaginationResult, type PaginationStatus, SPLIT_FACTOR, applyLoadMore, derivePaginationStatus, initialPages, rebalance };
@@ -0,0 +1,82 @@
1
+ /**
2
+ * `@lunora/client/pagination` — the framework-agnostic pagination state machine
3
+ * shared by every Lunora UI adapter (React, Vue, Svelte, Solid).
4
+ *
5
+ * Owns cursor tracking, page-size rebalancing (split/join), `initialPages`,
6
+ * `rebalance`, and the shared types (`Page`, `PaginationResult`,
7
+ * `PaginationStatus`, `PaginatedCoreResult`). Nothing here imports a UI
8
+ * framework — each adapter wires the pure functions into its own reactive
9
+ * primitives.
10
+ */
11
+ /** Grow factor: a bounded page is split when it exceeds this multiple of its target size. */
12
+ declare const SPLIT_FACTOR = 2;
13
+ /** Shrink factor: a bounded page with a neighbour is joined when it falls below this multiple of its target size. */
14
+ declare const JOIN_FACTOR = .5;
15
+ /** A loaded page: a fixed `(lower, upper]` range plus the size it targets. */
16
+ interface Page {
17
+ lower: null | string;
18
+ numItems: number;
19
+ upper: null | string;
20
+ }
21
+ /** One page returned by a paginated query — the shape `.paginate()` yields. */
22
+ interface PaginationResult<T = unknown> {
23
+ continueCursor: null | string;
24
+ isDone: boolean;
25
+ page: T[];
26
+ /**
27
+ * Reactive-pagination only: the midpoint cursor of a bounded
28
+ * `(cursor, endCursor]` page, used to split an over-grown page into two
29
+ * adjacent ranges. Absent on legacy (open-ended) pages.
30
+ */
31
+ splitCursor?: null | string;
32
+ }
33
+ /**
34
+ * Lifecycle of a `usePaginatedQuery` feed.
35
+ *
36
+ * - `LoadingFirstPage` — the first page is in flight; `results` is empty.
37
+ * - `CanLoadMore` — the loaded tail has a cursor; calling `loadMore` fetches the next page.
38
+ * - `LoadingMore` — a `loadMore` page is in flight; earlier results stay visible.
39
+ * - `Exhausted` — every page has loaded and the server reported `isDone`.
40
+ */
41
+ type PaginationStatus = "CanLoadMore" | "Exhausted" | "LoadingFirstPage" | "LoadingMore";
42
+ interface PaginatedCoreResult<T> {
43
+ /** Request another page off the open-ended tail. A no-op unless `status === "CanLoadMore"`. */
44
+ loadMore: (numberItems: number) => void;
45
+ /** Per-page resolved results in order; entries are `undefined` until a page resolves. */
46
+ pageResults: (PaginationResult<T> | undefined)[];
47
+ status: PaginationStatus;
48
+ }
49
+ /** First-page seed: a single open-ended range starting at the feed head. */
50
+ declare const initialPages: (numberItems: number) => Page[];
51
+ /**
52
+ * Run the SPLIT/JOIN maintenance pass over the current page list given freshly
53
+ * resolved results. Returns a new page list when a boundary changed, or
54
+ * `undefined` when the layout is already balanced (so the caller can skip a
55
+ * setState).
56
+ *
57
+ * Only ONE structural edit is applied per pass (the first split or join found),
58
+ * letting the subsequent re-render's resolved results drive the next pass — this
59
+ * keeps each transition observable and avoids reasoning about several
60
+ * simultaneous boundary moves.
61
+ */
62
+ declare const rebalance: (pages: Page[], results: (PaginationResult | undefined)[]) => Page[] | undefined;
63
+ /**
64
+ * Derive the feed `status` and the next-page cursor from the current page list
65
+ * and resolved page results. Framework adapters call this each render/effect to
66
+ * compute what to expose to callers.
67
+ */
68
+ declare const derivePaginationStatus: <T>(skipped: boolean, pageResults: (PaginationResult<T> | undefined)[]) => {
69
+ nextCursor: null | string | undefined;
70
+ status: PaginationStatus;
71
+ };
72
+ /**
73
+ * Apply a `loadMore` to the current page list. Pins the open-ended tail at
74
+ * `cursor` (making it a fixed bounded range) and appends a fresh open-ended
75
+ * page starting at `cursor`. The shared boundary keeps the feed gap- and
76
+ * dup-free.
77
+ *
78
+ * Returns the new page list, or `undefined` when the given `cursor` is not
79
+ * valid (null or undefined — caller should no-op).
80
+ */
81
+ declare const applyLoadMore: (pages: Page[], cursor: null | string | undefined, numberItems: number) => Page[] | undefined;
82
+ export { JOIN_FACTOR, type Page, type PaginatedCoreResult, type PaginationResult, type PaginationStatus, SPLIT_FACTOR, applyLoadMore, derivePaginationStatus, initialPages, rebalance };
@@ -0,0 +1,61 @@
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 };
@@ -0,0 +1,62 @@
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-B5vWSgvD.mjs";
2
+ export type { b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-B5vWSgvD.mjs";
3
+ import '@lunora/runtime';
4
+ /**
5
+ * The sentinel a framework adapter resolves its reactive args to when it wants
6
+ * to short-circuit a query — no network call, no socket.
7
+ */
8
+ declare const SKIP: "skip";
9
+ /** Args after a framework has resolved its reactivity primitive, or the skip sentinel. */
10
+ type ResolvedArgs<F extends FunctionReference> = ArgsOf<F> | typeof SKIP;
11
+ /**
12
+ * The framework-neutral sinks a {@link createQuerySubscription} call drives. A
13
+ * framework adapter supplies these, wiring each into its own reactivity
14
+ * primitive (a TanStack cache write, a Vue `ref`, a Svelte store `set`, a Solid
15
+ * signal setter).
16
+ *
17
+ * `onData` fires when a fresh server value lands (the initial frame or a delta).
18
+ * `onError` fires when the subscription attach threw, or the server pushed a
19
+ * subscription-scoped error — it is optional, and when omitted an attach throw
20
+ * propagates to the caller (preserving the "no error channel" behaviour of
21
+ * adapters like Solid/Vue that never had one) rather than being swallowed.
22
+ * `onReset` fires when the resolved args are `"skip"`: clear any prior value.
23
+ */
24
+ interface QuerySubscriptionSinks<T> {
25
+ onData: (value: T) => void;
26
+ onError?: (error: SubscriptionError) => void;
27
+ onReset?: () => void;
28
+ }
29
+ interface QuerySubscriptionOptions {
30
+ /** Route to a specific shard when the target function is `.shardBy(...)`-partitioned. */
31
+ shardKey?: string;
32
+ }
33
+ /** Normalise an unknown thrown value into the client's {@link SubscriptionError} shape. */
34
+ declare const toSubscriptionError: (error: unknown) => SubscriptionError;
35
+ /**
36
+ * The subscribe → snapshot → error/reset → cleanup state machine shared by
37
+ * every Lunora framework adapter's live-query hook.
38
+ *
39
+ * Given a `client`, a function reference, the already-resolved `args` (a
40
+ * framework reads its own reactive source first, then hands the plain value in),
41
+ * and a set of {@link QuerySubscriptionSinks}, this opens one `client.subscribe`
42
+ * registration and returns the {@link Unsubscribe} to tear it down. Each
43
+ * framework owns *when* to call this (a React effect, a Vue `watch`, a Svelte
44
+ * store start callback, a Solid `createEffect(on(...))`) and *where* to stash
45
+ * the value — this owns the lifecycle in between, so the skip-handling, the
46
+ * value/error fan-out, the attach-throw normalisation, and the
47
+ * cancellation-guarded teardown live in exactly one place.
48
+ *
49
+ * Behaviour. When `args === "skip"` it calls `sinks.onReset?.()` and returns a
50
+ * no-op teardown; no `client.subscribe` is issued. Otherwise it opens
51
+ * `client.subscribe(fn, args, …, { shardKey, onError })`: server pushes route to
52
+ * `sinks.onData`, and the client's own `onError` channel (a server-rejected
53
+ * subscription) routes to `sinks.onError` when present. The attach is wrapped —
54
+ * if `client.subscribe` itself throws, the error is normalised to a
55
+ * {@link SubscriptionError} and delivered to `sinks.onError` when present; with
56
+ * no `onError` sink the throw is rethrown so adapters without an error channel
57
+ * behave exactly as before. The returned teardown is idempotent and
58
+ * cancellation-guarded: once it runs, no further `onData`/`onError` from an
59
+ * in-flight push reaches the sinks.
60
+ */
61
+ declare const createQuerySubscription: <F extends FunctionReference, T = ReturnOf<F>>(client: LunoraClient, function_: F, args: ResolvedArgs<F>, sinks: QuerySubscriptionSinks<T>, options?: QuerySubscriptionOptions) => Unsubscribe;
62
+ export { type ArgsOf, type FunctionReference, type QuerySubscriptionOptions, type QuerySubscriptionSinks, type ResolvedArgs, type ReturnOf, SKIP, type SubscriptionError, type Unsubscribe, createQuerySubscription, toSubscriptionError };
@@ -0,0 +1,62 @@
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-B5vWSgvD.js";
2
+ export type { b as SubscriptionErrorCallback } from "../packem_shared/lunora-client.d-B5vWSgvD.js";
3
+ import '@lunora/runtime';
4
+ /**
5
+ * The sentinel a framework adapter resolves its reactive args to when it wants
6
+ * to short-circuit a query — no network call, no socket.
7
+ */
8
+ declare const SKIP: "skip";
9
+ /** Args after a framework has resolved its reactivity primitive, or the skip sentinel. */
10
+ type ResolvedArgs<F extends FunctionReference> = ArgsOf<F> | typeof SKIP;
11
+ /**
12
+ * The framework-neutral sinks a {@link createQuerySubscription} call drives. A
13
+ * framework adapter supplies these, wiring each into its own reactivity
14
+ * primitive (a TanStack cache write, a Vue `ref`, a Svelte store `set`, a Solid
15
+ * signal setter).
16
+ *
17
+ * `onData` fires when a fresh server value lands (the initial frame or a delta).
18
+ * `onError` fires when the subscription attach threw, or the server pushed a
19
+ * subscription-scoped error — it is optional, and when omitted an attach throw
20
+ * propagates to the caller (preserving the "no error channel" behaviour of
21
+ * adapters like Solid/Vue that never had one) rather than being swallowed.
22
+ * `onReset` fires when the resolved args are `"skip"`: clear any prior value.
23
+ */
24
+ interface QuerySubscriptionSinks<T> {
25
+ onData: (value: T) => void;
26
+ onError?: (error: SubscriptionError) => void;
27
+ onReset?: () => void;
28
+ }
29
+ interface QuerySubscriptionOptions {
30
+ /** Route to a specific shard when the target function is `.shardBy(...)`-partitioned. */
31
+ shardKey?: string;
32
+ }
33
+ /** Normalise an unknown thrown value into the client's {@link SubscriptionError} shape. */
34
+ declare const toSubscriptionError: (error: unknown) => SubscriptionError;
35
+ /**
36
+ * The subscribe → snapshot → error/reset → cleanup state machine shared by
37
+ * every Lunora framework adapter's live-query hook.
38
+ *
39
+ * Given a `client`, a function reference, the already-resolved `args` (a
40
+ * framework reads its own reactive source first, then hands the plain value in),
41
+ * and a set of {@link QuerySubscriptionSinks}, this opens one `client.subscribe`
42
+ * registration and returns the {@link Unsubscribe} to tear it down. Each
43
+ * framework owns *when* to call this (a React effect, a Vue `watch`, a Svelte
44
+ * store start callback, a Solid `createEffect(on(...))`) and *where* to stash
45
+ * the value — this owns the lifecycle in between, so the skip-handling, the
46
+ * value/error fan-out, the attach-throw normalisation, and the
47
+ * cancellation-guarded teardown live in exactly one place.
48
+ *
49
+ * Behaviour. When `args === "skip"` it calls `sinks.onReset?.()` and returns a
50
+ * no-op teardown; no `client.subscribe` is issued. Otherwise it opens
51
+ * `client.subscribe(fn, args, …, { shardKey, onError })`: server pushes route to
52
+ * `sinks.onData`, and the client's own `onError` channel (a server-rejected
53
+ * subscription) routes to `sinks.onError` when present. The attach is wrapped —
54
+ * if `client.subscribe` itself throws, the error is normalised to a
55
+ * {@link SubscriptionError} and delivered to `sinks.onError` when present; with
56
+ * no `onError` sink the throw is rethrown so adapters without an error channel
57
+ * behave exactly as before. The returned teardown is idempotent and
58
+ * cancellation-guarded: once it runs, no further `onData`/`onError` from an
59
+ * in-flight push reaches the sinks.
60
+ */
61
+ declare const createQuerySubscription: <F extends FunctionReference, T = ReturnOf<F>>(client: LunoraClient, function_: F, args: ResolvedArgs<F>, sinks: QuerySubscriptionSinks<T>, options?: QuerySubscriptionOptions) => Unsubscribe;
62
+ export { type ArgsOf, type FunctionReference, type QuerySubscriptionOptions, type QuerySubscriptionSinks, type ResolvedArgs, type ReturnOf, SKIP, type SubscriptionError, type Unsubscribe, createQuerySubscription, toSubscriptionError };
@@ -0,0 +1 @@
1
+ export { SKIP, createQuerySubscription, toSubscriptionError } from '../packem_shared/SKIP-vItZChkw.mjs';