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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +2 -0
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/index.d.mts +813 -175
  5. package/dist/index.d.ts +813 -175
  6. package/dist/index.mjs +18 -10
  7. package/dist/packem_shared/{AuthLoading-RMT5Q_eE.mjs → AuthLoading-u5QJoV-J.mjs} +1 -1
  8. package/dist/packem_shared/{LunoraContext-C9SpKj54.mjs → LunoraContext-C59PzHhN.mjs} +2 -1
  9. package/dist/packem_shared/{LunoraProvider-B5BJFk3K.mjs → LunoraProvider-CzB3zGhy.mjs} +1 -1
  10. package/dist/packem_shared/createAgent-D7EZBeql.mjs +55 -0
  11. package/dist/packem_shared/createAgentChat-Bq-wzSxv.mjs +166 -0
  12. package/dist/packem_shared/createAgentState-DckYu3G8.mjs +21 -0
  13. package/dist/packem_shared/createAgentToolEvents-UavTO16u.mjs +99 -0
  14. package/dist/packem_shared/{createConnectionStatus-D8GPatZX.mjs → createConnectionStatus-1poqwqR9.mjs} +1 -1
  15. package/dist/packem_shared/createFlag-DQoGdUMB.mjs +78 -0
  16. package/dist/packem_shared/{createInfiniteQuery-DyMvQ2Qy.mjs → createInfiniteQuery-CD2GT1_O.mjs} +148 -5
  17. package/dist/packem_shared/{createMutation-C7BxzO0y.mjs → createMutation-LkrbhItI.mjs} +1 -1
  18. package/dist/packem_shared/createMutator-foSnPJPt.mjs +24 -0
  19. package/dist/packem_shared/{createPresence-DiAak1Jw.mjs → createPresence-DM2cVkiG.mjs} +13 -6
  20. package/dist/packem_shared/{createQuery-D8mdHfyQ.mjs → createQuery-BUldvZXj.mjs} +1 -1
  21. package/dist/packem_shared/createStream-D9ONbGAw.mjs +70 -0
  22. package/dist/packem_shared/{createSubscription-BM2fw8hw.mjs → createSubscription-D3HbChGe.mjs} +4 -2
  23. package/dist/packem_shared/createVoiceAgent-hu59SaDl.mjs +418 -0
  24. package/dist/packem_shared/{hydratePreloaded-CaT1kDBH.mjs → hydratePreloaded-CWny5-2J.mjs} +1 -1
  25. package/dist/packem_shared/stable-key-DePnevIy.mjs +38 -0
  26. package/dist/upload.d.mts +2 -0
  27. package/dist/upload.d.ts +2 -0
  28. package/dist/upload.mjs +2 -0
  29. package/package.json +10 -4
package/dist/index.mjs CHANGED
@@ -1,11 +1,19 @@
1
- export { LunoraContext, useLunora } from './packem_shared/LunoraContext-C9SpKj54.mjs';
2
- export { AuthLoading, Authenticated, Unauthenticated, createAuth } from './packem_shared/AuthLoading-RMT5Q_eE.mjs';
3
- export { default as createConnectionStatus } from './packem_shared/createConnectionStatus-D8GPatZX.mjs';
4
- export { createMutation, createMutationForClient } from './packem_shared/createMutation-C7BxzO0y.mjs';
5
- export { createInfiniteQuery, createPaginatedQuery } from './packem_shared/createInfiniteQuery-DyMvQ2Qy.mjs';
6
- export { createPresence } from './packem_shared/createPresence-DiAak1Jw.mjs';
7
- export { createQuery } from './packem_shared/createQuery-D8mdHfyQ.mjs';
1
+ export { LunoraContext, useLunora } from './packem_shared/LunoraContext-C59PzHhN.mjs';
2
+ export { createAgent } from './packem_shared/createAgent-D7EZBeql.mjs';
3
+ export { createAgentChat } from './packem_shared/createAgentChat-Bq-wzSxv.mjs';
4
+ export { createAgentState } from './packem_shared/createAgentState-DckYu3G8.mjs';
5
+ export { createAgentToolEvents } from './packem_shared/createAgentToolEvents-UavTO16u.mjs';
6
+ export { AuthLoading, Authenticated, Unauthenticated, createAuth } from './packem_shared/AuthLoading-u5QJoV-J.mjs';
7
+ export { default as createConnectionStatus } from './packem_shared/createConnectionStatus-1poqwqR9.mjs';
8
+ export { createFlag, createFlags } from './packem_shared/createFlag-DQoGdUMB.mjs';
9
+ export { createMutation, createMutationForClient } from './packem_shared/createMutation-LkrbhItI.mjs';
10
+ export { createMutator } from './packem_shared/createMutator-foSnPJPt.mjs';
11
+ export { createInfiniteQuery, createPaginatedQuery } from './packem_shared/createInfiniteQuery-CD2GT1_O.mjs';
12
+ export { createPresence } from './packem_shared/createPresence-DM2cVkiG.mjs';
13
+ export { createQuery } from './packem_shared/createQuery-BUldvZXj.mjs';
8
14
  export { createRateLimit } from './packem_shared/createRateLimit-BA2f8XyF.mjs';
