statewire 0.0.0-0 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -1
- package/dist/client/changes.d.ts +7 -0
- package/dist/client/changes.d.ts.map +1 -0
- package/dist/client/changes.js +25 -0
- package/dist/client/changes.js.map +1 -0
- package/dist/client/connection.d.ts +63 -0
- package/dist/client/connection.d.ts.map +1 -0
- package/dist/client/connection.js +211 -0
- package/dist/client/connection.js.map +1 -0
- package/dist/client/core.d.ts +14 -0
- package/dist/client/core.d.ts.map +1 -0
- package/dist/client/core.js +272 -0
- package/dist/client/core.js.map +1 -0
- package/dist/client/session.d.ts +71 -0
- package/dist/client/session.d.ts.map +1 -0
- package/dist/client/session.js +529 -0
- package/dist/client/session.js.map +1 -0
- package/dist/client/sessionStore.d.ts +16 -0
- package/dist/client/sessionStore.d.ts.map +1 -0
- package/dist/client/sessionStore.js +14 -0
- package/dist/client/sessionStore.js.map +1 -0
- package/dist/client/timing.d.ts +11 -0
- package/dist/client/timing.d.ts.map +1 -0
- package/dist/client/timing.js +15 -0
- package/dist/client/timing.js.map +1 -0
- package/dist/host/adapter.d.ts +8 -0
- package/dist/host/adapter.d.ts.map +1 -0
- package/dist/host/adapter.js +23 -0
- package/dist/host/adapter.js.map +1 -0
- package/dist/host/draft.d.ts +28 -0
- package/dist/host/draft.d.ts.map +1 -0
- package/dist/host/draft.js +211 -0
- package/dist/host/draft.js.map +1 -0
- package/dist/host/engine.d.ts +14 -0
- package/dist/host/engine.d.ts.map +1 -0
- package/dist/host/engine.js +17 -0
- package/dist/host/engine.js.map +1 -0
- package/dist/host/host.d.ts +62 -0
- package/dist/host/host.d.ts.map +1 -0
- package/dist/host/host.js +331 -0
- package/dist/host/host.js.map +1 -0
- package/dist/host/socket.d.ts +14 -0
- package/dist/host/socket.d.ts.map +1 -0
- package/dist/host/socket.js +459 -0
- package/dist/host/socket.js.map +1 -0
- package/dist/host-internal.d.ts +27 -0
- package/dist/host-internal.d.ts.map +1 -0
- package/dist/host-internal.js +3 -0
- package/dist/host.d.ts +44 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +4 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/statewire.d.ts +104 -0
- package/dist/statewire.d.ts.map +1 -0
- package/dist/statewire.js +53 -0
- package/dist/statewire.js.map +1 -0
- package/dist/transports/fake-sse.d.ts +12 -0
- package/dist/transports/fake-sse.d.ts.map +1 -0
- package/dist/transports/fake-sse.js +39 -0
- package/dist/transports/fake-sse.js.map +1 -0
- package/dist/transports/fixtures.d.ts +33 -0
- package/dist/transports/fixtures.d.ts.map +1 -0
- package/dist/transports/fixtures.js +50 -0
- package/dist/transports/fixtures.js.map +1 -0
- package/dist/transports/remote.d.ts +12 -0
- package/dist/transports/remote.d.ts.map +1 -0
- package/dist/transports/remote.js +21 -0
- package/dist/transports/remote.js.map +1 -0
- package/dist/transports/sse-parser.d.ts +5 -0
- package/dist/transports/sse-parser.d.ts.map +1 -0
- package/dist/transports/sse-parser.js +26 -0
- package/dist/transports/sse-parser.js.map +1 -0
- package/dist/transports/sse.d.ts +64 -0
- package/dist/transports/sse.d.ts.map +1 -0
- package/dist/transports/sse.js +137 -0
- package/dist/transports/sse.js.map +1 -0
- package/dist/transports/testing.d.ts +32 -0
- package/dist/transports/testing.d.ts.map +1 -0
- package/dist/transports/testing.js +94 -0
- package/dist/transports/testing.js.map +1 -0
- package/dist/transports/ws.d.ts +9 -0
- package/dist/transports/ws.d.ts.map +1 -0
- package/dist/transports/ws.js +169 -0
- package/dist/transports/ws.js.map +1 -0
- package/dist/types.d.ts +60 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +24 -0
- package/dist/types.js.map +1 -0
- package/dist/util/draftTraps.d.ts +6 -0
- package/dist/util/draftTraps.d.ts.map +1 -0
- package/dist/util/draftTraps.js +25 -0
- package/dist/util/draftTraps.js.map +1 -0
- package/dist/util/macrotask.d.ts +5 -0
- package/dist/util/macrotask.d.ts.map +1 -0
- package/dist/util/macrotask.js +25 -0
- package/dist/util/macrotask.js.map +1 -0
- package/dist/util/methodProxy.d.ts +5 -0
- package/dist/util/methodProxy.d.ts.map +1 -0
- package/dist/util/methodProxy.js +17 -0
- package/dist/util/methodProxy.js.map +1 -0
- package/dist/util/randomId.d.ts +5 -0
- package/dist/util/randomId.d.ts.map +1 -0
- package/dist/util/randomId.js +6 -0
- package/dist/util/randomId.js.map +1 -0
- package/dist/util/recordMutations.d.ts +10 -0
- package/dist/util/recordMutations.d.ts.map +1 -0
- package/dist/util/recordMutations.js +109 -0
- package/dist/util/recordMutations.js.map +1 -0
- package/dist/util/statePath.d.ts +14 -0
- package/dist/util/statePath.d.ts.map +1 -0
- package/dist/util/statePath.js +31 -0
- package/dist/util/statePath.js.map +1 -0
- package/dist/wire/meta.d.ts +27 -0
- package/dist/wire/meta.d.ts.map +1 -0
- package/dist/wire/meta.js +75 -0
- package/dist/wire/meta.js.map +1 -0
- package/dist/wire/ops.d.ts +19 -0
- package/dist/wire/ops.d.ts.map +1 -0
- package/dist/wire/ops.js +112 -0
- package/dist/wire/ops.js.map +1 -0
- package/package.json +52 -5
- package/src/client/changes.ts +38 -0
- package/src/client/connection.ts +301 -0
- package/src/client/core.ts +312 -0
- package/src/client/session.ts +696 -0
- package/src/client/sessionStore.ts +23 -0
- package/src/client/timing.ts +14 -0
- package/src/host/adapter.ts +33 -0
- package/src/host/draft.ts +323 -0
- package/src/host/engine.ts +13 -0
- package/src/host/host.ts +482 -0
- package/src/host/socket.ts +542 -0
- package/src/host-internal.ts +28 -0
- package/src/host.ts +61 -0
- package/src/index.ts +5 -0
- package/src/statewire.ts +200 -0
- package/src/transports/fake-sse.ts +51 -0
- package/src/transports/fixtures.ts +60 -0
- package/src/transports/remote.ts +30 -0
- package/src/transports/sse-parser.ts +24 -0
- package/src/transports/sse.ts +267 -0
- package/src/transports/testing.ts +123 -0
- package/src/transports/ws.ts +256 -0
- package/src/types.ts +88 -0
- package/src/util/draftTraps.ts +32 -0
- package/src/util/macrotask.ts +25 -0
- package/src/util/methodProxy.ts +16 -0
- package/src/util/randomId.ts +4 -0
- package/src/util/recordMutations.ts +0 -0
- package/src/util/statePath.ts +61 -0
- package/src/wire/meta.ts +101 -0
- package/src/wire/ops.ts +202 -0
- package/index.js +0 -1
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import type { ResourceElement } from "@assistant-ui/tap";
|
|
2
|
+
import type { StatewireEnvelope } from "../client/connection";
|
|
3
|
+
import { recordMutations } from "../util/recordMutations";
|
|
4
|
+
import { StatewireSSE } from "./sse";
|
|
5
|
+
import type { Statewire } from "../types";
|
|
6
|
+
import { openSSEStream, sseFrame } from "./fake-sse";
|
|
7
|
+
import type { FakeStreamHandle } from "./fake-sse";
|
|
8
|
+
|
|
9
|
+
export * from "./fixtures";
|
|
10
|
+
|
|
11
|
+
/** Let queued microtasks and op batches drain through the statewire client. */
|
|
12
|
+
export const tick = () => new Promise<void>((r) => setTimeout(r, 0));
|
|
13
|
+
|
|
14
|
+
/** Run a mutator against a recording draft, as the client does for `optimistic`. */
|
|
15
|
+
export const applyOptimistic = <TState>(
|
|
16
|
+
state: TState,
|
|
17
|
+
mutate: (draft: TState) => void,
|
|
18
|
+
): TState => recordMutations(state, mutate).state;
|
|
19
|
+
|
|
20
|
+
export type MockTransport<TState> = {
|
|
21
|
+
/** Pass as the `transport:` option of useStatewire / Harness. */
|
|
22
|
+
transport: ResourceElement<Statewire<TState | undefined, any, any>>;
|
|
23
|
+
/** Captured `{ method, params }` command bodies, in POST order. */
|
|
24
|
+
commands: { method: string; params: unknown[] }[];
|
|
25
|
+
/** Replace the replicated state and broadcast it as a root snapshot op. */
|
|
26
|
+
setState: (state: TState) => Promise<void>;
|
|
27
|
+
/** Deliver an ack watermark on the stream. */
|
|
28
|
+
ack: (seq: number) => Promise<void>;
|
|
29
|
+
/** Deliver an arbitrary envelope on the stream. */
|
|
30
|
+
sendEnvelope: (envelope: StatewireEnvelope) => Promise<void>;
|
|
31
|
+
/** End the stream with a fin; further attaches fail like a dead server. */
|
|
32
|
+
finish: (reason: string, message?: string) => Promise<void>;
|
|
33
|
+
readonly clientId: string;
|
|
34
|
+
readonly attached: boolean;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A mock statewire backend: serves `initialState` as the attach snapshot,
|
|
39
|
+
* records command POSTs (receipt only — acks and results are delivered from
|
|
40
|
+
* test code), and exposes the wire as a transport ResourceElement.
|
|
41
|
+
*/
|
|
42
|
+
let mockCount = 0;
|
|
43
|
+
|
|
44
|
+
export const createMockTransport = <TState>(
|
|
45
|
+
initialState: TState,
|
|
46
|
+
): MockTransport<TState> => {
|
|
47
|
+
let state: unknown = initialState;
|
|
48
|
+
let clientId = "";
|
|
49
|
+
let finished = false;
|
|
50
|
+
const clients = new Map<string, number>();
|
|
51
|
+
const streams = new Set<FakeStreamHandle>();
|
|
52
|
+
const commands: { method: string; params: unknown[] }[] = [];
|
|
53
|
+
|
|
54
|
+
const sendEnvelope = (envelope: StatewireEnvelope) => {
|
|
55
|
+
for (const stream of streams) stream.send(sseFrame(envelope));
|
|
56
|
+
return tick();
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const fakeFetch = (async (
|
|
60
|
+
input: RequestInfo | URL,
|
|
61
|
+
init?: RequestInit,
|
|
62
|
+
): Promise<Response> => {
|
|
63
|
+
if (finished) throw new TypeError("fetch failed (finished)");
|
|
64
|
+
const url = String(input);
|
|
65
|
+
const headers = new Headers(init?.headers);
|
|
66
|
+
const id = headers.get("Statewire-Client-Id") ?? "";
|
|
67
|
+
if (url.endsWith("/stream")) {
|
|
68
|
+
clientId = id;
|
|
69
|
+
const lastSeq = clients.get(id) ?? 0;
|
|
70
|
+
clients.set(id, lastSeq);
|
|
71
|
+
return openSSEStream(
|
|
72
|
+
streams,
|
|
73
|
+
id,
|
|
74
|
+
(handle) => {
|
|
75
|
+
handle.send(
|
|
76
|
+
sseFrame({
|
|
77
|
+
ops: [{ op: "replace", path: [], value: state }],
|
|
78
|
+
syn: { lastSeq, lease: "mock-lease" },
|
|
79
|
+
}),
|
|
80
|
+
);
|
|
81
|
+
},
|
|
82
|
+
init?.signal ?? undefined,
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
if (url.endsWith("/commands")) {
|
|
86
|
+
const seq = Number(headers.get("Statewire-Command-Seq"));
|
|
87
|
+
clients.set(id, Math.max(clients.get(id) ?? 0, seq));
|
|
88
|
+
commands.push(
|
|
89
|
+
JSON.parse(String(init?.body)) as { method: string; params: unknown[] },
|
|
90
|
+
);
|
|
91
|
+
return Response.json({});
|
|
92
|
+
}
|
|
93
|
+
return new Response(null, { status: 404 });
|
|
94
|
+
}) as typeof fetch;
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
transport: StatewireSSE({
|
|
98
|
+
url: `http://mock-${++mockCount}/api`,
|
|
99
|
+
fetch: fakeFetch,
|
|
100
|
+
}),
|
|
101
|
+
commands,
|
|
102
|
+
setState: (next) => {
|
|
103
|
+
state = next;
|
|
104
|
+
return sendEnvelope({ ops: [{ op: "replace", path: [], value: next }] });
|
|
105
|
+
},
|
|
106
|
+
ack: (seq) => sendEnvelope({ ack: seq }),
|
|
107
|
+
sendEnvelope,
|
|
108
|
+
finish: async (reason, message) => {
|
|
109
|
+
await sendEnvelope({
|
|
110
|
+
fin: { reason, ...(message !== undefined && { message }) },
|
|
111
|
+
});
|
|
112
|
+
finished = true;
|
|
113
|
+
for (const stream of [...streams]) stream.close();
|
|
114
|
+
await tick();
|
|
115
|
+
},
|
|
116
|
+
get clientId() {
|
|
117
|
+
return clientId;
|
|
118
|
+
},
|
|
119
|
+
get attached() {
|
|
120
|
+
return streams.size > 0;
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
};
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { useState } from "react";
|
|
2
|
+
import { flushTapSync, resource } from "@assistant-ui/tap";
|
|
3
|
+
import type { ResourceElement } from "@assistant-ui/tap";
|
|
4
|
+
import { encodeParams } from "../wire/meta";
|
|
5
|
+
import { timing } from "../client/timing";
|
|
6
|
+
import {
|
|
7
|
+
handleEnvelope,
|
|
8
|
+
overloadedError,
|
|
9
|
+
useStatewireConn,
|
|
10
|
+
} from "../client/connection";
|
|
11
|
+
import type { Conn, StatewireEnvelope } from "../client/connection";
|
|
12
|
+
import type { Statewire } from "../types";
|
|
13
|
+
import type { StatewireClient } from "../statewire";
|
|
14
|
+
import { useStatewireRemote } from "./remote";
|
|
15
|
+
import { CLIENT_QUERY_PARAM } from "../host/adapter";
|
|
16
|
+
import type {
|
|
17
|
+
RemoteLink,
|
|
18
|
+
StatewireSubmitResult,
|
|
19
|
+
StatewireRemoteProps,
|
|
20
|
+
StatewireWireCommand,
|
|
21
|
+
} from "./sse";
|
|
22
|
+
|
|
23
|
+
type PendingCommand = {
|
|
24
|
+
seq: number;
|
|
25
|
+
resolve: (result: StatewireSubmitResult) => void;
|
|
26
|
+
reject: (error: Error) => void;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
type WsChannel = {
|
|
30
|
+
socket: WebSocket | null;
|
|
31
|
+
pending: PendingCommand[];
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const OPEN = 1;
|
|
35
|
+
|
|
36
|
+
export const WS_SUBPROTOCOL = "statewire.v1";
|
|
37
|
+
|
|
38
|
+
const socketUrl = async (
|
|
39
|
+
options: StatewireClient.WSOptions,
|
|
40
|
+
clientId: string,
|
|
41
|
+
) => {
|
|
42
|
+
const { url, query } = options;
|
|
43
|
+
const params = new URLSearchParams(
|
|
44
|
+
typeof query === "function" ? await query() : query,
|
|
45
|
+
);
|
|
46
|
+
params.set(CLIENT_QUERY_PARAM, clientId);
|
|
47
|
+
const base = url.replace(/\/$/, "").replace(/^http/, "ws");
|
|
48
|
+
return `${base}/ws?${params.toString()}`;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const settleOverloaded = (
|
|
52
|
+
w: WsChannel,
|
|
53
|
+
{ seq, retryAfterMs }: { seq?: number; retryAfterMs?: number },
|
|
54
|
+
) => {
|
|
55
|
+
if (seq === undefined) throw overloadedError(retryAfterMs);
|
|
56
|
+
const entry = w.pending.find((p) => p.seq === seq);
|
|
57
|
+
if (!entry) return;
|
|
58
|
+
w.pending = w.pending.filter((p) => p !== entry);
|
|
59
|
+
entry.reject(overloadedError(retryAfterMs));
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const resolvePending = (
|
|
63
|
+
w: WsChannel,
|
|
64
|
+
matches: (entry: PendingCommand) => boolean,
|
|
65
|
+
) => {
|
|
66
|
+
const remaining: PendingCommand[] = [];
|
|
67
|
+
for (const entry of w.pending) {
|
|
68
|
+
if (matches(entry)) entry.resolve({ type: "receipt" });
|
|
69
|
+
else remaining.push(entry);
|
|
70
|
+
}
|
|
71
|
+
w.pending = remaining;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const failPending = (w: WsChannel, error: Error) => {
|
|
75
|
+
const pending = w.pending;
|
|
76
|
+
w.pending = [];
|
|
77
|
+
for (const entry of pending) entry.reject(error);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const runSocket = (
|
|
81
|
+
c: Conn,
|
|
82
|
+
w: WsChannel,
|
|
83
|
+
ws: WebSocket,
|
|
84
|
+
abort: AbortController,
|
|
85
|
+
): Promise<"stop" | "reattach"> =>
|
|
86
|
+
new Promise((resolve, reject) => {
|
|
87
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
88
|
+
let timedOut = false;
|
|
89
|
+
let outcome: "stop" | "reattach" | null = null;
|
|
90
|
+
let closed = false;
|
|
91
|
+
const arm = () => {
|
|
92
|
+
clearTimeout(timer);
|
|
93
|
+
timer = setTimeout(() => {
|
|
94
|
+
timedOut = true;
|
|
95
|
+
ws.close();
|
|
96
|
+
}, timing.heartbeatTimeoutMs);
|
|
97
|
+
};
|
|
98
|
+
arm();
|
|
99
|
+
abort.signal.addEventListener("abort", () => ws.close());
|
|
100
|
+
ws.onerror = () => {};
|
|
101
|
+
const stale = () => Boolean(outcome) || closed || abort.signal.aborted;
|
|
102
|
+
const fail = (error: unknown) => {
|
|
103
|
+
clearTimeout(timer);
|
|
104
|
+
reject(error instanceof Error ? error : new Error("protocol"));
|
|
105
|
+
ws.close();
|
|
106
|
+
};
|
|
107
|
+
const processEnv = (env: StatewireEnvelope) => {
|
|
108
|
+
const done = flushTapSync(() => handleEnvelope(c, env));
|
|
109
|
+
if (env.ack !== undefined) {
|
|
110
|
+
const ack = env.ack;
|
|
111
|
+
resolvePending(w, (entry) => entry.seq <= ack);
|
|
112
|
+
}
|
|
113
|
+
if (env.res !== undefined) {
|
|
114
|
+
const seqs = new Set(env.res.map((r) => r.seq));
|
|
115
|
+
resolvePending(w, (entry) => seqs.has(entry.seq));
|
|
116
|
+
}
|
|
117
|
+
if (done) {
|
|
118
|
+
outcome = done;
|
|
119
|
+
ws.close();
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
ws.onmessage = (event) => {
|
|
123
|
+
if (stale()) return;
|
|
124
|
+
arm();
|
|
125
|
+
let frame: StatewireEnvelope & {
|
|
126
|
+
overloaded?: { seq?: number; retryAfterMs?: number };
|
|
127
|
+
};
|
|
128
|
+
try {
|
|
129
|
+
frame = JSON.parse(String(event.data)) as typeof frame;
|
|
130
|
+
} catch {
|
|
131
|
+
fail(new Error("protocol"));
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
try {
|
|
135
|
+
if (frame.overloaded !== undefined) {
|
|
136
|
+
settleOverloaded(w, frame.overloaded);
|
|
137
|
+
} else {
|
|
138
|
+
processEnv(frame);
|
|
139
|
+
}
|
|
140
|
+
} catch (error) {
|
|
141
|
+
fail(error);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
ws.onclose = () => {
|
|
145
|
+
closed = true;
|
|
146
|
+
clearTimeout(timer);
|
|
147
|
+
if (w.socket === ws) failPending(w, new Error("network"));
|
|
148
|
+
if (outcome) resolve(outcome);
|
|
149
|
+
else reject(new Error(timedOut ? "timeout" : "network"));
|
|
150
|
+
};
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
const attemptSocket = async (
|
|
154
|
+
c: Conn,
|
|
155
|
+
w: WsChannel,
|
|
156
|
+
options: StatewireClient.WSOptions,
|
|
157
|
+
abort: AbortController,
|
|
158
|
+
): Promise<"stop" | "reattach"> => {
|
|
159
|
+
let ws: WebSocket | null = null;
|
|
160
|
+
try {
|
|
161
|
+
const url = await socketUrl(options, c.ctx.clientId);
|
|
162
|
+
abort.signal.throwIfAborted();
|
|
163
|
+
const { protocols, webSocket } = options;
|
|
164
|
+
const WS = webSocket ?? globalThis.WebSocket;
|
|
165
|
+
if (!WS) throw new Error("no WebSocket implementation");
|
|
166
|
+
const extra =
|
|
167
|
+
protocols === undefined
|
|
168
|
+
? []
|
|
169
|
+
: typeof protocols === "string"
|
|
170
|
+
? [protocols]
|
|
171
|
+
: protocols;
|
|
172
|
+
ws = new WS(url, [WS_SUBPROTOCOL, ...extra]);
|
|
173
|
+
w.socket = ws;
|
|
174
|
+
return await runSocket(c, w, ws, abort);
|
|
175
|
+
} finally {
|
|
176
|
+
if (w.socket === ws) w.socket = null;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const sendCommand = (
|
|
181
|
+
w: WsChannel,
|
|
182
|
+
{ seq, command }: { seq: number; command: StatewireWireCommand },
|
|
183
|
+
): Promise<StatewireSubmitResult> => {
|
|
184
|
+
const ws = w.socket;
|
|
185
|
+
if (!ws || ws.readyState !== OPEN) {
|
|
186
|
+
return Promise.reject(new Error("network"));
|
|
187
|
+
}
|
|
188
|
+
return new Promise((resolve, reject) => {
|
|
189
|
+
const entry: PendingCommand = {
|
|
190
|
+
seq,
|
|
191
|
+
resolve: (result) => {
|
|
192
|
+
clearTimeout(timer);
|
|
193
|
+
resolve(result);
|
|
194
|
+
},
|
|
195
|
+
reject: (error) => {
|
|
196
|
+
clearTimeout(timer);
|
|
197
|
+
reject(error);
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
// A timed-out command fails the socket: the retry then rides reconnect +
|
|
201
|
+
// attach-seq arbitration.
|
|
202
|
+
const timer = setTimeout(() => {
|
|
203
|
+
w.pending = w.pending.filter((p) => p !== entry);
|
|
204
|
+
reject(new Error("timeout"));
|
|
205
|
+
ws.close();
|
|
206
|
+
}, timing.heartbeatTimeoutMs);
|
|
207
|
+
w.pending.push(entry);
|
|
208
|
+
try {
|
|
209
|
+
ws.send(
|
|
210
|
+
JSON.stringify({
|
|
211
|
+
method: command.method,
|
|
212
|
+
...encodeParams(command.params),
|
|
213
|
+
seq,
|
|
214
|
+
}),
|
|
215
|
+
);
|
|
216
|
+
} catch {
|
|
217
|
+
clearTimeout(timer);
|
|
218
|
+
w.pending = w.pending.filter((p) => p !== entry);
|
|
219
|
+
reject(new Error("network"));
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
const useWsLink = (
|
|
225
|
+
options: StatewireClient.WSOptions,
|
|
226
|
+
ctx: StatewireRemoteProps,
|
|
227
|
+
): RemoteLink => {
|
|
228
|
+
const [w] = useState((): WsChannel => ({ socket: null, pending: [] }));
|
|
229
|
+
const c = useStatewireConn({
|
|
230
|
+
url: options.url,
|
|
231
|
+
onChange: options.onChange,
|
|
232
|
+
ctx,
|
|
233
|
+
attemptOnce: (c, abort) => attemptSocket(c, w, options, abort),
|
|
234
|
+
});
|
|
235
|
+
const [link] = useState(
|
|
236
|
+
(): RemoteLink => ({
|
|
237
|
+
get connection() {
|
|
238
|
+
return c.connection;
|
|
239
|
+
},
|
|
240
|
+
send: (args) => sendCommand(w, args),
|
|
241
|
+
}),
|
|
242
|
+
);
|
|
243
|
+
return link;
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
const useStatewireWS = (
|
|
247
|
+
options: StatewireClient.WSOptions,
|
|
248
|
+
): Statewire<any, any, any> => useStatewireRemote(options, useWsLink);
|
|
249
|
+
|
|
250
|
+
export const StatewireWS = resource(useStatewireWS) as <
|
|
251
|
+
TState = any,
|
|
252
|
+
TCommands extends Statewire.Commands = Statewire.Commands,
|
|
253
|
+
TEvent = any,
|
|
254
|
+
>(
|
|
255
|
+
options: StatewireClient.WSOptions,
|
|
256
|
+
) => ResourceElement<Statewire<TState | undefined, TCommands, TEvent>>;
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { StatewireClient } from "./statewire";
|
|
2
|
+
import type { StatewirePath } from "./wire/ops";
|
|
3
|
+
|
|
4
|
+
export namespace Statewire {
|
|
5
|
+
export type Commands = Record<string, (...args: never[]) => unknown>;
|
|
6
|
+
|
|
7
|
+
export type Command<TCommands extends Commands = Commands> = {
|
|
8
|
+
[K in keyof TCommands]: { method: K; params: Parameters<TCommands[K]> };
|
|
9
|
+
}[keyof TCommands];
|
|
10
|
+
|
|
11
|
+
export type CommandsProxy<TCommands extends Commands> = {
|
|
12
|
+
[K in keyof TCommands]: (
|
|
13
|
+
...args: Parameters<TCommands[K]>
|
|
14
|
+
) => Promise<Awaited<ReturnType<TCommands[K]>>>;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type CommandUpdate<TCommands extends Commands = Commands> = {
|
|
18
|
+
[K in keyof TCommands]: {
|
|
19
|
+
method: K;
|
|
20
|
+
params: Parameters<TCommands[K]>;
|
|
21
|
+
seq: number;
|
|
22
|
+
status: "queued" | "posted" | "acked" | "settled";
|
|
23
|
+
result?: unknown;
|
|
24
|
+
failure?: StatewireClient.SendFailure;
|
|
25
|
+
};
|
|
26
|
+
}[keyof TCommands];
|
|
27
|
+
|
|
28
|
+
/** Push-based canonical state feed a statewire hands to the client core. */
|
|
29
|
+
export type StateSource = {
|
|
30
|
+
snapshot: () => unknown;
|
|
31
|
+
/** Drain the paths changed since the last take (`[]` entry = whole state). */
|
|
32
|
+
takeChanged: () => StatewirePath[];
|
|
33
|
+
/** Synchronous, per change; the consumer owns coalescing. */
|
|
34
|
+
setOnChange: (listener: (() => void) | null) => void;
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export type Op =
|
|
38
|
+
| { op: "replace"; path: StatewirePath; value: unknown }
|
|
39
|
+
| { op: "add"; path: StatewirePath; value: unknown }
|
|
40
|
+
| { op: "remove"; path: StatewirePath }
|
|
41
|
+
| { op: "event"; value: object };
|
|
42
|
+
|
|
43
|
+
export type Changes = {
|
|
44
|
+
isChangedAt(path: readonly (string | number)[]): boolean;
|
|
45
|
+
getChangedKeys(path: readonly (string | number)[]): string[];
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface Statewire<
|
|
50
|
+
TState = any,
|
|
51
|
+
TCommands extends Statewire.Commands = Statewire.Commands,
|
|
52
|
+
TEvent = any,
|
|
53
|
+
> {
|
|
54
|
+
state: TState;
|
|
55
|
+
commands: Statewire.CommandsProxy<TCommands>;
|
|
56
|
+
emit?: (event: TEvent) => void;
|
|
57
|
+
connection?: StatewireClient.Connection;
|
|
58
|
+
source?: Statewire.StateSource;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const describe = (failure: StatewireClient.SendFailure): string => {
|
|
62
|
+
switch (failure.fate) {
|
|
63
|
+
case "rejected":
|
|
64
|
+
return `statewire: command rejected: ${failure.message}`;
|
|
65
|
+
case "unknown-command":
|
|
66
|
+
return "statewire: unknown command";
|
|
67
|
+
case "invalid-params":
|
|
68
|
+
return `statewire: invalid params: ${failure.message}`;
|
|
69
|
+
case "aborted":
|
|
70
|
+
return `statewire: command aborted (${failure.cause})`;
|
|
71
|
+
case "lost":
|
|
72
|
+
return `statewire: command lost (${failure.cause})`;
|
|
73
|
+
case "crashed":
|
|
74
|
+
return "statewire: command crashed";
|
|
75
|
+
case "result-unavailable":
|
|
76
|
+
return `statewire: command result unavailable (${failure.cause})`;
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
export class StatewireSendError extends Error {
|
|
81
|
+
readonly failure: StatewireClient.SendFailure;
|
|
82
|
+
|
|
83
|
+
constructor(failure: StatewireClient.SendFailure) {
|
|
84
|
+
super(describe(failure));
|
|
85
|
+
this.name = "StatewireSendError";
|
|
86
|
+
this.failure = failure;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
type SharedTraps = Pick<
|
|
2
|
+
ProxyHandler<object>,
|
|
3
|
+
| "defineProperty"
|
|
4
|
+
| "setPrototypeOf"
|
|
5
|
+
| "preventExtensions"
|
|
6
|
+
| "ownKeys"
|
|
7
|
+
| "getOwnPropertyDescriptor"
|
|
8
|
+
>;
|
|
9
|
+
|
|
10
|
+
export const sharedDraftTraps = (
|
|
11
|
+
current: () => object,
|
|
12
|
+
context: string,
|
|
13
|
+
): SharedTraps => {
|
|
14
|
+
const unsupported = (op: string): never => {
|
|
15
|
+
throw new Error(`statewire: ${op} is not supported ${context}`);
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
defineProperty: () => unsupported("defineProperty"),
|
|
19
|
+
setPrototypeOf: () => unsupported("setPrototypeOf"),
|
|
20
|
+
preventExtensions: () => unsupported("preventExtensions"),
|
|
21
|
+
ownKeys: () => Reflect.ownKeys(current()),
|
|
22
|
+
getOwnPropertyDescriptor: (_target, prop) => {
|
|
23
|
+
const node = current();
|
|
24
|
+
const desc = Reflect.getOwnPropertyDescriptor(node, prop);
|
|
25
|
+
if (!desc) return undefined;
|
|
26
|
+
return {
|
|
27
|
+
...desc,
|
|
28
|
+
configurable: !Array.isArray(node) || prop !== "length",
|
|
29
|
+
};
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// MessageChannel schedules the flush as a macrotask (tap's pattern): it runs
|
|
2
|
+
// after the whole microtask drain, so every producer in the current turn
|
|
3
|
+
// coalesces. The port is ref'd only while a flush is pending — an active
|
|
4
|
+
// MessagePort holds the Node event loop open. ref/unref are Node-only.
|
|
5
|
+
export const createMacrotaskPoster = (callback: () => void): (() => void) => {
|
|
6
|
+
if (typeof MessageChannel !== "undefined") {
|
|
7
|
+
let port1: (MessagePort & { ref?: () => void; unref?: () => void }) | null =
|
|
8
|
+
null;
|
|
9
|
+
let port2: MessagePort;
|
|
10
|
+
return () => {
|
|
11
|
+
if (!port1) {
|
|
12
|
+
const channel = new MessageChannel();
|
|
13
|
+
channel.port1.onmessage = () => {
|
|
14
|
+
port1?.unref?.();
|
|
15
|
+
callback();
|
|
16
|
+
};
|
|
17
|
+
port1 = channel.port1;
|
|
18
|
+
port2 = channel.port2;
|
|
19
|
+
}
|
|
20
|
+
port1.ref?.();
|
|
21
|
+
port2!.postMessage(null);
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
return () => setTimeout(callback, 0);
|
|
25
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export const createMethodProxy = <T extends object>(
|
|
2
|
+
dispatch: (method: string, params: unknown[]) => Promise<unknown>,
|
|
3
|
+
): T => {
|
|
4
|
+
const memo = new Map<string, (...params: unknown[]) => Promise<unknown>>();
|
|
5
|
+
return new Proxy({} as T, {
|
|
6
|
+
get: (_target, method) => {
|
|
7
|
+
if (typeof method !== "string") return undefined;
|
|
8
|
+
let fn = memo.get(method);
|
|
9
|
+
if (fn === undefined) {
|
|
10
|
+
fn = (...params: unknown[]) => dispatch(method, params);
|
|
11
|
+
memo.set(method, fn);
|
|
12
|
+
}
|
|
13
|
+
return fn;
|
|
14
|
+
},
|
|
15
|
+
});
|
|
16
|
+
};
|
|
Binary file
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export type StatePath = readonly (string | number)[];
|
|
2
|
+
|
|
3
|
+
export const isUnsafeKey = (
|
|
4
|
+
key: string | number,
|
|
5
|
+
parent: string | number | undefined,
|
|
6
|
+
) => key === "__proto__" || (key === "prototype" && parent === "constructor");
|
|
7
|
+
|
|
8
|
+
export type WalkedPath = {
|
|
9
|
+
/** Container of the final key; undefined when the path is empty. */
|
|
10
|
+
parent: unknown;
|
|
11
|
+
key: string | number;
|
|
12
|
+
leaf: unknown;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
// "read": lenient, never fails — missing steps yield an undefined leaf.
|
|
16
|
+
// "parent": every step before the last must resolve; the leaf may not exist.
|
|
17
|
+
// "resolve": every step including the last must resolve.
|
|
18
|
+
// Strict modes require array+integer for number keys, plain object for string
|
|
19
|
+
// keys, and reject unsafe (prototype-polluting) segments.
|
|
20
|
+
export const walkStatePath = (
|
|
21
|
+
root: unknown,
|
|
22
|
+
path: StatePath,
|
|
23
|
+
mode: "read" | "parent" | "resolve",
|
|
24
|
+
): WalkedPath | undefined => {
|
|
25
|
+
let parent: unknown = undefined;
|
|
26
|
+
let key: string | number = "";
|
|
27
|
+
let node: unknown = root;
|
|
28
|
+
for (let depth = 0; depth < path.length; depth++) {
|
|
29
|
+
const k = path[depth]!;
|
|
30
|
+
const mustResolve =
|
|
31
|
+
mode === "resolve" || (mode === "parent" && depth < path.length - 1);
|
|
32
|
+
if (mode !== "read") {
|
|
33
|
+
if (typeof k === "number") {
|
|
34
|
+
if (!Array.isArray(node) || !Number.isInteger(k) || k < 0) {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
if (mustResolve && k >= node.length) return undefined;
|
|
38
|
+
} else {
|
|
39
|
+
if (
|
|
40
|
+
isUnsafeKey(k, path[depth - 1]) ||
|
|
41
|
+
typeof node !== "object" ||
|
|
42
|
+
node === null ||
|
|
43
|
+
Array.isArray(node)
|
|
44
|
+
) {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
if (mustResolve && !Object.hasOwn(node, k)) return undefined;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
parent = node;
|
|
51
|
+
key = k;
|
|
52
|
+
node =
|
|
53
|
+
typeof node === "object" && node !== null && Object.hasOwn(node, k)
|
|
54
|
+
? (node as Record<string | number, unknown>)[k]
|
|
55
|
+
: undefined;
|
|
56
|
+
}
|
|
57
|
+
return { parent, key, leaf: node };
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export const readAtPath = (root: unknown, path: StatePath): unknown =>
|
|
61
|
+
walkStatePath(root, path, "read")!.leaf;
|