@dammers/use-signalr-react 0.4.0 → 1.0.0
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 +36 -166
- package/dist/create-signalr-client.d.ts +20 -16
- package/dist/create-signalr-client.js +21 -16
- package/dist/index.d.ts +4 -5
- package/dist/index.js +2 -2
- package/dist/internal/create-hooks.d.ts +6 -6
- package/dist/internal/create-hooks.js +37 -145
- package/dist/internal/create-provider.d.ts +2 -2
- package/dist/internal/create-provider.js +25 -75
- package/dist/status-store.d.ts +3 -7
- package/dist/status-store.js +10 -6
- package/dist/types.d.ts +5 -2
- package/package.json +30 -13
package/README.md
CHANGED
|
@@ -1,191 +1,61 @@
|
|
|
1
1
|
# @dammers/use-signalr-react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Provider and hooks for typed [SignalR](https://learn.microsoft.com/aspnet/core/signalr) in React. Part of [use-signalr](https://use-signalr.vercel.app).
|
|
4
4
|
|
|
5
5
|
[](https://www.npmjs.com/package/@dammers/use-signalr-react)
|
|
6
|
-
[](./LICENSE)
|
|
8
|
-
|
|
9
|
-
```ts
|
|
10
|
-
const { SignalRProvider, useSignalRInvoke } = createSignalRClient({
|
|
11
|
-
hubs: {
|
|
12
|
-
"/hubs/chat": {
|
|
13
|
-
methods: { SendMessage: method<[roomId: string, message: string]>() },
|
|
14
|
-
},
|
|
15
|
-
},
|
|
16
|
-
});
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
One factory call returns a provider and a set of hooks, each typed against your hub contract. Event args, method args, and return values are all inferred from the config.
|
|
20
|
-
|
|
21
|
-
Shared concepts (the contract, per-hub config, invoke retry, send vs invoke vs teardown) are covered in the [root README](https://github.com/DammersCode/use-signalr#readme). This document covers React-specific install and usage.
|
|
6
|
+
[](https://github.com/DammersCode/use-signalr/blob/main/LICENSE)
|
|
22
7
|
|
|
23
8
|
## Install
|
|
24
9
|
|
|
25
10
|
```bash
|
|
26
|
-
npm
|
|
11
|
+
npm install @dammers/use-signalr-react @microsoft/signalr
|
|
27
12
|
```
|
|
28
13
|
|
|
29
|
-
|
|
14
|
+
It needs React ^19, `@microsoft/signalr` ^8 || ^9 || ^10, and Node 20.19 or later.
|
|
30
15
|
|
|
31
|
-
##
|
|
16
|
+
## Example
|
|
32
17
|
|
|
33
|
-
|
|
18
|
+
This file declares a hub, connects it, and reads a typed method result:
|
|
34
19
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
import { createSignalRClient, event, method } from "@dammers/use-signalr-react";
|
|
20
|
+
<!-- hero:react:start -->
|
|
21
|
+
```tsx
|
|
22
|
+
import { useState } from "react";
|
|
23
|
+
import { createSignalRClient, method } from "@dammers/use-signalr-react";
|
|
40
24
|
|
|
41
|
-
|
|
42
|
-
SignalRProvider,
|
|
43
|
-
useSignalR,
|
|
44
|
-
useSignalREffect,
|
|
45
|
-
useSignalRInvoke,
|
|
46
|
-
useSignalRSend,
|
|
47
|
-
useSignalRTeardown,
|
|
48
|
-
useHubStatus,
|
|
49
|
-
useOnReconnected,
|
|
50
|
-
useHubConsumer,
|
|
51
|
-
} = createSignalRClient({
|
|
25
|
+
const { SignalRProvider, useSignalRInvoke } = createSignalRClient({
|
|
52
26
|
hubs: {
|
|
53
|
-
"/hubs/
|
|
54
|
-
|
|
55
|
-
ReceiveMessage: event<[user: string, message: string]>(),
|
|
56
|
-
},
|
|
57
|
-
methods: {
|
|
58
|
-
SendMessage: method<[roomId: string, message: string]>(),
|
|
59
|
-
JoinRoom: method<[roomId: string], { success: boolean }>(),
|
|
60
|
-
},
|
|
61
|
-
// per-hub config also goes here (see the root README)
|
|
27
|
+
"/hubs/rooms": {
|
|
28
|
+
methods: { GetHistory: method<[roomId: string], { text: string }[]>() },
|
|
62
29
|
},
|
|
63
30
|
},
|
|
64
|
-
// global defaults (all optional):
|
|
65
|
-
// lazy: false, reconnect: true, maxConnectRetries: 2, logLevel: LogLevel.Information
|
|
66
31
|
});
|
|
67
|
-
```
|
|
68
|
-
|
|
69
|
-
`event<Args>()` takes the handler's argument tuple. `method<Args, Return>()` takes the argument tuple and the resolved return type (default `void`).
|
|
70
|
-
|
|
71
|
-
### 2. Mount the provider with your auth
|
|
72
32
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
<App />
|
|
88
|
-
</SignalRProvider>;
|
|
33
|
+
function HistoryCount({ roomId }: { roomId: string }) {
|
|
34
|
+
const getHistory = useSignalRInvoke("/hubs/rooms", "GetHistory");
|
|
35
|
+
const [count, setCount] = useState(0);
|
|
36
|
+
const load = () => getHistory(roomId).then((m) => setCount(m.length)).catch(console.error);
|
|
37
|
+
return <button onClick={load}>{count} messages</button>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function App() {
|
|
41
|
+
return (
|
|
42
|
+
<SignalRProvider baseUrl="https://api.example.com" accessTokenFactory={() => "token"}>
|
|
43
|
+
<HistoryCount roomId="general" />
|
|
44
|
+
</SignalRProvider>
|
|
45
|
+
);
|
|
46
|
+
}
|
|
89
47
|
```
|
|
48
|
+
<!-- hero:react:end -->
|
|
90
49
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
```tsx
|
|
94
|
-
// Listen to a server event — args inferred from the contract
|
|
95
|
-
useSignalREffect("/hubs/chat", "ReceiveMessage", (user, message) => {
|
|
96
|
-
console.log(user, message);
|
|
97
|
-
});
|
|
98
|
-
|
|
99
|
-
// Invoke a server method — args + return inferred, waits for connection
|
|
100
|
-
const sendMessage = useSignalRInvoke("/hubs/chat", "SendMessage");
|
|
101
|
-
await sendMessage(roomId, "hello"); // typed params, Promise<void>
|
|
102
|
-
|
|
103
|
-
// Typed fire-and-forget — does not wait for connection; drops if not connected.
|
|
104
|
-
// Stable across renders — safe to capture in an unmount cleanup.
|
|
105
|
-
const send = useSignalRSend("/hubs/chat", "SendMessage");
|
|
106
|
-
await send(roomId, "bye"); // typed args; Promise<boolean> (true = dispatched)
|
|
107
|
-
|
|
108
|
-
// Reliable teardown — for a method called in an effect cleanup. Survives
|
|
109
|
-
// unmount, queues while the hub connects (instead of dropping), and holds a
|
|
110
|
-
// lazy hub open until it flushes. Best-effort: Promise<boolean> (true = dispatched).
|
|
111
|
-
const leaveRoom = useSignalRTeardown("/hubs/chat", "LeaveRoomAsync");
|
|
112
|
-
useEffect(() => {
|
|
113
|
-
joinRoom(roomId);
|
|
114
|
-
return () => {
|
|
115
|
-
leaveRoom(roomId);
|
|
116
|
-
}; // lands even mid-connect or after unmount
|
|
117
|
-
}, [roomId, joinRoom, leaveRoom]);
|
|
118
|
-
|
|
119
|
-
// Live connection status — re-renders only when this hub's status changes
|
|
120
|
-
const status = useHubStatus("/hubs/chat"); // "connecting" | "connected" | "reconnecting" | ...
|
|
121
|
-
|
|
122
|
-
// Re-sync after a reconnect, for example to refetch a query
|
|
123
|
-
useOnReconnected("/hubs/chat", () => refetchMessages());
|
|
124
|
-
|
|
125
|
-
// Keep a lazy hub connected for this component's lifetime without subscribing
|
|
126
|
-
useHubConsumer("/hubs/chat");
|
|
127
|
-
|
|
128
|
-
// Last resort: the raw HubConnection (prefer the typed hooks above)
|
|
129
|
-
const { getConnection } = useSignalR();
|
|
130
|
-
getConnection("/hubs/chat")?.send("SendMessage", roomId, "bye");
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
### Reliable join/leave (session pattern)
|
|
134
|
-
|
|
135
|
-
A common pattern joins a session on mount and leaves it in the effect cleanup.
|
|
136
|
-
|
|
137
|
-
```tsx
|
|
138
|
-
const joinRoom = useSignalRInvoke("/hubs/chat", "JoinRoomAsync");
|
|
139
|
-
const leaveRoom = useSignalRTeardown("/hubs/chat", "LeaveRoomAsync");
|
|
140
|
-
|
|
141
|
-
useEffect(() => {
|
|
142
|
-
joinRoom(roomId);
|
|
143
|
-
return () => {
|
|
144
|
-
leaveRoom(roomId);
|
|
145
|
-
};
|
|
146
|
-
}, [roomId, joinRoom, leaveRoom]);
|
|
147
|
-
```
|
|
148
|
-
|
|
149
|
-
A plain `useSignalRInvoke` or `useSignalRSend` makes the **leave** unreliable:
|
|
150
|
-
|
|
151
|
-
- `useSignalRInvoke` aborts in-flight calls on unmount, so a leave issued in cleanup can be cancelled before it reaches the server.
|
|
152
|
-
- `useSignalRSend` drops silently if the hub is not `Connected`, so a leave that races a still-connecting socket (StrictMode's first mount, a fast route switch) is lost.
|
|
153
|
-
|
|
154
|
-
`useSignalRTeardown` fixes both problems. It:
|
|
155
|
-
|
|
156
|
-
- **survives the calling component's unmount** — it runs detached and is never aborted,
|
|
157
|
-
- **queues while connecting** — it waits up to `timeout` (default 10s) for the hub, then sends, instead of dropping,
|
|
158
|
-
- **holds a lazy hub open** until the flush completes, even if the unmounting component was its last consumer.
|
|
159
|
-
|
|
160
|
-
It is best-effort and fire-and-forget: it resolves `true` once dispatched, `false` if the hub never connected in time, and never throws. It also lands correctly under StrictMode's mount→cleanup→mount, at the cost of one extra round-trip.
|
|
161
|
-
|
|
162
|
-
> If your leave already uses `useSignalRInvoke` and only needs to avoid the abort on unmount, pass `{ keepAliveOnUnmount: true }`. This covers the abort case but **not** the still-connecting race. For that race, use `useSignalRTeardown`.
|
|
163
|
-
|
|
164
|
-
## API
|
|
165
|
-
|
|
166
|
-
| Export | What it does |
|
|
167
|
-
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
168
|
-
| `createSignalRClient(config)` | Returns the provider and hooks, typed against the contract **inferred** from `config`. |
|
|
169
|
-
| `event<Args>()` | Declares a server-pushed event inside a hub's `events`. `Args` is the handler's argument tuple. |
|
|
170
|
-
| `method<Args, Return?>()` | Declares an invocable server method inside a hub's `methods`. `Args` is the argument tuple; `Return` is the resolved return type (default `void`). |
|
|
171
|
-
| `<SignalRProvider>` | Builds and starts connections, retries, and auto-reconnects. |
|
|
172
|
-
| `useSignalREffect(hub, event, handler)` | Subscribes to a server event for the component's lifetime. |
|
|
173
|
-
| `useSignalRInvoke(hub, method, opts?)` | Typed request/response invoker. Waits for the connection and returns the method's result. Optional retry/backoff/timeout; `keepAliveOnUnmount` skips the unmount abort. |
|
|
174
|
-
| `useSignalRSend(hub, method)` | Typed fire-and-forget sender. **Drops** if not connected. For high-frequency signals where loss is acceptable. Safe in unmount cleanups. |
|
|
175
|
-
| `useSignalRTeardown(hub, method, opts?)` | Reliable teardown sender for a method called in cleanup: survives unmount, **queues** while connecting instead of dropping, and holds a lazy hub open until flushed. |
|
|
176
|
-
| `useHubStatus(hub)` | Live connection status. Re-renders only when that hub changes. |
|
|
177
|
-
| `useOnReconnected(hub, cb)` | Runs `cb` after the hub reconnects, for example to refetch. |
|
|
178
|
-
| `useHubConsumer(hub)` | Keeps a lazy hub connected for the component's lifetime without subscribing. |
|
|
179
|
-
| `useSignalR()` | Last-resort raw context: `getConnection`, `isHubConnected`, `getStatus`. |
|
|
180
|
-
|
|
181
|
-
### Provider props
|
|
182
|
-
|
|
183
|
-
Required: `baseUrl`, `accessTokenFactory`. Optional: `enabled` (default `true`), `connectionKey`, `onStatusChange`, `onError`. Connection behavior (`lazy`, `reconnect`, `maxConnectRetries`, `logLevel`, per-hub overrides) lives in the **config** passed to `createSignalRClient`, not on the provider.
|
|
184
|
-
|
|
185
|
-
## More
|
|
50
|
+
## Documentation
|
|
186
51
|
|
|
187
|
-
|
|
52
|
+
- [Quick start](https://use-signalr.vercel.app/docs/react/quick-start)
|
|
53
|
+
- [Provider setup](https://use-signalr.vercel.app/docs/react/concepts/provider)
|
|
54
|
+
- [Events](https://use-signalr.vercel.app/docs/react/concepts/events) and [calls](https://use-signalr.vercel.app/docs/react/concepts/calls)
|
|
55
|
+
- [Connection status](https://use-signalr.vercel.app/docs/react/concepts/connection-status) and [recovery](https://use-signalr.vercel.app/docs/react/concepts/recovery)
|
|
56
|
+
- [API reference](https://use-signalr.vercel.app/docs/react/reference/api)
|
|
57
|
+
- [Troubleshooting](https://use-signalr.vercel.app/docs/react/reference/troubleshooting)
|
|
188
58
|
|
|
189
59
|
## License
|
|
190
60
|
|
|
191
|
-
MIT © [DammersCode](https://github.com/DammersCode)
|
|
61
|
+
[MIT](https://github.com/DammersCode/use-signalr/blob/main/LICENSE) © [DammersCode](https://github.com/DammersCode)
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { HubDef, HubString, InferContract, SignalRClientConfig } from "@dammers/use-signalr-core";
|
|
2
|
-
import type { SignalRContextValue } from "./types";
|
|
3
2
|
/**
|
|
4
3
|
* Creates a fully-typed SignalR client. Returns a provider and hooks, typed
|
|
5
4
|
* against the contract inferred from `config.hubs`: the keys declare the
|
|
@@ -12,13 +11,13 @@ export declare function createSignalRClient<const H extends Record<HubString, Hu
|
|
|
12
11
|
* configured hub. Pass `baseUrl` and `accessTokenFactory`, and gate them
|
|
13
12
|
* with `enabled`. Mount it once, near the root.
|
|
14
13
|
*/
|
|
15
|
-
SignalRProvider: ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: import("./types").SignalRProviderProps) => import("react").JSX.Element;
|
|
14
|
+
SignalRProvider: ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: import("./types.js").SignalRProviderProps<keyof H & `/${string}`>) => import("react").JSX.Element;
|
|
16
15
|
/**
|
|
17
|
-
* Escape hatch to the
|
|
18
|
-
*
|
|
16
|
+
* Escape hatch to the SignalR context (`getConnection`, `getStatus`,
|
|
17
|
+
* and `waitForConnection`). Prefer the typed hooks below. Use this only
|
|
19
18
|
* for the underlying `HubConnection` or a non-reactive point read.
|
|
20
19
|
*/
|
|
21
|
-
useSignalR: () =>
|
|
20
|
+
useSignalR: () => import("@dammers/use-signalr-core").SignalRPublicContext<InferContract<H>>;
|
|
22
21
|
/**
|
|
23
22
|
* Keeps a (possibly lazy) hub connected for the component's lifetime,
|
|
24
23
|
* without subscribing to events or status. Acquires on mount, releases on
|
|
@@ -27,38 +26,43 @@ export declare function createSignalRClient<const H extends Record<HubString, Hu
|
|
|
27
26
|
useHubConsumer: (hub: keyof H & `/${string}`) => void;
|
|
28
27
|
/**
|
|
29
28
|
* Subscribes to a typed server event for the component's lifetime.
|
|
30
|
-
* Handler args are inferred from your contract.
|
|
31
|
-
* reconnects.
|
|
29
|
+
* Handler args are inferred from your contract. The subscription survives
|
|
30
|
+
* reconnects and rebuilds.
|
|
32
31
|
*/
|
|
33
32
|
useSignalREffect: <H_1 extends keyof H & `/${string}`, E extends import("@dammers/use-signalr-core").EventName<InferContract<H>, H_1>>(hub: H_1, event: E, handler: (...args: import("@dammers/use-signalr-core").EventArgs<InferContract<H>, H_1, E>) => void) => void;
|
|
34
33
|
/**
|
|
35
34
|
* Typed invoker that waits for the connection and resolves with the
|
|
36
35
|
* method's return value. Fails fast by default. Opt in to retry for
|
|
37
|
-
* idempotent methods only.
|
|
36
|
+
* idempotent methods only. When the component unmounts, a call that still
|
|
37
|
+
* waits rejects with `AbortError`, unless you set `keepAliveOnUnmount`.
|
|
38
38
|
*/
|
|
39
39
|
useSignalRInvoke: <H_1 extends keyof H & `/${string}`, M extends import("@dammers/use-signalr-core").MethodName<InferContract<H>, H_1>>(hub: H_1, method: M, options?: import("@dammers/use-signalr-core").InvokeOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<InferContract<H>, H_1, M>) => Promise<import("@dammers/use-signalr-core").MethodReturn<InferContract<H>, H_1, M>>;
|
|
40
40
|
/**
|
|
41
|
-
* Typed fire-and-forget sender.
|
|
42
|
-
*
|
|
43
|
-
*
|
|
41
|
+
* Typed fire-and-forget sender. It does not wait for the connection. It
|
|
42
|
+
* resolves `true` when it sends the call, and `false` when the hub is not
|
|
43
|
+
* connected and it drops the call. It never throws, so a cleanup can call
|
|
44
|
+
* it. For a call that must land in a cleanup, use `useSignalRTeardown`.
|
|
44
45
|
*/
|
|
45
46
|
useSignalRSend: <H_1 extends keyof H & `/${string}`, M extends import("@dammers/use-signalr-core").MethodName<InferContract<H>, H_1>>(hub: H_1, method: M) => (...args: import("@dammers/use-signalr-core").MethodArgs<InferContract<H>, H_1, M>) => Promise<boolean>;
|
|
46
47
|
/**
|
|
47
|
-
* Typed
|
|
48
|
+
* Typed teardown sender for a method invoked in an effect
|
|
48
49
|
* cleanup. Survives the calling component's unmount, queues while the hub
|
|
49
50
|
* is still connecting instead of dropping, and holds a lazy hub open
|
|
50
|
-
* until the flush completes.
|
|
51
|
-
* `false` if the hub
|
|
51
|
+
* until the flush completes. Resolves `true` if the call is sent.
|
|
52
|
+
* Resolves `false` if the hub does not connect in time,
|
|
53
|
+
* the session is disabled, the hub failed, or the send fails. Never
|
|
54
|
+
* throws.
|
|
52
55
|
*/
|
|
53
56
|
useSignalRTeardown: <H_1 extends keyof H & `/${string}`, M extends import("@dammers/use-signalr-core").MethodName<InferContract<H>, H_1>>(hub: H_1, method: M, options?: import("@dammers/use-signalr-core").TeardownOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<InferContract<H>, H_1, M>) => Promise<boolean>;
|
|
54
57
|
/**
|
|
55
|
-
* Live connection status of a hub. Re-renders only when
|
|
58
|
+
* Live connection status of a hub. Re-renders only when this hub's status
|
|
56
59
|
* changes. Also keeps a lazy hub connected while mounted.
|
|
57
60
|
*/
|
|
58
61
|
useHubStatus: <H_1 extends keyof H & `/${string}`>(hub: H_1) => import("@dammers/use-signalr-core").HubConnectionStatus;
|
|
59
62
|
/**
|
|
60
63
|
* Runs a callback after each reconnect, not the first connect, to refetch
|
|
61
|
-
* state that went stale while offline.
|
|
64
|
+
* state that went stale while offline. It also runs after a rebuild that a
|
|
65
|
+
* `connectionKey`, `baseUrl`, or `enabled` change causes.
|
|
62
66
|
*/
|
|
63
67
|
useOnReconnected: <H_1 extends keyof H & `/${string}`>(hub: H_1, callback: () => void) => void;
|
|
64
68
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createContext } from "react";
|
|
2
2
|
import { hubKeys, resolveHubConfig } from "@dammers/use-signalr-core";
|
|
3
|
-
import { createSignalRProvider } from "./internal/create-provider";
|
|
4
|
-
import { createSignalRHooks } from "./internal/create-hooks";
|
|
3
|
+
import { createSignalRProvider } from "./internal/create-provider.js";
|
|
4
|
+
import { createSignalRHooks } from "./internal/create-hooks.js";
|
|
5
5
|
/**
|
|
6
6
|
* Creates a fully-typed SignalR client. Returns a provider and hooks, typed
|
|
7
7
|
* against the contract inferred from `config.hubs`: the keys declare the
|
|
@@ -10,7 +10,7 @@ import { createSignalRHooks } from "./internal/create-hooks";
|
|
|
10
10
|
*/
|
|
11
11
|
export function createSignalRClient(config) {
|
|
12
12
|
const hubs = hubKeys(config);
|
|
13
|
-
const resolved = new Map(hubs.map((h) => [h, resolveHubConfig(config,
|
|
13
|
+
const resolved = new Map(hubs.map((h) => [h, resolveHubConfig(config, h)]));
|
|
14
14
|
const resolve = (hub) => resolved.get(hub);
|
|
15
15
|
const Context = createContext(null);
|
|
16
16
|
const SignalRProvider = createSignalRProvider(Context, hubs, resolve);
|
|
@@ -23,8 +23,8 @@ export function createSignalRClient(config) {
|
|
|
23
23
|
*/
|
|
24
24
|
SignalRProvider,
|
|
25
25
|
/**
|
|
26
|
-
* Escape hatch to the
|
|
27
|
-
*
|
|
26
|
+
* Escape hatch to the SignalR context (`getConnection`, `getStatus`,
|
|
27
|
+
* and `waitForConnection`). Prefer the typed hooks below. Use this only
|
|
28
28
|
* for the underlying `HubConnection` or a non-reactive point read.
|
|
29
29
|
*/
|
|
30
30
|
useSignalR: hooks.useSignalR,
|
|
@@ -36,38 +36,43 @@ export function createSignalRClient(config) {
|
|
|
36
36
|
useHubConsumer: hooks.useHubConsumer,
|
|
37
37
|
/**
|
|
38
38
|
* Subscribes to a typed server event for the component's lifetime.
|
|
39
|
-
* Handler args are inferred from your contract.
|
|
40
|
-
* reconnects.
|
|
39
|
+
* Handler args are inferred from your contract. The subscription survives
|
|
40
|
+
* reconnects and rebuilds.
|
|
41
41
|
*/
|
|
42
42
|
useSignalREffect: hooks.useSignalREffect,
|
|
43
43
|
/**
|
|
44
44
|
* Typed invoker that waits for the connection and resolves with the
|
|
45
45
|
* method's return value. Fails fast by default. Opt in to retry for
|
|
46
|
-
* idempotent methods only.
|
|
46
|
+
* idempotent methods only. When the component unmounts, a call that still
|
|
47
|
+
* waits rejects with `AbortError`, unless you set `keepAliveOnUnmount`.
|
|
47
48
|
*/
|
|
48
49
|
useSignalRInvoke: hooks.useSignalRInvoke,
|
|
49
50
|
/**
|
|
50
|
-
* Typed fire-and-forget sender.
|
|
51
|
-
*
|
|
52
|
-
*
|
|
51
|
+
* Typed fire-and-forget sender. It does not wait for the connection. It
|
|
52
|
+
* resolves `true` when it sends the call, and `false` when the hub is not
|
|
53
|
+
* connected and it drops the call. It never throws, so a cleanup can call
|
|
54
|
+
* it. For a call that must land in a cleanup, use `useSignalRTeardown`.
|
|
53
55
|
*/
|
|
54
56
|
useSignalRSend: hooks.useSignalRSend,
|
|
55
57
|
/**
|
|
56
|
-
* Typed
|
|
58
|
+
* Typed teardown sender for a method invoked in an effect
|
|
57
59
|
* cleanup. Survives the calling component's unmount, queues while the hub
|
|
58
60
|
* is still connecting instead of dropping, and holds a lazy hub open
|
|
59
|
-
* until the flush completes.
|
|
60
|
-
* `false` if the hub
|
|
61
|
+
* until the flush completes. Resolves `true` if the call is sent.
|
|
62
|
+
* Resolves `false` if the hub does not connect in time,
|
|
63
|
+
* the session is disabled, the hub failed, or the send fails. Never
|
|
64
|
+
* throws.
|
|
61
65
|
*/
|
|
62
66
|
useSignalRTeardown: hooks.useSignalRTeardown,
|
|
63
67
|
/**
|
|
64
|
-
* Live connection status of a hub. Re-renders only when
|
|
68
|
+
* Live connection status of a hub. Re-renders only when this hub's status
|
|
65
69
|
* changes. Also keeps a lazy hub connected while mounted.
|
|
66
70
|
*/
|
|
67
71
|
useHubStatus: hooks.useHubStatus,
|
|
68
72
|
/**
|
|
69
73
|
* Runs a callback after each reconnect, not the first connect, to refetch
|
|
70
|
-
* state that went stale while offline.
|
|
74
|
+
* state that went stale while offline. It also runs after a rebuild that a
|
|
75
|
+
* `connectionKey`, `baseUrl`, or `enabled` change causes.
|
|
71
76
|
*/
|
|
72
77
|
useOnReconnected: hooks.useOnReconnected,
|
|
73
78
|
};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
export { createSignalRClient } from "./create-signalr-client";
|
|
2
|
-
export {
|
|
3
|
-
export type {
|
|
4
|
-
export type {
|
|
5
|
-
export type { SignalRProviderProps, SignalRContextValue } from "./types";
|
|
1
|
+
export { createSignalRClient } from "./create-signalr-client.js";
|
|
2
|
+
export { event, method } from "@dammers/use-signalr-core";
|
|
3
|
+
export type { HubString, HubContract, SignalRContract, SignalRClientConfig, PerHubConfig, HubProtocolConfig, ConfigureBuilder, BuilderContext, HttpOptions, HubDef, EventDef, MethodDef, InferContract, ReconnectConfig, InvokeOptions, TeardownOptions, HubConnectionStatus, SignalRErrorInfo, SignalRPublicContext, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, } from "@dammers/use-signalr-core";
|
|
4
|
+
export type { SignalRProviderProps } from "./types.js";
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { createSignalRClient } from "./create-signalr-client";
|
|
2
|
-
export {
|
|
1
|
+
export { createSignalRClient } from "./create-signalr-client.js";
|
|
2
|
+
export { event, method } from "@dammers/use-signalr-core";
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import type { Context } from "react";
|
|
2
|
-
import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions,
|
|
3
|
-
import type { SignalRContextValue } from "../types";
|
|
2
|
+
import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions, MethodName, SignalRContract, SignalRPublicContext } from "@dammers/use-signalr-core";
|
|
3
|
+
import type { SignalRContextValue } from "../types.js";
|
|
4
4
|
/** Builds the hooks bound to one client's context. */
|
|
5
5
|
export declare function createSignalRHooks<T extends SignalRContract>(ReactContext: Context<SignalRContextValue<T> | null>): {
|
|
6
|
-
useSignalR: () =>
|
|
6
|
+
useSignalR: () => SignalRPublicContext<T>;
|
|
7
7
|
useHubConsumer: (hub: keyof T & `/${string}`) => void;
|
|
8
8
|
useHubStatus: <H extends keyof T & `/${string}`>(hub: H) => HubConnectionStatus;
|
|
9
9
|
useOnReconnected: <H extends keyof T & `/${string}`>(hub: H, callback: () => void) => void;
|
|
10
10
|
useSignalREffect: <H extends keyof T & `/${string}`, E extends EventName<T, H>>(hub: H, event: E, handler: (...args: EventArgs<T, H, E>) => void) => void;
|
|
11
|
-
useSignalRInvoke: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: InvokeOptions) => (...args: MethodArgs<T, H, M>) => Promise<MethodReturn<T, H, M>>;
|
|
12
|
-
useSignalRSend: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M) => (...args: MethodArgs<T, H, M>) => Promise<boolean>;
|
|
13
|
-
useSignalRTeardown: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: TeardownOptions) => (...args: MethodArgs<T, H, M>) => Promise<boolean>;
|
|
11
|
+
useSignalRInvoke: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: InvokeOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<import("@dammers/use-signalr-core").MethodReturn<T, H, M>>;
|
|
12
|
+
useSignalRSend: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M) => (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<boolean>;
|
|
13
|
+
useSignalRTeardown: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: TeardownOptions) => (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<boolean>;
|
|
14
14
|
};
|
|
@@ -1,185 +1,77 @@
|
|
|
1
1
|
import { use, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
|
|
2
|
-
import { useLatest } from "../internal-hooks";
|
|
3
|
-
import { createInvoker, createSender, createTeardownSender } from "@dammers/use-signalr-core";
|
|
2
|
+
import { useLatest } from "../internal-hooks.js";
|
|
3
|
+
import { createAbortScope, createInvoker, createSender, createTeardownSender, } from "@dammers/use-signalr-core";
|
|
4
|
+
const INITIAL_STATUS = "idle";
|
|
4
5
|
/** Builds the hooks bound to one client's context. */
|
|
5
6
|
export function createSignalRHooks(ReactContext) {
|
|
6
|
-
|
|
7
|
-
* Escape hatch to the raw SignalR context. Prefer the typed hooks below.
|
|
8
|
-
* Reach for this only when you need the underlying `HubConnection` or a
|
|
9
|
-
* non-reactive point read.
|
|
10
|
-
*
|
|
11
|
-
* @returns The context value: `getConnection`, `isHubConnected`, `getStatus`,
|
|
12
|
-
* `waitForConnection`, `acquire`/`release`, `registerReconnect`, `statusStore`.
|
|
13
|
-
* @throws If called outside a `<SignalRProvider>`.
|
|
14
|
-
*/
|
|
15
|
-
function useSignalR() {
|
|
7
|
+
function useInternalContext() {
|
|
16
8
|
const ctx = use(ReactContext);
|
|
17
9
|
if (!ctx)
|
|
18
10
|
throw new Error("useSignalR must be used within a SignalRProvider");
|
|
19
11
|
return ctx;
|
|
20
12
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
*
|
|
25
|
-
* Most hooks already do this internally. Use it directly only when you want
|
|
26
|
-
* a lazy hub connected for a component that does not otherwise touch it.
|
|
27
|
-
*
|
|
28
|
-
* @param hub The hub path to keep connected.
|
|
29
|
-
*/
|
|
13
|
+
function useSignalR() {
|
|
14
|
+
return useInternalContext().publicContext;
|
|
15
|
+
}
|
|
30
16
|
function useHubConsumer(hub) {
|
|
31
|
-
const { acquire, release } =
|
|
17
|
+
const { acquire, release } = useInternalContext();
|
|
32
18
|
useEffect(() => {
|
|
33
19
|
acquire(hub);
|
|
34
20
|
return () => release(hub);
|
|
35
21
|
}, [hub, acquire, release]);
|
|
36
22
|
}
|
|
37
|
-
/**
|
|
38
|
-
* Live connection status of a hub. Re-renders the component only when THIS
|
|
39
|
-
* hub's status changes, not when another hub changes. Also keeps the hub
|
|
40
|
-
* alive while mounted, so a lazy hub connects on first use.
|
|
41
|
-
*
|
|
42
|
-
* @param hub The hub path to watch.
|
|
43
|
-
* @returns `"disconnected" | "connecting" | "connected" | "reconnecting" | "reconnected"`.
|
|
44
|
-
*/
|
|
45
23
|
function useHubStatus(hub) {
|
|
46
|
-
const { statusStore } =
|
|
24
|
+
const { statusStore } = useInternalContext();
|
|
47
25
|
useHubConsumer(hub);
|
|
48
|
-
|
|
26
|
+
const subscribe = useMemo(() => (listener) => statusStore.subscribe(hub, listener), [statusStore, hub]);
|
|
27
|
+
return useSyncExternalStore(subscribe, () => statusStore.get(hub), () => INITIAL_STATUS);
|
|
49
28
|
}
|
|
50
|
-
/**
|
|
51
|
-
* Runs a callback every time a hub reconnects, after a dropped connection
|
|
52
|
-
* is re-established, to refetch state that may have gone stale while
|
|
53
|
-
* offline. Does NOT fire on the first connect, only on reconnects.
|
|
54
|
-
*
|
|
55
|
-
* A fresh closure each render is fine — it does not re-subscribe or fire
|
|
56
|
-
* spuriously, so you do not need to memoize the callback.
|
|
57
|
-
*
|
|
58
|
-
* @param hub The hub path to watch.
|
|
59
|
-
* @param callback Invoked after each successful reconnect.
|
|
60
|
-
*/
|
|
61
29
|
function useOnReconnected(hub, callback) {
|
|
62
|
-
const { registerReconnect } =
|
|
30
|
+
const { registerReconnect } = useInternalContext();
|
|
63
31
|
useHubConsumer(hub);
|
|
64
32
|
const cbRef = useLatest(callback);
|
|
65
33
|
useEffect(() => registerReconnect(hub, () => cbRef.current()), [hub, registerReconnect, cbRef]);
|
|
66
34
|
}
|
|
67
|
-
/**
|
|
68
|
-
* Subscribes to a typed server event for the lifetime of the component. The
|
|
69
|
-
* handler's args are inferred from your contract for `(hub, event)`. The
|
|
70
|
-
* subscription attaches once the hub is connected, re-attaches across
|
|
71
|
-
* reconnects, and detaches on unmount.
|
|
72
|
-
*
|
|
73
|
-
* A fresh closure each render is fine — it does not re-subscribe, so you do
|
|
74
|
-
* not need to memoize the handler.
|
|
75
|
-
*
|
|
76
|
-
* @param hub The hub path.
|
|
77
|
-
* @param event The event name, a key of that hub's `events`.
|
|
78
|
-
* @param handler Called with the event's typed args each time the server pushes it.
|
|
79
|
-
*/
|
|
80
35
|
function useSignalREffect(hub, event, handler) {
|
|
81
|
-
const {
|
|
82
|
-
|
|
36
|
+
const { subscribe } = useInternalContext();
|
|
37
|
+
useHubConsumer(hub);
|
|
83
38
|
const handlerRef = useLatest(handler);
|
|
84
|
-
useEffect(() =>
|
|
85
|
-
const connection = getConnection(hub);
|
|
86
|
-
if (!connection || status !== "connected")
|
|
87
|
-
return;
|
|
88
|
-
const listener = (...args) => handlerRef.current(...args);
|
|
89
|
-
connection.on(event, listener);
|
|
90
|
-
return () => connection.off(event, listener);
|
|
91
|
-
}, [hub, event, status, getConnection, handlerRef]);
|
|
39
|
+
useEffect(() => subscribe(hub, event, (...args) => handlerRef.current(...args)), [hub, event, subscribe, handlerRef]);
|
|
92
40
|
}
|
|
93
|
-
/**
|
|
94
|
-
* Returns a stable, typed function that invokes a hub method and resolves
|
|
95
|
-
* with its return value. It waits, up to `timeout`, for the connection
|
|
96
|
-
* before it invokes, so calling right after mount is safe.
|
|
97
|
-
*
|
|
98
|
-
* Special behavior:
|
|
99
|
-
* - **Fails fast by default** (`retries: 0`): rethrows the raw server error,
|
|
100
|
-
* so callers see the original.
|
|
101
|
-
* - **Opt-in retry** for retriable failures (transport drops, timeouts),
|
|
102
|
-
* with jittered backoff. Business errors (a `HubException` thrown while
|
|
103
|
-
* still connected) are never retried.
|
|
104
|
-
* - **At-least-once when retrying.** Enable `retries` only for IDEMPOTENT methods.
|
|
105
|
-
* - **Auto-aborts** any in-flight call or retry loop on unmount, UNLESS
|
|
106
|
-
* `keepAliveOnUnmount: true`. For a method invoked in an effect cleanup,
|
|
107
|
-
* set that flag, or prefer {@link useSignalRTeardown}, which also handles
|
|
108
|
-
* the hub-still-connecting race.
|
|
109
|
-
*
|
|
110
|
-
* @param hub The hub path.
|
|
111
|
-
* @param method The method name, a key of that hub's `methods`.
|
|
112
|
-
* @param options Optional `retries`, `timeout`, `backoff`, `isRetriable`, `keepAliveOnUnmount`.
|
|
113
|
-
* @returns An async fn that takes the method's typed args and resolves to its typed return.
|
|
114
|
-
* @throws The raw error when `retries === 0`. Otherwise an {@link InvokeError}
|
|
115
|
-
* that wraps the last failure once attempts are exhausted.
|
|
116
|
-
*/
|
|
117
41
|
function useSignalRInvoke(hub, method, options) {
|
|
118
|
-
const { waitForConnection, getConnection } =
|
|
42
|
+
const { waitForConnection, getConnection, acquire, release } = useInternalContext();
|
|
119
43
|
useHubConsumer(hub);
|
|
120
44
|
const optsRef = useLatest(options);
|
|
121
|
-
const
|
|
45
|
+
const scopeRef = useRef(null);
|
|
46
|
+
scopeRef.current ?? (scopeRef.current = createAbortScope());
|
|
47
|
+
const scope = scopeRef.current;
|
|
122
48
|
useEffect(() => () => {
|
|
123
49
|
if (!optsRef.current?.keepAliveOnUnmount)
|
|
124
|
-
|
|
125
|
-
}, [optsRef]);
|
|
126
|
-
return useMemo(() => createInvoker({
|
|
127
|
-
|
|
128
|
-
|
|
50
|
+
scope.abort();
|
|
51
|
+
}, [optsRef, scope]);
|
|
52
|
+
return useMemo(() => createInvoker({
|
|
53
|
+
target: { waitForConnection, getConnection, acquire, release },
|
|
54
|
+
hub,
|
|
55
|
+
method,
|
|
56
|
+
getOptions: () => optsRef.current,
|
|
57
|
+
getSignal: scope.signal,
|
|
58
|
+
}), [waitForConnection, getConnection, acquire, release, hub, method, optsRef, scope]);
|
|
129
59
|
}
|
|
130
|
-
/**
|
|
131
|
-
* Returns a stable, typed fire-and-forget sender. Unlike {@link useSignalRInvoke},
|
|
132
|
-
* it does NOT wait for the connection and does NOT return the method's
|
|
133
|
-
* result. If the hub is not Connected, the call is dropped (resolves
|
|
134
|
-
* `false`); otherwise it is dispatched (resolves `true`).
|
|
135
|
-
*
|
|
136
|
-
* Reads the connection at call time and never depends on render-time state,
|
|
137
|
-
* so it is safe to capture in an unmount cleanup.
|
|
138
|
-
*
|
|
139
|
-
* @param hub The hub path.
|
|
140
|
-
* @param method The method name, a key of that hub's `methods`.
|
|
141
|
-
* @returns An async fn that takes the method's typed args and resolves
|
|
142
|
-
* `true` if dispatched, `false` if dropped because it was not connected.
|
|
143
|
-
*/
|
|
144
60
|
function useSignalRSend(hub, method) {
|
|
145
|
-
const { getConnection } =
|
|
61
|
+
const { getConnection } = useInternalContext();
|
|
146
62
|
useHubConsumer(hub);
|
|
147
|
-
return useMemo(() => createSender(getConnection, hub, method), [getConnection, hub, method]);
|
|
63
|
+
return useMemo(() => createSender({ getConnection, hub, method }), [getConnection, hub, method]);
|
|
148
64
|
}
|
|
149
|
-
/**
|
|
150
|
-
* Returns a stable, typed RELIABLE teardown sender, built for a method
|
|
151
|
-
* invoked in an effect cleanup. Unlike {@link useSignalRSend}, which drops
|
|
152
|
-
* a call if not yet connected, and {@link useSignalRInvoke}, which aborts
|
|
153
|
-
* in-flight calls on unmount, the returned function:
|
|
154
|
-
*
|
|
155
|
-
* - **Survives the calling component's unmount.** It runs detached, not
|
|
156
|
-
* tied to any effect or AbortController, so a call issued in cleanup
|
|
157
|
-
* still lands.
|
|
158
|
-
* - **Queues while connecting.** It waits, up to `timeout`, for the hub to
|
|
159
|
-
* (re)connect, then sends, instead of dropping the call.
|
|
160
|
-
* - **Holds a lazy hub open** until the flush completes, even when the
|
|
161
|
-
* calling component was the last consumer — it acquires and releases
|
|
162
|
-
* independently.
|
|
163
|
-
* - **Is best-effort and fire-and-forget.** It resolves `true` once
|
|
164
|
-
* dispatched, `false` if the hub never connected within `timeout`, and
|
|
165
|
-
* never throws.
|
|
166
|
-
*
|
|
167
|
-
* Trade-off: under StrictMode's mount→cleanup→mount, the intermediate
|
|
168
|
-
* teardown DOES fire, and the remount then re-runs setup. This is correct:
|
|
169
|
-
* the server is never left in a stale joined state, at the cost of one
|
|
170
|
-
* extra round-trip.
|
|
171
|
-
*
|
|
172
|
-
* @param hub The hub path.
|
|
173
|
-
* @param method The teardown method name, a key of that hub's `methods`.
|
|
174
|
-
* @param options Optional `timeout` in ms to wait for a connection. Default 10_000.
|
|
175
|
-
* @returns An async fn that takes the method's typed args and resolves
|
|
176
|
-
* `true` if dispatched, `false` if the hub never connected in time.
|
|
177
|
-
*/
|
|
178
65
|
function useSignalRTeardown(hub, method, options) {
|
|
179
|
-
const { acquire, release, waitForConnection } =
|
|
66
|
+
const { acquire, release, waitForConnection } = useInternalContext();
|
|
180
67
|
useHubConsumer(hub);
|
|
181
68
|
const optsRef = useLatest(options);
|
|
182
|
-
return useMemo(() => createTeardownSender({
|
|
69
|
+
return useMemo(() => createTeardownSender({
|
|
70
|
+
target: { acquire, release, waitForConnection },
|
|
71
|
+
hub,
|
|
72
|
+
method,
|
|
73
|
+
getOptions: () => optsRef.current,
|
|
74
|
+
}), [acquire, release, waitForConnection, hub, method, optsRef]);
|
|
183
75
|
}
|
|
184
76
|
return {
|
|
185
77
|
useSignalR,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Context } from "react";
|
|
2
2
|
import type { HubString, ResolvedHubConfig, SignalRContract } from "@dammers/use-signalr-core";
|
|
3
|
-
import type { SignalRContextValue, SignalRProviderProps } from "../types";
|
|
3
|
+
import type { SignalRContextValue, SignalRProviderProps } from "../types.js";
|
|
4
4
|
/** Builds the `SignalRProvider` component bound to one client's context. */
|
|
5
|
-
export declare function createSignalRProvider<T extends SignalRContract>(ReactContext: Context<SignalRContextValue<T> | null>, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: SignalRProviderProps) => import("react").JSX.Element;
|
|
5
|
+
export declare function createSignalRProvider<T extends SignalRContract>(ReactContext: Context<SignalRContextValue<T> | null>, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): ({ children, baseUrl, accessTokenFactory, enabled, connectionKey, onStatusChange, onError, }: SignalRProviderProps<keyof T & `/${string}`>) => import("react").JSX.Element;
|
|
@@ -1,87 +1,37 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
-
import { useEffect,
|
|
3
|
-
import { useLatest } from "../internal-hooks";
|
|
4
|
-
import { createStatusStore } from "../status-store";
|
|
5
|
-
import {
|
|
2
|
+
import { useEffect, useRef } from "react";
|
|
3
|
+
import { useLatest } from "../internal-hooks.js";
|
|
4
|
+
import { createStatusStore } from "../status-store.js";
|
|
5
|
+
import { createSignalRSession } from "@dammers/use-signalr-core";
|
|
6
6
|
/** Builds the `SignalRProvider` component bound to one client's context. */
|
|
7
7
|
export function createSignalRProvider(ReactContext, hubs, resolve) {
|
|
8
8
|
return function SignalRProvider({ children, baseUrl, accessTokenFactory, enabled = true, connectionKey, onStatusChange, onError, }) {
|
|
9
|
-
const statusStore = useRef(createStatusStore()).current;
|
|
10
|
-
// Lazy ref-counts, pending stop timers, and reconnect listeners persist
|
|
11
|
-
// across rebuilds. The live manager is swapped per generation.
|
|
12
|
-
const refCounts = useRef(new Map()).current;
|
|
13
|
-
const stopTimers = useRef(new Map()).current;
|
|
14
|
-
const reconnectListeners = useRef(new Map()).current;
|
|
15
|
-
const managerRef = useRef(null);
|
|
16
|
-
// Latest props via refs, so once-attached handlers call the current props.
|
|
17
9
|
const tokenFactoryRef = useLatest(accessTokenFactory);
|
|
18
10
|
const onStatusChangeRef = useLatest(onStatusChange);
|
|
19
11
|
const onErrorRef = useLatest(onError);
|
|
12
|
+
const sessionRef = useRef(null);
|
|
13
|
+
sessionRef.current ?? (sessionRef.current = createSignalRSession({
|
|
14
|
+
hubs,
|
|
15
|
+
resolve,
|
|
16
|
+
statusStore: createStatusStore(),
|
|
17
|
+
getAccessToken: () => tokenFactoryRef.current(),
|
|
18
|
+
onStatusChange: (hub, status) => onStatusChangeRef.current?.(hub, status),
|
|
19
|
+
onError: (hub, err, info) => onErrorRef.current?.(hub, err, info),
|
|
20
|
+
}));
|
|
21
|
+
const session = sessionRef.current;
|
|
22
|
+
const stopPending = useRef(false);
|
|
20
23
|
useEffect(() => {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
managerRef.current = null;
|
|
24
|
-
hubs.forEach((h) => statusStore.set(h, "disconnected"));
|
|
25
|
-
return;
|
|
26
|
-
}
|
|
27
|
-
const manager = createConnectionManager({
|
|
28
|
-
baseUrl,
|
|
29
|
-
hubs,
|
|
30
|
-
resolve,
|
|
31
|
-
getAccessToken: () => tokenFactoryRef.current(),
|
|
32
|
-
refCounts,
|
|
33
|
-
stopTimers,
|
|
34
|
-
reconnectListeners,
|
|
35
|
-
onStatus: (hub, status) => {
|
|
36
|
-
statusStore.set(hub, status);
|
|
37
|
-
onStatusChangeRef.current?.(hub, status);
|
|
38
|
-
},
|
|
39
|
-
onError: (hub, err) => onErrorRef.current?.(hub, err),
|
|
40
|
-
isCurrent: () => managerRef.current === manager,
|
|
41
|
-
});
|
|
42
|
-
managerRef.current = manager;
|
|
43
|
-
manager.reconcile(); // build eager hubs plus already-referenced lazy hubs
|
|
24
|
+
stopPending.current = false;
|
|
25
|
+
session.update({ baseUrl, enabled, connectionKey });
|
|
44
26
|
return () => {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
27
|
+
stopPending.current = true;
|
|
28
|
+
// StrictMode re-runs the effect synchronously, so a deferred stop can be cancelled.
|
|
29
|
+
queueMicrotask(() => {
|
|
30
|
+
if (stopPending.current)
|
|
31
|
+
session.stop();
|
|
32
|
+
});
|
|
48
33
|
};
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
52
|
-
}, [baseUrl, enabled, connectionKey]);
|
|
53
|
-
const value = useMemo(() => ({
|
|
54
|
-
getConnection: (hub) => managerRef.current?.getConnection(hub) ?? null,
|
|
55
|
-
isHubConnected: (hub) => statusStore.get(hub) === "connected",
|
|
56
|
-
getStatus: (hub) => statusStore.get(hub),
|
|
57
|
-
statusStore,
|
|
58
|
-
waitForConnection: (hub, timeoutMs) => {
|
|
59
|
-
const manager = managerRef.current;
|
|
60
|
-
if (!manager) {
|
|
61
|
-
return Promise.reject(new Error(`SignalR not connected: ${String(hub)}`));
|
|
62
|
-
}
|
|
63
|
-
return manager.waitForConnection(hub, timeoutMs);
|
|
64
|
-
},
|
|
65
|
-
acquire: (hub) => {
|
|
66
|
-
const next = (refCounts.get(hub) ?? 0) + 1;
|
|
67
|
-
refCounts.set(hub, next);
|
|
68
|
-
if (next === 1)
|
|
69
|
-
managerRef.current?.reconcile();
|
|
70
|
-
},
|
|
71
|
-
release: (hub) => {
|
|
72
|
-
const next = Math.max(0, (refCounts.get(hub) ?? 0) - 1);
|
|
73
|
-
refCounts.set(hub, next);
|
|
74
|
-
if (next === 0)
|
|
75
|
-
managerRef.current?.reconcile();
|
|
76
|
-
},
|
|
77
|
-
registerReconnect: (hub, cb) => {
|
|
78
|
-
let set = reconnectListeners.get(hub);
|
|
79
|
-
if (!set)
|
|
80
|
-
reconnectListeners.set(hub, (set = new Set()));
|
|
81
|
-
set.add(cb);
|
|
82
|
-
return () => set.delete(cb);
|
|
83
|
-
},
|
|
84
|
-
}), [statusStore, refCounts, reconnectListeners]);
|
|
85
|
-
return _jsx(ReactContext, { value: value, children: children });
|
|
34
|
+
}, [session, baseUrl, enabled, connectionKey]);
|
|
35
|
+
return _jsx(ReactContext, { value: session.context, children: children });
|
|
86
36
|
};
|
|
87
37
|
}
|
package/dist/status-store.d.ts
CHANGED
|
@@ -1,11 +1,7 @@
|
|
|
1
1
|
import type { StatusStore as StatusStoreBase } from "@dammers/use-signalr-core";
|
|
2
|
-
/**
|
|
3
|
-
* Small external store for hub statuses, consumed with `useSyncExternalStore`.
|
|
4
|
-
* Exposes only `subscribe`, `get`, and `set` — no whole-record snapshot — so
|
|
5
|
-
* a per-hub selector lets React skip a re-render when an unrelated hub's
|
|
6
|
-
* status changes.
|
|
7
|
-
*/
|
|
2
|
+
/** External store for hub statuses, read with `useSyncExternalStore`. */
|
|
8
3
|
export interface StatusStore<H extends string> extends StatusStoreBase<H> {
|
|
9
|
-
subscribe: (listener: () => void) => () => void;
|
|
4
|
+
subscribe: (hub: H, listener: () => void) => () => void;
|
|
10
5
|
}
|
|
6
|
+
/** Separate listener sets keep status updates granular per hub. */
|
|
11
7
|
export declare function createStatusStore<H extends string>(): StatusStore<H>;
|
package/dist/status-store.js
CHANGED
|
@@ -1,17 +1,21 @@
|
|
|
1
|
+
/** Separate listener sets keep status updates granular per hub. */
|
|
1
2
|
export function createStatusStore() {
|
|
2
3
|
const snapshot = new Map();
|
|
3
|
-
const listeners = new
|
|
4
|
+
const listeners = new Map();
|
|
4
5
|
return {
|
|
5
|
-
subscribe: (listener) => {
|
|
6
|
-
listeners.
|
|
7
|
-
|
|
6
|
+
subscribe: (hub, listener) => {
|
|
7
|
+
let set = listeners.get(hub);
|
|
8
|
+
if (!set)
|
|
9
|
+
listeners.set(hub, (set = new Set()));
|
|
10
|
+
set.add(listener);
|
|
11
|
+
return () => set.delete(listener);
|
|
8
12
|
},
|
|
9
|
-
get: (hub) => snapshot.get(hub) ?? "
|
|
13
|
+
get: (hub) => snapshot.get(hub) ?? "idle",
|
|
10
14
|
set: (hub, status) => {
|
|
11
15
|
if (snapshot.get(hub) === status)
|
|
12
16
|
return; // dedupe: skip a spurious notify
|
|
13
17
|
snapshot.set(hub, status);
|
|
14
|
-
listeners.forEach((l) => l());
|
|
18
|
+
listeners.get(hub)?.forEach((l) => l());
|
|
15
19
|
},
|
|
16
20
|
};
|
|
17
21
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { ReactNode } from "react";
|
|
2
2
|
import type { HubString, SignalRContract, SignalRProviderPropsBase, SignalRContextValueBase } from "@dammers/use-signalr-core";
|
|
3
|
-
import type { StatusStore } from "./status-store";
|
|
4
|
-
export type SignalRProviderProps = SignalRProviderPropsBase<
|
|
3
|
+
import type { StatusStore } from "./status-store.js";
|
|
4
|
+
export type SignalRProviderProps<THub extends HubString = HubString> = SignalRProviderPropsBase<THub> & {
|
|
5
|
+
/** The component tree that uses the hooks. */
|
|
6
|
+
children: ReactNode;
|
|
7
|
+
};
|
|
5
8
|
export type SignalRContextValue<T extends SignalRContract> = SignalRContextValueBase<T, StatusStore<keyof T & HubString>>;
|
package/package.json
CHANGED
|
@@ -1,12 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dammers/use-signalr-react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "Fully-typed multi-hub SignalR provider + hooks for React: auto-reconnect, invoke retry, lazy hubs, live status.",
|
|
5
5
|
"author": "Dammers",
|
|
6
6
|
"license": "MIT",
|
|
7
|
-
"repository":
|
|
8
|
-
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/DammersCode/use-signalr.git",
|
|
10
|
+
"directory": "packages/react"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://use-signalr.vercel.app/docs/react",
|
|
9
13
|
"bugs": "https://github.com/DammersCode/use-signalr/issues",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"signalr",
|
|
16
|
+
"typescript",
|
|
17
|
+
"realtime",
|
|
18
|
+
"websocket",
|
|
19
|
+
"react",
|
|
20
|
+
"hooks"
|
|
21
|
+
],
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=20.19"
|
|
24
|
+
},
|
|
10
25
|
"type": "module",
|
|
11
26
|
"sideEffects": false,
|
|
12
27
|
"main": "./dist/index.js",
|
|
@@ -14,8 +29,10 @@
|
|
|
14
29
|
"exports": {
|
|
15
30
|
".": {
|
|
16
31
|
"types": "./dist/index.d.ts",
|
|
17
|
-
"import": "./dist/index.js"
|
|
18
|
-
|
|
32
|
+
"import": "./dist/index.js",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
},
|
|
35
|
+
"./package.json": "./package.json"
|
|
19
36
|
},
|
|
20
37
|
"files": [
|
|
21
38
|
"dist"
|
|
@@ -24,23 +41,23 @@
|
|
|
24
41
|
"access": "public"
|
|
25
42
|
},
|
|
26
43
|
"scripts": {
|
|
44
|
+
"prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
|
|
27
45
|
"build": "tsc -p tsconfig.build.json",
|
|
28
46
|
"typecheck": "tsc --noEmit",
|
|
29
47
|
"test": "vitest run"
|
|
30
48
|
},
|
|
31
49
|
"dependencies": {
|
|
32
|
-
"@dammers/use-signalr-core": "0.
|
|
50
|
+
"@dammers/use-signalr-core": "1.0.0"
|
|
33
51
|
},
|
|
34
52
|
"peerDependencies": {
|
|
35
|
-
"@microsoft/signalr": "
|
|
36
|
-
"react": "
|
|
37
|
-
"react-dom": ">=19"
|
|
53
|
+
"@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0",
|
|
54
|
+
"react": "^19.0.0"
|
|
38
55
|
},
|
|
39
56
|
"devDependencies": {
|
|
40
|
-
"@microsoft/signalr": "
|
|
57
|
+
"@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0",
|
|
41
58
|
"@testing-library/react": "^16.1.0",
|
|
42
|
-
"@types/react": "
|
|
43
|
-
"react": "
|
|
44
|
-
"react-dom": "
|
|
59
|
+
"@types/react": "^19.0.0",
|
|
60
|
+
"react": "^19.0.0",
|
|
61
|
+
"react-dom": "^19.0.0"
|
|
45
62
|
}
|
|
46
63
|
}
|