9
- export { createSubscription } from './packem_shared/createSubscription-BM2fw8hw.mjs';
10
- export { default as hydratePreloaded } from './packem_shared/hydratePreloaded-CaT1kDBH.mjs';
11
- export { LunoraProvider } from './packem_shared/LunoraProvider-B5BJFk3K.mjs';
15
+ export { createStream } from './packem_shared/createStream-D9ONbGAw.mjs';
16
+ export { createSubscription } from './packem_shared/createSubscription-D3HbChGe.mjs';
17
+ export { createVoiceAgent } from './packem_shared/createVoiceAgent-hu59SaDl.mjs';
18
+ export { default as hydratePreloaded } from './packem_shared/hydratePreloaded-CWny5-2J.mjs';
19
+ export { LunoraProvider } from './packem_shared/LunoraProvider-CzB3zGhy.mjs';
@@ -1,7 +1,7 @@
1
1
  import { createComponent, memo } from 'solid-js/web';
2
2
  import { getIdentityStore } from '@lunora/client/auth';
3
3
  import { Show, createSignal, onCleanup } from 'solid-js';
4
- import { useLunora } from './LunoraContext-C9SpKj54.mjs';
4
+ import { useLunora } from './LunoraContext-C59PzHhN.mjs';
5
5
 
6
6
  const createAuth = () => {
7
7
  const client = useLunora();
@@ -1,10 +1,11 @@
1
+ import { LunoraError } from '@lunora/errors';
1
2
  import { createContext, useContext } from 'solid-js';
2
3
 
3
4
  const LunoraContext = createContext();
4
5
  const useLunora = () => {
5
6
  const client = useContext(LunoraContext);
6
7
  if (!client) {
7
- throw new Error("useLunora must be used inside <LunoraProvider />");
8
+ throw new LunoraError("INTERNAL", "useLunora must be used inside <LunoraProvider />");
8
9
  }
9
10
  return client;
10
11
  };
@@ -1,5 +1,5 @@
1
1
  import { createComponent } from 'solid-js/web';
2
- import { LunoraContext } from './LunoraContext-C9SpKj54.mjs';
2
+ import { LunoraContext } from './LunoraContext-C59PzHhN.mjs';
3
3
 
4
4
  const LunoraProvider = (props) => (
5
5
  // `props.client` is read lazily inside the JSX so Solid tracks it: swapping
@@ -0,0 +1,55 @@
1
+ import { createMemo } from 'solid-js';
2
+ import { createMutation } from './createMutation-LkrbhItI.mjs';
3
+ import { createSubscription } from './createSubscription-D3HbChGe.mjs';
4
+
5
+ const NO_MUTATION_REF = {
6
+ __lunoraRef: ""
7
+ };
8
+ const resolveMaybe = (value) => typeof value === "function" ? value() : value;
9
+ const createAgent = (options) => {
10
+ const {
11
+ api,
12
+ cancel: cancelReference,
13
+ run: runReference,
14
+ runArgs,
15
+ threadKey
16
+ } = options;
17
+ const runMutation = createMutation(runReference);
18
+ const cancelMutation = createMutation(cancelReference ?? NO_MUTATION_REF);
19
+ const {
20
+ data: threadData
21
+ } = createSubscription(api.agents.agentThread, () => {
22
+ return {
23
+ key: resolveMaybe(threadKey)
24
+ };
25
+ });
26
+ const thread = createMemo(() => threadData());
27
+ const status = createMemo(() => thread()?.status);
28
+ const run = async (input, arguments_) => {
29
+ await runMutation.mutate({
30
+ input,
31
+ threadKey: resolveMaybe(threadKey),
32
+ ...runArgs,
33
+ ...arguments_
34
+ });
35
+ };
36
+ const cancel = async () => {
37
+ const instanceId = thread()?.instanceId;
38
+ if (cancelReference === void 0 || instanceId === void 0) {
39
+ return;
40
+ }
41
+ await cancelMutation.mutate({
42
+ instanceId,
43
+ threadKey: resolveMaybe(threadKey)
44
+ });
45
+ };
46
+ return {
47
+ cancel,
48
+ pending: runMutation.pending,
49
+ run,
50
+ status,
51
+ thread
52
+ };
53
+ };
54
+
55
+ export { NO_MUTATION_REF, createAgent, resolveMaybe };
@@ -0,0 +1,166 @@
1
+ import { createSignal, createMemo } from 'solid-js';
2
+ import { resolveMaybe, NO_MUTATION_REF } from './createAgent-D7EZBeql.mjs';
3
+ import { createMutation } from './createMutation-LkrbhItI.mjs';
4
+ import { createStream } from './createStream-D9ONbGAw.mjs';
5
+ import { createSubscription } from './createSubscription-D3HbChGe.mjs';
6
+
7
+ const NO_STREAM_REF = {
8
+ __lunoraRef: ""
9
+ };
10
+ const reconcileOptimistic = (optimistic, durable) => {
11
+ const durableUserRows = durable.filter((message) => message.role === "user");
12
+ const consumed = /* @__PURE__ */ new Set();
13
+ return optimistic.filter((pending) => {
14
+ for (let index = pending.durableUserCountAtSend; index < durableUserRows.length; index += 1) {
15
+ const row = durableUserRows[index];
16
+ if (row !== void 0 && !consumed.has(index) && row.content === pending.content) {
17
+ consumed.add(index);
18
+ return false;
19
+ }
20
+ }
21
+ return true;
22
+ });
23
+ };
24
+ const createAgentChat = (options) => {
25
+ const {
26
+ api,
27
+ cancel: cancelReference,
28
+ limit,
29
+ send: sendReference,
30
+ sendArgs,
31
+ stream: streamReference,
32
+ threadKey
33
+ } = options;
34
+ const {
35
+ data: history
36
+ } = createSubscription(api.agents.agentMessages, () => {
37
+ const key = resolveMaybe(threadKey);
38
+ return limit === void 0 ? {
39
+ key
40
+ } : {
41
+ key,
42
+ limit
43
+ };
44
+ });
45
+ const {
46
+ data: threadData
47
+ } = createSubscription(api.agents.agentThread, () => {
48
+ return {
49
+ key: resolveMaybe(threadKey)
50
+ };
51
+ });
52
+ const streamArguments = streamReference === void 0 ? "skip" : () => {
53
+ return {
54
+ key: resolveMaybe(threadKey)
55
+ };
56
+ };
57
+ const {
58
+ chunks
59
+ } = createStream(streamReference ?? NO_STREAM_REF, streamArguments);
60
+ const sendMutation = createMutation(sendReference);
61
+ const cancelMutation = createMutation(cancelReference ?? NO_MUTATION_REF);
62
+ const approvalMutation = createMutation(api.agents.agentResolveApproval);
63
+ const [optimistic, setOptimistic] = createSignal([]);
64
+ let nextId = 0;
65
+ const thread = createMemo(() => threadData());
66
+ const status = createMemo(() => thread()?.status);
67
+ const durable = createMemo(() => history() ?? []);
68
+ const messages = createMemo(() => {
69
+ const rows = durable();
70
+ const visible = reconcileOptimistic(optimistic(), rows);
71
+ if (visible.length === 0) {
72
+ return rows;
73
+ }
74
+ let maxDurableSeq = -1;
75
+ for (const message of rows) {
76
+ if (message.seq > maxDurableSeq) {
77
+ maxDurableSeq = message.seq;
78
+ }
79
+ }
80
+ return [...rows, ...visible.map((pending, index) => {
81
+ return {
82
+ content: pending.content,
83
+ optimistic: true,
84
+ role: "user",
85
+ seq: maxDurableSeq + 1 + index
86
+ };
87
+ })];
88
+ });
89
+ const streamingText = createMemo(() => {
90
+ const key = resolveMaybe(threadKey);
91
+ const assistantCount = durable().filter((message) => message.role === "assistant").length;
92
+ return chunks().filter((event) => event.kind !== "progress" && event.threadKey === key && event.turn >= assistantCount).map((delta) => delta.text).join("");
93
+ });
94
+ const send = async (input, arguments_) => {
95
+ const id = nextId;
96
+ nextId += 1;
97
+ const durableUserCountAtSend = durable().filter((message) => message.role === "user").length;
98
+ setOptimistic((previous) => [...reconcileOptimistic(previous, durable()), {
99
+ content: input,
100
+ durableUserCountAtSend,
101
+ id
102
+ }]);
103
+ try {
104
+ await sendMutation.mutate({
105
+ input,
106
+ threadKey: resolveMaybe(threadKey),
107
+ ...sendArgs,
108
+ ...arguments_
109
+ });
110
+ } catch (error) {
111
+ setOptimistic((previous) => previous.filter((pending) => pending.id !== id));
112
+ throw error;
113
+ }
114
+ };
115
+ const approve = async (toolCallId, note) => {
116
+ const instanceId = thread()?.instanceId;
117
+ if (instanceId === void 0) {
118
+ throw new Error("createAgentChat: cannot approve — no in-flight run (thread has no instanceId)");
119
+ }
120
+ await approvalMutation.mutate({
121
+ decision: "approve",
122
+ instanceId,
123
+ threadKey: resolveMaybe(threadKey),
124
+ toolCallId,
125
+ ...note === void 0 ? {} : {
126
+ note
127
+ }
128
+ });
129
+ };
130
+ const reject = async (toolCallId, note) => {
131
+ const instanceId = thread()?.instanceId;
132
+ if (instanceId === void 0) {
133
+ throw new Error("createAgentChat: cannot reject — no in-flight run (thread has no instanceId)");
134
+ }
135
+ await approvalMutation.mutate({
136
+ decision: "reject",
137
+ instanceId,
138
+ threadKey: resolveMaybe(threadKey),
139
+ toolCallId,
140
+ ...note === void 0 ? {} : {
141
+ note
142
+ }
143
+ });
144
+ };
145
+ const cancel = async () => {
146
+ const instanceId = thread()?.instanceId;
147
+ if (cancelReference === void 0 || instanceId === void 0) {
148
+ return;
149
+ }
150
+ await cancelMutation.mutate({
151
+ instanceId,
152
+ threadKey: resolveMaybe(threadKey)
153
+ });
154
+ };
155
+ return {
156
+ approve,
157
+ cancel,
158
+ messages,
159
+ reject,
160
+ send,
161
+ status,
162
+ streamingText
163
+ };
164
+ };
165
+
166
+ export { createAgentChat };
@@ -0,0 +1,21 @@
1
+ import { createMemo } from 'solid-js';
2
+ import { resolveMaybe } from './createAgent-D7EZBeql.mjs';
3
+ import { createSubscription } from './createSubscription-D3HbChGe.mjs';
4
+
5
+ const createAgentState = (options) => {
6
+ const {
7
+ data,
8
+ error
9
+ } = createSubscription(options.api.agents.agentState, () => {
10
+ return {
11
+ key: resolveMaybe(options.threadKey)
12
+ };
13
+ });
14
+ const state = createMemo(() => data());
15
+ return {
16
+ error,
17
+ state
18
+ };
19
+ };
20
+
21
+ export { createAgentState };
@@ -0,0 +1,99 @@
1
+ import { createMemo } from 'solid-js';
2
+ import { resolveMaybe } from './createAgent-D7EZBeql.mjs';
3
+ import { createStream } from './createStream-D9ONbGAw.mjs';
4
+ import { createSubscription } from './createSubscription-D3HbChGe.mjs';
5
+
6
+ const NO_STREAM_REF = {
7
+ __lunoraRef: ""
8
+ };
9
+ const EMPTY_MESSAGES = [];
10
+ const toDurableEvent = (message) => {
11
+ if (message.role === "assistant" && message.toolCalls) {
12
+ return message.toolCalls.map((call) => {
13
+ return {
14
+ input: call.input,
15
+ seq: message.seq,
16
+ toolCallId: call.id,
17
+ toolName: call.name,
18
+ type: "call"
19
+ };
20
+ });
21
+ }
22
+ if (message.role !== "tool") {
23
+ return void 0;
24
+ }
25
+ if (message.status === "awaiting_approval") {
26
+ return [{
27
+ seq: message.seq,
28
+ type: "awaiting-approval",
29
+ ...message.toolCallId === void 0 ? {} : {
30
+ toolCallId: message.toolCallId
31
+ },
32
+ ...message.toolName === void 0 ? {} : {
33
+ toolName: message.toolName
34
+ }
35
+ }];
36
+ }
37
+ return [{
38
+ output: message.content,
39
+ seq: message.seq,
40
+ type: "result",
41
+ ...message.status === "approved" || message.status === "rejected" ? {
42
+ status: message.status
43
+ } : {},
44
+ ...message.toolCallId === void 0 ? {} : {
45
+ toolCallId: message.toolCallId
46
+ },
47
+ ...message.toolName === void 0 ? {} : {
48
+ toolName: message.toolName
49
+ }
50
+ }];
51
+ };
52
+ const createAgentToolEvents = (options) => {
53
+ const {
54
+ api,
55
+ limit,
56
+ stream: streamReference,
57
+ threadKey
58
+ } = options;
59
+ const messagesArguments = () => {
60
+ const key = resolveMaybe(threadKey);
61
+ return limit === void 0 ? {
62
+ key
63
+ } : {
64
+ key,
65
+ limit
66
+ };
67
+ };
68
+ const {
69
+ data: history
70
+ } = createSubscription(api.agents.agentMessages, messagesArguments);
71
+ const streamArguments = streamReference === void 0 ? "skip" : () => {
72
+ return {
73
+ key: resolveMaybe(threadKey)
74
+ };
75
+ };
76
+ const {
77
+ chunks
78
+ } = createStream(streamReference ?? NO_STREAM_REF, streamArguments);
79
+ const events = createMemo(() => {
80
+ const key = resolveMaybe(threadKey);
81
+ const durable = history() ?? EMPTY_MESSAGES;
82
+ const derived = durable.flatMap((message) => toDurableEvent(message) ?? []);
83
+ for (const event of chunks()) {
84
+ if (event.kind === "progress" && event.threadKey === key) {
85
+ derived.push({
86
+ data: event.data,
87
+ toolCallId: event.toolCallId,
88
+ type: "progress"
89
+ });
90
+ }
91
+ }
92
+ return derived;
93
+ });
94
+ return {
95
+ events
96
+ };
97
+ };
98
+
99
+ export { createAgentToolEvents };
@@ -1,5 +1,5 @@
1
1
  import { createSignal, onCleanup } from 'solid-js';
2
- import { useLunora } from './LunoraContext-C9SpKj54.mjs';
2
+ import { useLunora } from './LunoraContext-C59PzHhN.mjs';
3
3
 
4
4
  const createConnectionStatus = () => {
5
5
  const client = useLunora();
@@ -0,0 +1,78 @@
1
+ import { createSignal, createEffect, on, onCleanup } from 'solid-js';
2
+ import { s as stableStringify } from './stable-key-DePnevIy.mjs';
3
+ import { useLunora } from './LunoraContext-C59PzHhN.mjs';
4
+
5
+ const FLAGS_EVAL_PATH = "__lunora_flags__:eval";
6
+ const flagKind = (value) => {
7
+ const kind = typeof value;
8
+ if (kind === "boolean" || kind === "number" || kind === "string") {
9
+ return kind;
10
+ }
11
+ return "object";
12
+ };
13
+ const flagsReference = {
14
+ __lunoraRef: FLAGS_EVAL_PATH
15
+ };
16
+ const resolveMaybe = (value) => typeof value === "function" ? value() : value;
17
+ const serializeContext = (context) => context === void 0 ? "" : stableStringify(context);
18
+ const createFlag = (key, defaultValue, context) => {
19
+ const client = useLunora();
20
+ const type = flagKind(defaultValue);
21
+ const [value, setValue] = createSignal(defaultValue);
22
+ createEffect(on(() => `${resolveMaybe(key)} ${serializeContext(resolveMaybe(context))}`, () => {
23
+ const currentKey = resolveMaybe(key);
24
+ const currentContext = resolveMaybe(context);
25
+ setValue(() => defaultValue);
26
+ let unsubscribe;
27
+ try {
28
+ unsubscribe = client.subscribe(flagsReference, {
29
+ context: currentContext,
30
+ default: defaultValue,
31
+ key: currentKey,
32
+ type
33
+ }, (next) => {
34
+ setValue(() => next);
35
+ });
36
+ } catch {
37
+ return;
38
+ }
39
+ onCleanup(unsubscribe);
40
+ }));
41
+ return value;
42
+ };
43
+ const createFlags = (flags, context) => {
44
+ const client = useLunora();
45
+ const [values, setValues] = createSignal(flags);
46
+ const spec = stableStringify(flags);
47
+ createEffect(on(() => `${spec} ${serializeContext(resolveMaybe(context))}`, () => {
48
+ const currentContext = resolveMaybe(context);
49
+ setValues(() => flags);
50
+ const unsubscribes = [];
51
+ for (const [key, defaultValue] of Object.entries(flags)) {
52
+ try {
53
+ unsubscribes.push(client.subscribe(flagsReference, {
54
+ context: currentContext,
55
+ default: defaultValue,
56
+ key,
57
+ type: flagKind(defaultValue)
58
+ }, (next) => {
59
+ setValues((previous) => {
60
+ return {
61
+ ...previous,
62
+ [key]: next
63
+ };
64
+ });
65
+ }));
66
+ } catch {
67
+ }
68
+ }
69
+ onCleanup(() => {
70
+ for (const unsubscribe of unsubscribes) {
71
+ unsubscribe();
72
+ }
73
+ });
74
+ }));
75
+ return values;
76
+ };
77
+
78
+ export { createFlag, createFlags };
@@ -1,6 +1,105 @@
1
- import { initialPages, derivePaginationStatus, rebalance, applyLoadMore } from '@lunora/client/pagination';
1
+ import { initialPages, derivePaginationStatus, applyLoadMore, rebalance } from '@lunora/client/pagination';
2
2
  import { createMemo, createSignal, createEffect, on, onCleanup } from 'solid-js';
3
- import { useLunora } from './LunoraContext-C9SpKj54.mjs';
3
+ import { s as stableStringify } from './stable-key-DePnevIy.mjs';
4
+ import { useLunora } from './LunoraContext-C59PzHhN.mjs';
5
+
6
+ const toBase64 = (bytes) => {
7
+ let binary = "";
8
+ const chunk = 32768;
9
+ for (let index = 0; index < bytes.length; index += chunk) {
10
+ binary += String.fromCharCode(...bytes.subarray(index, index + chunk));
11
+ }
12
+ return btoa(binary);
13
+ };
14
+
15
+ const TAG = "$lunora.wire$";
16
+ const MAX_DEPTH = 64;
17
+ const encodeWire = (value, depth = 0) => {
18
+ if (depth > MAX_DEPTH) {
19
+ throw new RangeError(`wire-codec: value nesting exceeds the ${MAX_DEPTH}-level limit`);
20
+ }
21
+ if (value === void 0) {
22
+ return [TAG, "undefined"];
23
+ }
24
+ if (value === null) {
25
+ return null;
26
+ }
27
+ const kind = typeof value;
28
+ if (kind === "bigint") {
29
+ return [TAG, "bigint", value.toString()];
30
+ }
31
+ if (kind === "number") {
32
+ const numeric = value;
33
+ if (Number.isNaN(numeric)) {
34
+ return [TAG, "nan"];
35
+ }
36
+ if (numeric === Infinity) {
37
+ return [TAG, "inf"];
38
+ }
39
+ if (numeric === -Infinity) {
40
+ return [TAG, "-inf"];
41
+ }
42
+ return numeric;
43
+ }
44
+ if (kind !== "object") {
45
+ return value;
46
+ }
47
+ if (value instanceof Date) {
48
+ return [TAG, "date", encodeWire(value.getTime(), depth + 1)];
49
+ }
50
+ if (value instanceof Error) {
51
+ const error = value;
52
+ const properties = {};
53
+ for (const key of Object.keys(error)) {
54
+ if (error[key] !== void 0) {
55
+ properties[key] = encodeWire(error[key], depth + 1);
56
+ }
57
+ }
58
+ const encodedError = [TAG, "error", error.name, error.message, properties];
59
+ if (error.cause !== void 0) {
60
+ encodedError.push(encodeWire(error.cause, depth + 1));
61
+ }
62
+ return encodedError;
63
+ }
64
+ if (value instanceof URL) {
65
+ return [TAG, "url", value.href];
66
+ }
67
+ if (value instanceof Map) {
68
+ return [TAG, "map", [...value.entries()].map(([k, v]) => [encodeWire(k, depth + 1), encodeWire(v, depth + 1)])];
69
+ }
70
+ if (value instanceof Set) {
71
+ return [TAG, "set", [...value].map((item) => encodeWire(item, depth + 1))];
72
+ }
73
+ if (value instanceof ArrayBuffer) {
74
+ return [TAG, "bytes", toBase64(new Uint8Array(value)), "ArrayBuffer"];
75
+ }
76
+ if (ArrayBuffer.isView(value)) {
77
+ const view = value;
78
+ const ctorName = view.constructor.name;
79
+ const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
80
+ return ctorName === "Uint8Array" ? [TAG, "bytes", toBase64(bytes)] : [TAG, "bytes", toBase64(bytes), ctorName];
81
+ }
82
+ if (Array.isArray(value)) {
83
+ const encoded = value.map((item) => encodeWire(item, depth + 1));
84
+ return encoded.length > 0 && encoded[0] === TAG ? [TAG, "arr", encoded] : encoded;
85
+ }
86
+ const proto = Object.getPrototypeOf(value);
87
+ if (proto !== null && proto !== Object.prototype) {
88
+ const name = value.constructor?.name ?? "value";
89
+ throw new TypeError(`wire-codec: cannot encode a ${name} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`);
90
+ }
91
+ const source = value;
92
+ const result = {};
93
+ for (const key of Object.keys(source)) {
94
+ const field = source[key];
95
+ if (field !== void 0) {
96
+ result[key] = encodeWire(field, depth + 1);
97
+ }
98
+ }
99
+ return result;
100
+ };
101
+
102
+ const stableWireKey = (value) => stableStringify(encodeWire(value));
4
103
 
5
104
  const buildPageArgs = (page, baseArgs) => {
6
105
  return {
@@ -12,7 +111,7 @@ const buildPageArgs = (page, baseArgs) => {
12
111
  }
13
112
  };
14
113
  };
15
- const buildPageKey = (functionPath, pageArgs) => `${functionPath}::${JSON.stringify(pageArgs)}`;
114
+ const buildPageKey = (functionPath, pageArgs) => `${functionPath}::${stableWireKey(pageArgs)}`;
16
115
  const createPaginatedCore = (function_, args, options) => {
17
116
  const client = useLunora();
18
117
  const {
@@ -32,7 +131,23 @@ const createPaginatedCore = (function_, args, options) => {
32
131
  });
33
132
  setPageResults(updated);
34
133
  };
35
- const syncSubscriptions = (currentPages, baseArgs) => {
134
+ const migrateResultsForRebalance = (oldPages, newPages, baseArgs) => {
135
+ const keyOf = (page) => buildPageKey(function_["__lunoraRef"], buildPageArgs(page, baseArgs));
136
+ for (const newPage of newPages) {
137
+ const newKey = keyOf(newPage);
138
+ if (resultsByKey.has(newKey)) {
139
+ continue;
140
+ }
141
+ const donor = oldPages.find((oldPage) => oldPage.lower === newPage.lower);
142
+ if (donor) {
143
+ const carried = resultsByKey.get(keyOf(donor));
144
+ if (carried) {
145
+ resultsByKey.set(newKey, carried);
146
+ }
147
+ }
148
+ }
149
+ };
150
+ const syncPass = (currentPages, baseArgs) => {
36
151
  const wantedKeys = /* @__PURE__ */ new Set();
37
152
  for (const page of currentPages) {
38
153
  wantedKeys.add(buildPageKey(function_["__lunoraRef"], buildPageArgs(page, baseArgs)));
@@ -42,6 +157,7 @@ const createPaginatedCore = (function_, args, options) => {
42
157
  unsub();
43
158
  activeSubs.delete(key);
44
159
  pendingPageKeys.delete(key);
160
+ resultsByKey.delete(key);
45
161
  }
46
162
  }
47
163
  for (const page of currentPages) {
@@ -60,8 +176,10 @@ const createPaginatedCore = (function_, args, options) => {
60
176
  }
61
177
  rebuildPageResults(pages(), currentArgs);
62
178
  if (pendingPageKeys.size === 0) {
63
- const next = rebalance(pages(), pageResults());
179
+ const latestPages = pages();
180
+ const next = rebalance(latestPages, pageResults());
64
181
  if (next) {
182
+ migrateResultsForRebalance(latestPages, next, currentArgs);
65
183
  setPages(next);
66
184
  }
67
185
  }
@@ -71,6 +189,31 @@ const createPaginatedCore = (function_, args, options) => {
71
189
  activeSubs.set(key, unsub);
72
190
  }
73
191
  };
192
+ let syncing = false;
193
+ let resyncRequested = false;
194
+ const syncSubscriptions = (currentPages, baseArgs) => {
195
+ if (syncing) {
196
+ resyncRequested = true;
197
+ return;
198
+ }
199
+ syncing = true;
200
+ try {
201
+ let pagesToSync = currentPages;
202
+ let argsToSync = baseArgs;
203
+ do {
204
+ resyncRequested = false;
205
+ syncPass(pagesToSync, argsToSync);
206
+ const latestArgs = resolveArgs();
207
+ if (latestArgs === "skip") {
208
+ break;
209
+ }
210
+ pagesToSync = pages();
211
+ argsToSync = latestArgs;
212
+ } while (resyncRequested);
213
+ } finally {
214
+ syncing = false;
215
+ }
216
+ };
74
217
  const teardownAll = () => {
75
218
  for (const unsub of activeSubs.values()) {
76
219
  unsub();