@dammers/use-signalr-core 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DammersCode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # @dammers/use-signalr-core
2
+
3
+ Framework-free connection lifecycle, contracts, and retry logic for [SignalR](https://learn.microsoft.com/aspnet/core/signalr): the shared engine behind `@dammers/use-signalr-react` and `@dammers/use-signalr-solid`.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@dammers/use-signalr-core.svg)](https://www.npmjs.com/package/@dammers/use-signalr-core)
6
+ ![types](https://img.shields.io/badge/types-included-blue.svg)
7
+ [![license](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
8
+
9
+ ## Who needs this
10
+
11
+ Adapter authors — if you are building bindings for a framework this repo does not already cover. This package has no provider, no hooks, no reactive layer: it owns connection lifecycle, contract types, and retry/backoff math, and leaves rendering to the adapter.
12
+
13
+ Building an app? Install `@dammers/use-signalr-react` or `@dammers/use-signalr-solid` instead — this package is a dependency of both, not something you install directly.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ npm i @dammers/use-signalr-core @microsoft/signalr
19
+ ```
20
+
21
+ Requires `@microsoft/signalr` ≥ 8.
22
+
23
+ ## What it exposes
24
+
25
+ | Export | What it does |
26
+ | ---------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
27
+ | `createConnectionManager(deps)` | Owns one provider generation's `HubConnection`s: build, start with retry, lazy ref-counted start/stop, reconnect fan-out. No framework dependency — driven by callbacks. |
28
+ | `createInvoker(deps, hub, method, getOptions, onAbort)` | Builds the request/response call function behind an invoke hook: waits for connection, retries idempotent failures, rethrows business errors. |
29
+ | `createSender(getConnection, hub, method)` | Builds the fire-and-forget call function behind a send hook: drops if not connected. |
30
+ | `createTeardownSender(deps, hub, method, getOptions)` | Builds the reliable teardown call function: survives disposal, queues while connecting, holds a lazy hub open until flushed. |
31
+ | `event<Args>()` / `method<Args, Return?>()` | Contract markers used inside `hubs.<path>.events` / `.methods` to declare what a hub pushes and what it accepts. |
32
+ | `hubKeys(config)`, `resolveHubConfig(config, hubConfig)` | Resolve per-hub config against global defaults. |
33
+ | `isRetriableConnectError`, `isRetriableInvokeError`, `resolveBackoff`, `DEFAULT_BACKOFF`, `sleep`, `InvokeError` | Retry/backoff building blocks and the error type thrown once an invoke's attempts are exhausted. |
34
+
35
+ Plus the contract and config types: `HubString`, `HubContract`, `SignalRContract`, `EventDef`, `MethodDef`, `HubDef`, `InferContract`, `EventName`, `MethodName`, `EventArgs`, `MethodArgs`, `MethodReturn`, `HubConnectionStatus`, `ReconnectConfig`, `PerHubConfig`, `SignalRClientConfig`, `ResolvedHubConfig`, `InvokeOptions`, `TeardownOptions`, `StatusStore`, `SignalRProviderPropsBase`, `SignalRContextValueBase`, `ConnectionManager`, `ConnectionManagerDeps`, `HubEntry`, `CallTarget`.
36
+
37
+ An adapter wraps `createConnectionManager` in its own reactive provider (context + hooks + a status store built on its framework's primitives), and wraps the three call factories in hooks that supply the framework's own acquire/release and abort/cleanup lifecycle. See `packages/react` and `packages/solid` in this repo for two full implementations.
38
+
39
+ ## More
40
+
41
+ Shared concepts (the contract, per-hub config, invoke retry, send vs invoke vs teardown) live in the [root README](https://github.com/DammersCode/use-signalr#readme).
42
+
43
+ ## License
44
+
45
+ MIT © [DammersCode](https://github.com/DammersCode)
@@ -0,0 +1,31 @@
1
+ import type { HubConnection } from "@microsoft/signalr";
2
+ import type { HubString, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "./types";
3
+ export interface CallTarget<T extends SignalRContract> {
4
+ waitForConnection: (hub: keyof T & HubString, timeoutMs: number) => Promise<HubConnection>;
5
+ getConnection: (hub: keyof T & HubString) => HubConnection | null;
6
+ }
7
+ /**
8
+ * Builds the stable invoke function for `useSignalRInvoke`. `getOptions` is
9
+ * called at CALL time (not build time), so the adapter can pass a ref/latest
10
+ * accessor and preserve latest-options semantics. `setAbort` is called once
11
+ * per invocation with the new controller, so the adapter's unmount/cleanup
12
+ * handler can abort the in-flight call.
13
+ */
14
+ export declare function createInvoker<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(target: CallTarget<T>, hub: H, method: M, getOptions: () => InvokeOptions | undefined, setAbort: (ac: AbortController) => void): (...args: MethodArgs<T, H, M>) => Promise<MethodReturn<T, H, M>>;
15
+ /**
16
+ * Builds the stable fire-and-forget sender for `useSignalRSend`. Reads the
17
+ * connection at call time and never depends on render/tracked state, so it
18
+ * is safe to capture in an unmount/cleanup handler.
19
+ */
20
+ export declare function createSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(getConnection: (hub: H) => HubConnection | null, hub: H, method: M): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
21
+ /**
22
+ * Builds the stable RELIABLE teardown sender for `useSignalRTeardown`. Runs
23
+ * detached from the caller's lifecycle: it acquires the hub itself, waits
24
+ * for a connection, sends, then releases — independent of the component
25
+ * that created it having already unmounted.
26
+ */
27
+ export declare function createTeardownSender<T extends SignalRContract, H extends keyof T & HubString, M extends MethodName<T, H>>(deps: {
28
+ acquire: (hub: H) => void;
29
+ release: (hub: H) => void;
30
+ waitForConnection: (hub: H, timeoutMs: number) => Promise<HubConnection>;
31
+ }, hub: H, method: M, getOptions: () => TeardownOptions | undefined): (...args: MethodArgs<T, H, M>) => Promise<boolean>;
package/dist/calls.js ADDED
@@ -0,0 +1,82 @@
1
+ import { HubConnectionState } from "@microsoft/signalr";
2
+ import { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry";
3
+ const DEFAULT_TIMEOUT = 10000;
4
+ const DEFAULT_TEARDOWN_TIMEOUT = 10000;
5
+ /**
6
+ * Builds the stable invoke function for `useSignalRInvoke`. `getOptions` is
7
+ * called at CALL time (not build time), so the adapter can pass a ref/latest
8
+ * accessor and preserve latest-options semantics. `setAbort` is called once
9
+ * per invocation with the new controller, so the adapter's unmount/cleanup
10
+ * handler can abort the in-flight call.
11
+ */
12
+ export function createInvoker(target, hub, method, getOptions, setAbort) {
13
+ const { waitForConnection, getConnection } = target;
14
+ return async (...args) => {
15
+ const o = getOptions();
16
+ const timeout = o?.timeout ?? DEFAULT_TIMEOUT;
17
+ const retries = o?.retries ?? 0;
18
+ const ac = new AbortController();
19
+ setAbort(ac);
20
+ let attempt = 0;
21
+ for (;;) {
22
+ try {
23
+ const connection = await waitForConnection(hub, timeout);
24
+ return await connection.invoke(method, ...args);
25
+ }
26
+ catch (error) {
27
+ const conn = getConnection(hub);
28
+ const forced = o?.isRetriable?.(error);
29
+ const retriable = forced ?? (conn ? isRetriableInvokeError(error, conn) : true);
30
+ if (!retriable || attempt >= retries) {
31
+ // No retries: rethrow the raw error, so callers see the original.
32
+ if (retries === 0)
33
+ throw error;
34
+ throw new InvokeError(`SignalR invoke ${hub}/${String(method)} failed after ${attempt + 1} attempts`, error, attempt + 1, retriable);
35
+ }
36
+ await sleep(resolveBackoff(o?.backoff ?? DEFAULT_BACKOFF, attempt), ac.signal);
37
+ attempt += 1;
38
+ }
39
+ }
40
+ };
41
+ }
42
+ /**
43
+ * Builds the stable fire-and-forget sender for `useSignalRSend`. Reads the
44
+ * connection at call time and never depends on render/tracked state, so it
45
+ * is safe to capture in an unmount/cleanup handler.
46
+ */
47
+ export function createSender(getConnection, hub, method) {
48
+ return (...args) => {
49
+ const connection = getConnection(hub);
50
+ if (!connection || connection.state !== HubConnectionState.Connected) {
51
+ return Promise.resolve(false); // dropped: not connected
52
+ }
53
+ // send() is variadic and untyped; args are enforced at the call site.
54
+ return connection.send(method, ...args).then(() => true);
55
+ };
56
+ }
57
+ /**
58
+ * Builds the stable RELIABLE teardown sender for `useSignalRTeardown`. Runs
59
+ * detached from the caller's lifecycle: it acquires the hub itself, waits
60
+ * for a connection, sends, then releases — independent of the component
61
+ * that created it having already unmounted.
62
+ */
63
+ export function createTeardownSender(deps, hub, method, getOptions) {
64
+ const { acquire, release, waitForConnection } = deps;
65
+ return (...args) => {
66
+ const timeout = getOptions()?.timeout ?? DEFAULT_TEARDOWN_TIMEOUT;
67
+ acquire(hub); // hold the hub open past our own unmount, until flushed
68
+ return (async () => {
69
+ try {
70
+ const connection = await waitForConnection(hub, timeout);
71
+ await connection.send(method, ...args);
72
+ return true;
73
+ }
74
+ catch {
75
+ return false; // never connected in time, or the send failed: best-effort
76
+ }
77
+ finally {
78
+ release(hub);
79
+ }
80
+ })();
81
+ };
82
+ }
@@ -0,0 +1,11 @@
1
+ import type { HubDef, HubString, ResolvedHubConfig, SignalRClientConfig } from "./types";
2
+ /** Typed `Object.keys`. Narrows the keys to the declared hubs. */
3
+ export declare function hubKeys<H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): Array<keyof H & HubString>;
4
+ /** Merge a hub's per-hub config over the global defaults. */
5
+ export declare function resolveHubConfig<H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>, perHub: HubDef | undefined): ResolvedHubConfig;
6
+ /**
7
+ * Checks whether a FIRST-CONNECT failure is worth a retry. Permanent
8
+ * negotiate failures (auth, wrong path, bad request) are not — a retry just
9
+ * hammers the server. Network, transient, and 5xx failures are worth a retry.
10
+ */
11
+ export declare function isRetriableConnectError(err: unknown): boolean;
package/dist/config.js ADDED
@@ -0,0 +1,32 @@
1
+ import { HttpError, LogLevel } from "@microsoft/signalr";
2
+ /** Typed `Object.keys`. Narrows the keys to the declared hubs. */
3
+ export function hubKeys(config) {
4
+ return Object.keys(config.hubs);
5
+ }
6
+ /** Merge a hub's per-hub config over the global defaults. */
7
+ export function resolveHubConfig(config, perHub) {
8
+ return {
9
+ lazy: perHub?.lazy ?? config.lazy ?? false,
10
+ graceMs: perHub?.graceMs ?? 0,
11
+ reconnect: perHub?.reconnect ?? config.reconnect ?? true,
12
+ maxConnectRetries: perHub?.maxConnectRetries ?? config.maxConnectRetries ?? 2,
13
+ logLevel: perHub?.logLevel ?? config.logLevel ?? LogLevel.Information,
14
+ transport: perHub?.transport,
15
+ skipNegotiation: perHub?.skipNegotiation,
16
+ events: Object.keys(perHub?.events ?? {}),
17
+ };
18
+ }
19
+ /**
20
+ * Checks whether a FIRST-CONNECT failure is worth a retry. Permanent
21
+ * negotiate failures (auth, wrong path, bad request) are not — a retry just
22
+ * hammers the server. Network, transient, and 5xx failures are worth a retry.
23
+ */
24
+ export function isRetriableConnectError(err) {
25
+ if (err instanceof HttpError) {
26
+ const s = err.statusCode;
27
+ if (s === 400 || s === 401 || s === 403 || s === 404)
28
+ return false;
29
+ return true; // 0 (network), 408, 429, 5xx, and other transient codes
30
+ }
31
+ return true; // timeout, transport, or unknown error: retry
32
+ }
@@ -0,0 +1,33 @@
1
+ import type { HubConnection } from "@microsoft/signalr";
2
+ import type { HubConnectionStatus, HubString, ResolvedHubConfig } from "./types";
3
+ export interface ConnectionManagerDeps<Hub extends HubString> {
4
+ baseUrl: string;
5
+ hubs: Hub[];
6
+ resolve: (hub: Hub) => ResolvedHubConfig;
7
+ /** Read fresh on every (re)negotiate, so token rotation needs no rebuild. */
8
+ getAccessToken: () => string | Promise<string>;
9
+ /** Per-hub ref-counts, shared across rebuilds, for the lazy lifecycle. */
10
+ refCounts: Map<Hub, number>;
11
+ /** Pending lazy-stop timers, shared across rebuilds. */
12
+ stopTimers: Map<Hub, ReturnType<typeof setTimeout>>;
13
+ reconnectListeners: Map<Hub, Set<() => void>>;
14
+ onStatus: (hub: Hub, status: HubConnectionStatus) => void;
15
+ onError: (hub: Hub, error: unknown) => void;
16
+ /** True while this manager's generation is the live one. Guards stale rebuilds. */
17
+ isCurrent: () => boolean;
18
+ }
19
+ export interface ConnectionManager<Hub extends HubString> {
20
+ /** Builds/starts desired hubs and stops undesired ones. Safe to call repeatedly. */
21
+ reconcile: () => void;
22
+ getConnection: (hub: Hub) => HubConnection | null;
23
+ /** Resolves once the hub is connected. Rejects after timeoutMs otherwise. */
24
+ waitForConnection: (hub: Hub, timeoutMs: number) => Promise<HubConnection>;
25
+ /** Stops all connections and cancels timers. */
26
+ dispose: () => void;
27
+ }
28
+ /**
29
+ * Owns the HubConnection lifecycle for one provider generation: building,
30
+ * starting with retry, lazy ref-counted start/stop, and reconnect fan-out.
31
+ * Has no React dependency — driven by the provider's effect and context callbacks.
32
+ */
33
+ export declare function createConnectionManager<Hub extends HubString>(deps: ConnectionManagerDeps<Hub>): ConnectionManager<Hub>;
@@ -0,0 +1,186 @@
1
+ import { HubConnectionBuilder, HubConnectionState } from "@microsoft/signalr";
2
+ import { isRetriableConnectError } from "./config";
3
+ const CONNECT_RETRY_BASE_MS = 2500;
4
+ function noop() { }
5
+ /**
6
+ * Owns the HubConnection lifecycle for one provider generation: building,
7
+ * starting with retry, lazy ref-counted start/stop, and reconnect fan-out.
8
+ * Has no React dependency — driven by the provider's effect and context callbacks.
9
+ */
10
+ export function createConnectionManager(deps) {
11
+ const { baseUrl, hubs, resolve, getAccessToken, refCounts, stopTimers, reconnectListeners, onStatus, onError, isCurrent, } = deps;
12
+ const built = new Map();
13
+ let disposing = false;
14
+ const setStatus = (hub, status) => {
15
+ const e = built.get(hub);
16
+ if (e)
17
+ e.status = status;
18
+ onStatus(hub, status);
19
+ };
20
+ const clearStopTimer = (hub) => {
21
+ const id = stopTimers.get(hub);
22
+ if (id !== undefined) {
23
+ clearTimeout(id);
24
+ stopTimers.delete(hub);
25
+ }
26
+ };
27
+ const applyReconnect = (builder, reconnect) => {
28
+ if (reconnect === true)
29
+ builder.withAutomaticReconnect();
30
+ else if (Array.isArray(reconnect))
31
+ builder.withAutomaticReconnect(reconnect);
32
+ else if (reconnect !== false)
33
+ builder.withAutomaticReconnect(reconnect);
34
+ };
35
+ const buildAndStart = (hub) => {
36
+ if (disposing || built.has(hub))
37
+ return;
38
+ clearStopTimer(hub);
39
+ const rc = resolve(hub);
40
+ const builder = new HubConnectionBuilder()
41
+ .withUrl(`${baseUrl}${hub}`, {
42
+ accessTokenFactory: () => Promise.resolve(getAccessToken()),
43
+ transport: rc.transport,
44
+ skipNegotiation: rc.skipNegotiation,
45
+ })
46
+ .configureLogging(rc.logLevel);
47
+ applyReconnect(builder, rc.reconnect);
48
+ const conn = builder.build();
49
+ // Pre-bind declared client events, so a server push never hits zero handlers.
50
+ for (const ev of rc.events)
51
+ conn.on(ev, noop);
52
+ let resolveReady;
53
+ const ready = new Promise((res) => {
54
+ resolveReady = res;
55
+ });
56
+ const entry = {
57
+ connection: conn,
58
+ status: "connecting",
59
+ ready,
60
+ resolveReady,
61
+ stopping: false,
62
+ };
63
+ built.set(hub, entry);
64
+ // Attach lifecycle handlers ONCE — SignalR has no removal API.
65
+ conn.onclose((err) => {
66
+ // A deliberate stop() (logout, rebuild, lazy stop) leaves err undefined: stay silent.
67
+ if (disposing || err === undefined) {
68
+ setStatus(hub, "disconnected");
69
+ return;
70
+ }
71
+ setStatus(hub, "disconnected");
72
+ onError(hub, err);
73
+ });
74
+ conn.onreconnecting(() => setStatus(hub, "reconnecting"));
75
+ conn.onreconnected(() => {
76
+ entry.resolveReady();
77
+ if (!disposing && isCurrent()) {
78
+ onStatus(hub, "reconnected");
79
+ reconnectListeners.get(hub)?.forEach((cb) => cb());
80
+ }
81
+ setStatus(hub, "connected");
82
+ });
83
+ let retries = 0;
84
+ const start = async () => {
85
+ if (disposing || entry.stopping)
86
+ return;
87
+ if (conn.state !== HubConnectionState.Disconnected)
88
+ return;
89
+ try {
90
+ await conn.start();
91
+ if (disposing || entry.stopping)
92
+ return;
93
+ entry.resolveReady();
94
+ setStatus(hub, "connected");
95
+ }
96
+ catch (err) {
97
+ if (disposing || entry.stopping)
98
+ return;
99
+ if (!isRetriableConnectError(err) || retries >= rc.maxConnectRetries) {
100
+ setStatus(hub, "disconnected");
101
+ onError(hub, err);
102
+ return;
103
+ }
104
+ retries += 1;
105
+ setStatus(hub, "disconnected");
106
+ setTimeout(start, CONNECT_RETRY_BASE_MS * retries);
107
+ }
108
+ };
109
+ void start();
110
+ };
111
+ const scheduleStop = (hub) => {
112
+ const entry = built.get(hub);
113
+ if (!entry)
114
+ return;
115
+ const { graceMs } = resolve(hub);
116
+ clearStopTimer(hub);
117
+ const stopNow = () => {
118
+ stopTimers.delete(hub);
119
+ if ((refCounts.get(hub) ?? 0) > 0)
120
+ return; // re-acquired during the grace period
121
+ const e = built.get(hub);
122
+ if (!e || e.stopping)
123
+ return;
124
+ e.stopping = true;
125
+ built.delete(hub);
126
+ setStatus(hub, "disconnected");
127
+ void e.connection.stop();
128
+ };
129
+ if (graceMs <= 0)
130
+ queueMicrotask(stopNow);
131
+ else
132
+ stopTimers.set(hub, setTimeout(stopNow, graceMs));
133
+ };
134
+ const desired = () => {
135
+ const out = new Set();
136
+ for (const hub of hubs) {
137
+ const rc = resolve(hub);
138
+ if (!rc.lazy)
139
+ out.add(hub);
140
+ else if ((refCounts.get(hub) ?? 0) > 0)
141
+ out.add(hub);
142
+ }
143
+ return out;
144
+ };
145
+ const reconcile = () => {
146
+ if (disposing)
147
+ return;
148
+ const want = desired();
149
+ for (const hub of want)
150
+ if (!built.has(hub))
151
+ buildAndStart(hub);
152
+ for (const hub of built.keys())
153
+ if (!want.has(hub))
154
+ scheduleStop(hub);
155
+ };
156
+ const getConnection = (hub) => built.get(hub)?.connection ?? null;
157
+ const waitForConnection = async (hub, timeoutMs) => {
158
+ const sync = built.get(hub);
159
+ if (sync && sync.connection.state === HubConnectionState.Connected) {
160
+ return sync.connection;
161
+ }
162
+ const deadline = Date.now() + timeoutMs;
163
+ while (Date.now() < deadline) {
164
+ const entry = built.get(hub);
165
+ if (entry?.connection.state === HubConnectionState.Connected) {
166
+ return entry.connection;
167
+ }
168
+ const timeout = new Promise((res) => setTimeout(() => res("timeout"), deadline - Date.now()));
169
+ const result = await Promise.race([
170
+ entry?.ready.then(() => "ready") ?? timeout,
171
+ timeout,
172
+ ]);
173
+ if (result === "timeout")
174
+ break;
175
+ }
176
+ throw new Error(`Timeout waiting for SignalR connection to ${hub} (${timeoutMs}ms)`);
177
+ };
178
+ const dispose = () => {
179
+ disposing = true;
180
+ stopTimers.forEach((id) => clearTimeout(id));
181
+ stopTimers.clear();
182
+ built.forEach((e) => void e.connection.stop());
183
+ // refCounts are kept across rebuilds on purpose.
184
+ };
185
+ return { reconcile, getConnection, waitForConnection, dispose };
186
+ }
@@ -0,0 +1,32 @@
1
+ import type { HubConnection } from "@microsoft/signalr";
2
+ import type { HubConnectionStatus, HubString, SignalRContract } from "./types";
3
+ export interface SignalRProviderPropsBase<TChildren> {
4
+ children: TChildren;
5
+ /** Base URL of the SignalR server. Connections rebuild when this changes. */
6
+ baseUrl: string | undefined;
7
+ /** Returns the bearer token. Read on every (re)negotiate, so token rotation
8
+ * needs no connection rebuild. */
9
+ accessTokenFactory: () => string | Promise<string>;
10
+ /** When false, all connections stop and clear. Default true. */
11
+ enabled?: boolean;
12
+ /** Optional rebuild trigger. Pass the access token (or any value) to force a
13
+ * reconnect when it changes, for example on a re-login. */
14
+ connectionKey?: string | number;
15
+ onStatusChange?: (hub: HubString, status: HubConnectionStatus) => void;
16
+ onError?: (hub: HubString, error: unknown) => void;
17
+ }
18
+ export interface SignalRContextValueBase<T extends SignalRContract, TStore> {
19
+ getConnection: (hub: keyof T & HubString) => HubConnection | null;
20
+ /** Point read of the hub's current status. Use `useHubStatus` for a subscribed read. */
21
+ isHubConnected: (hub: keyof T & HubString) => boolean;
22
+ /** Point read of the hub's current status. Use `useHubStatus` for a subscribed read. */
23
+ getStatus: (hub: keyof T & HubString) => HubConnectionStatus;
24
+ waitForConnection: (hub: keyof T & HubString, timeoutMs: number) => Promise<HubConnection>;
25
+ /** Status store backing `useHubStatus`. */
26
+ statusStore: TStore;
27
+ /** Lazy ref-count: keeps a hub alive while a consumer is mounted. */
28
+ acquire: (hub: keyof T & HubString) => void;
29
+ release: (hub: keyof T & HubString) => void;
30
+ /** Registers a reconnect callback for a hub. Returns an unsubscribe fn. */
31
+ registerReconnect: (hub: keyof T & HubString, cb: () => void) => () => void;
32
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ import type { HubConnection } from "@microsoft/signalr";
2
+ import type { HubConnectionStatus } from "./types";
3
+ /** Live state for one hub connection, owned by the connection manager. */
4
+ export interface HubEntry {
5
+ connection: HubConnection;
6
+ status: HubConnectionStatus;
7
+ /** Resolves once Connected. Replaced on each rebuild. */
8
+ ready: Promise<void>;
9
+ resolveReady: () => void;
10
+ /** Set before stop(), so the start() catch never reconnects a stopped hub. */
11
+ stopping: boolean;
12
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ export { event, method } from "./types";
2
+ export type { HubString, HubContract, SignalRContract, EventDef, MethodDef, HubDef, InferContract, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, HubConnectionStatus, ReconnectConfig, PerHubConfig, SignalRClientConfig, ResolvedHubConfig, InvokeOptions, TeardownOptions, } from "./types";
3
+ export { hubKeys, resolveHubConfig, isRetriableConnectError } from "./config";
4
+ export { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry";
5
+ export type { HubEntry } from "./hub-entry";
6
+ export { createConnectionManager } from "./connection-manager";
7
+ export type { ConnectionManager, ConnectionManagerDeps } from "./connection-manager";
8
+ export type { StatusStore } from "./status-store";
9
+ export type { SignalRProviderPropsBase, SignalRContextValueBase } from "./context";
10
+ export { createInvoker, createSender, createTeardownSender } from "./calls";
11
+ export type { CallTarget } from "./calls";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { event, method } from "./types";
2
+ export { hubKeys, resolveHubConfig, isRetriableConnectError } from "./config";
3
+ export { DEFAULT_BACKOFF, InvokeError, isRetriableInvokeError, resolveBackoff, sleep, } from "./retry";
4
+ export { createConnectionManager } from "./connection-manager";
5
+ export { createInvoker, createSender, createTeardownSender } from "./calls";
@@ -0,0 +1,34 @@
1
+ import type { HubConnection } from "@microsoft/signalr";
2
+ export declare const DEFAULT_BACKOFF: number[];
3
+ /**
4
+ * Thrown by `useSignalRInvoke` when a retried call exhausts its retry budget.
5
+ * Used only when `retries > 0`. With `retries === 0`, the raw server error is
6
+ * rethrown unwrapped, so this error appears only if you opted into retries.
7
+ */
8
+ export declare class InvokeError extends Error {
9
+ /** The last underlying error that caused the final attempt to fail. */
10
+ readonly cause: unknown;
11
+ /** Total number of attempts made, including the first, before giving up. */
12
+ readonly attempts: number;
13
+ /** Whether the final failure was classed as retriable (budget ran out) or not. */
14
+ readonly retriable: boolean;
15
+ constructor(message: string,
16
+ /** The last underlying error that caused the final attempt to fail. */
17
+ cause: unknown,
18
+ /** Total number of attempts made, including the first, before giving up. */
19
+ attempts: number,
20
+ /** Whether the final failure was classed as retriable (budget ran out) or not. */
21
+ retriable: boolean);
22
+ }
23
+ /**
24
+ * Checks whether a failed invoke is worth a retry. This is keyed on
25
+ * CONNECTION STATE, not the error message: a transport drop leaves the
26
+ * connection not-Connected, so it is worth a retry. An error thrown while
27
+ * still Connected is a genuine server or business error (HubException) and
28
+ * must NOT be retried.
29
+ */
30
+ export declare function isRetriableInvokeError(error: unknown, connection: HubConnection): boolean;
31
+ /** Resolves the backoff delay for an attempt, capped and jittered. */
32
+ export declare function resolveBackoff(backoff: number[] | ((attempt: number) => number), attempt: number): number;
33
+ /** setTimeout wrapped as a cancellable promise. */
34
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
package/dist/retry.js ADDED
@@ -0,0 +1,61 @@
1
+ import { AbortError, HttpError, HubConnectionState, TimeoutError, } from "@microsoft/signalr";
2
+ export const DEFAULT_BACKOFF = [250, 1000, 3000, 5000];
3
+ const MAX_BACKOFF = 30000;
4
+ /**
5
+ * Thrown by `useSignalRInvoke` when a retried call exhausts its retry budget.
6
+ * Used only when `retries > 0`. With `retries === 0`, the raw server error is
7
+ * rethrown unwrapped, so this error appears only if you opted into retries.
8
+ */
9
+ export class InvokeError extends Error {
10
+ constructor(message,
11
+ /** The last underlying error that caused the final attempt to fail. */
12
+ cause,
13
+ /** Total number of attempts made, including the first, before giving up. */
14
+ attempts,
15
+ /** Whether the final failure was classed as retriable (budget ran out) or not. */
16
+ retriable) {
17
+ super(message);
18
+ this.cause = cause;
19
+ this.attempts = attempts;
20
+ this.retriable = retriable;
21
+ this.name = "InvokeError";
22
+ }
23
+ }
24
+ /**
25
+ * Checks whether a failed invoke is worth a retry. This is keyed on
26
+ * CONNECTION STATE, not the error message: a transport drop leaves the
27
+ * connection not-Connected, so it is worth a retry. An error thrown while
28
+ * still Connected is a genuine server or business error (HubException) and
29
+ * must NOT be retried.
30
+ */
31
+ export function isRetriableInvokeError(error, connection) {
32
+ if (connection.state !== HubConnectionState.Connected)
33
+ return true;
34
+ if (error instanceof TimeoutError)
35
+ return true;
36
+ if (error instanceof AbortError)
37
+ return true;
38
+ if (error instanceof HttpError) {
39
+ const s = error.statusCode;
40
+ return s === 0 || s === 408 || s === 429 || s >= 500;
41
+ }
42
+ return false; // Connected + plain Error: a server business error, no retry
43
+ }
44
+ /** Resolves the backoff delay for an attempt, capped and jittered. */
45
+ export function resolveBackoff(backoff, attempt) {
46
+ const base = typeof backoff === "function"
47
+ ? backoff(attempt)
48
+ : (backoff[Math.min(attempt, backoff.length - 1)] ?? 0);
49
+ const capped = Math.min(base, MAX_BACKOFF);
50
+ return capped * (0.5 + Math.random() * 0.5);
51
+ }
52
+ /** setTimeout wrapped as a cancellable promise. */
53
+ export function sleep(ms, signal) {
54
+ return new Promise((resolve, reject) => {
55
+ const t = setTimeout(resolve, ms);
56
+ signal?.addEventListener("abort", () => {
57
+ clearTimeout(t);
58
+ reject(new AbortError("aborted"));
59
+ });
60
+ });
61
+ }
@@ -0,0 +1,6 @@
1
+ import type { HubConnectionStatus } from "./types";
2
+ /** Per-hub status store: point reads and writes keyed by hub. */
3
+ export interface StatusStore<H extends string> {
4
+ get: (hub: H) => HubConnectionStatus;
5
+ set: (hub: H, status: HubConnectionStatus) => void;
6
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,143 @@
1
+ import type { HttpTransportType, IRetryPolicy, LogLevel } from "@microsoft/signalr";
2
+ /** A hub path, for example `/hubs/chat`. */
3
+ export type HubString = `/${string}`;
4
+ /**
5
+ * One hub's contract: the `events` the server pushes to you, and the
6
+ * `methods` you invoke on the server. Both are optional.
7
+ */
8
+ export interface HubContract {
9
+ events?: Record<string, (...args: any[]) => void>;
10
+ methods?: Record<string, (...args: any[]) => Promise<any>>;
11
+ }
12
+ /** The full app contract: a map of hub path to {events, methods}. */
13
+ export type SignalRContract = Record<HubString, HubContract>;
14
+ declare const ARGS: unique symbol;
15
+ /** Phantom-typed event declaration, created with {@link event}. */
16
+ export interface EventDef<A extends unknown[] = unknown[]> {
17
+ readonly [ARGS]?: A;
18
+ }
19
+ declare const SIG: unique symbol;
20
+ /** Phantom-typed server-method declaration, created with {@link method}. */
21
+ export interface MethodDef<A extends unknown[] = unknown[], R = unknown> {
22
+ readonly [SIG]?: [A, R];
23
+ }
24
+ /** Runtime per-hub definition: config plus event/method declarations. */
25
+ export interface HubDef extends PerHubConfig {
26
+ events?: Record<string, EventDef<any>>;
27
+ methods?: Record<string, MethodDef<any, any>>;
28
+ }
29
+ type InferEvents<E> = {
30
+ [K in keyof E]: E[K] extends EventDef<infer A> ? (...args: A) => void : never;
31
+ };
32
+ type InferMethods<M> = {
33
+ [K in keyof M]: M[K] extends MethodDef<infer A, infer R> ? (...args: A) => Promise<R> : never;
34
+ };
35
+ /** Derives the app contract ({@link SignalRContract}) from a runtime hub config. */
36
+ export type InferContract<H> = {
37
+ [P in keyof H]: {
38
+ events: InferEvents<H[P] extends {
39
+ events?: infer E;
40
+ } ? NonNullable<E> : {}>;
41
+ methods: InferMethods<H[P] extends {
42
+ methods?: infer M;
43
+ } ? NonNullable<M> : {}>;
44
+ };
45
+ };
46
+ /** Declares a server-pushed event, for example `event<[user: string, message: string]>()`. */
47
+ export declare function event<A extends unknown[] = []>(): EventDef<A>;
48
+ /** Declares an invocable server method, for example `method<[roomId: string], { success: boolean }>()`. */
49
+ export declare function method<A extends unknown[] = [], R = void>(): MethodDef<A, R>;
50
+ type Events<T, H extends keyof T> = NonNullable<T[H] extends {
51
+ events?: infer E;
52
+ } ? E : never>;
53
+ type Methods<T, H extends keyof T> = NonNullable<T[H] extends {
54
+ methods?: infer M;
55
+ } ? M : never>;
56
+ export type EventName<T, H extends keyof T> = keyof Events<T, H> & string;
57
+ export type MethodName<T, H extends keyof T> = keyof Methods<T, H> & string;
58
+ export type EventArgs<T, H extends keyof T, E extends EventName<T, H>> = Events<T, H>[E] extends (...args: infer A) => any ? A : never;
59
+ export type MethodArgs<T, H extends keyof T, M extends MethodName<T, H>> = Methods<T, H>[M] extends (...args: infer A) => any ? A : any[];
60
+ export type MethodReturn<T, H extends keyof T, M extends MethodName<T, H>> = Methods<T, H>[M] extends (...args: any[]) => Promise<infer R> ? R : unknown;
61
+ export type HubConnectionStatus = "disconnected" | "connecting" | "connected" | "reconnecting"
62
+ /** Transient: fires once after a successful reconnect (not on the first connect). */
63
+ | "reconnected";
64
+ /** Reconnect strategy: `true` for the library default, `false` for none, an
65
+ * array of retry delays in ms, or a custom policy. */
66
+ export type ReconnectConfig = boolean | number[] | IRetryPolicy;
67
+ /** Per-hub overrides. Anything omitted falls back to the global config. */
68
+ export interface PerHubConfig {
69
+ /** Connect this hub only when first consumed; disconnect when the last
70
+ * consumer unmounts. Default: the global `lazy` (false). */
71
+ lazy?: boolean;
72
+ /** Grace period in ms before a lazy hub disconnects after its last consumer
73
+ * leaves. Avoids churn on quick remounts. Default 0. */
74
+ graceMs?: number;
75
+ /** Reconnect strategy. Default: the global value, else `true`. */
76
+ reconnect?: ReconnectConfig;
77
+ /** Connect retries before giving up. Default: the global value (2). */
78
+ maxConnectRetries?: number;
79
+ logLevel?: LogLevel;
80
+ transport?: HttpTransportType;
81
+ skipNegotiation?: boolean;
82
+ }
83
+ /** Config passed to `createSignalRClient(config)`. The keys of `hubs` are the
84
+ * hubs; each value's `events`/`methods` (declared with {@link event}/{@link method})
85
+ * are that hub's contract. */
86
+ export interface SignalRClientConfig<H extends Record<HubString, HubDef>> {
87
+ /** One entry per hub. Each value is a {@link HubDef}: per-hub config plus
88
+ * its event/method declarations. */
89
+ hubs: H;
90
+ /** Global default: connect hubs only on demand. Default false — all
91
+ * configured hubs connect upfront. */
92
+ lazy?: boolean;
93
+ /** Global reconnect strategy. Default true. */
94
+ reconnect?: ReconnectConfig;
95
+ /** Global connect-retry budget. Default 2. */
96
+ maxConnectRetries?: number;
97
+ logLevel?: LogLevel;
98
+ }
99
+ /** Per-hub config with all defaults resolved. */
100
+ export interface ResolvedHubConfig {
101
+ lazy: boolean;
102
+ graceMs: number;
103
+ reconnect: ReconnectConfig;
104
+ maxConnectRetries: number;
105
+ logLevel: LogLevel;
106
+ transport?: HttpTransportType;
107
+ skipNegotiation?: boolean;
108
+ events: string[];
109
+ }
110
+ /** Options for an invoke call. */
111
+ export interface InvokeOptions {
112
+ /**
113
+ * Auto-retry count for RETRIABLE failures. Default 0 (fail fast).
114
+ * Warning: invoke is at-least-once. A drop after the server processed the
115
+ * call, but before its completion reaches the client, re-runs the call.
116
+ * Set this above 0 only for IDEMPOTENT methods.
117
+ */
118
+ retries?: number;
119
+ /** Per-attempt wait-for-connection plus invoke deadline in ms. Default 10_000. */
120
+ timeout?: number;
121
+ /** Backoff: fixed delays per attempt, or a fn(attempt) => ms. Capped at 30s
122
+ * and jittered. Default [250, 1000, 3000, 5000]. */
123
+ backoff?: number[] | ((attempt: number) => number);
124
+ /** Forces retriable or not. true = retry, false = throw now, undefined =
125
+ * the default rule. */
126
+ isRetriable?: (error: unknown) => boolean | undefined;
127
+ /**
128
+ * Keeps an in-flight call alive when the calling component unmounts.
129
+ * Default false: in-flight invokes are aborted on unmount, which is
130
+ * correct for query-like reads. Set true for a method invoked in an effect
131
+ * cleanup, so it still reaches the server. The detached call survives
132
+ * unmount, but a still-pending retry loop is NOT cancelled. For the
133
+ * connecting-race and lazy-hub case, use `useSignalRTeardown` instead.
134
+ */
135
+ keepAliveOnUnmount?: boolean;
136
+ }
137
+ /** Options for a `useSignalRTeardown` call. */
138
+ export interface TeardownOptions {
139
+ /** Max time in ms to wait for the hub to (re)connect before giving up the
140
+ * flush. Default 10_000. */
141
+ timeout?: number;
142
+ }
143
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ /** Declares a server-pushed event, for example `event<[user: string, message: string]>()`. */
2
+ export function event() {
3
+ return {};
4
+ }
5
+ /** Declares an invocable server method, for example `method<[roomId: string], { success: boolean }>()`. */
6
+ export function method() {
7
+ return {};
8
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@dammers/use-signalr-core",
3
+ "version": "0.1.0",
4
+ "description": "Framework-free typed multi-hub SignalR core: connection lifecycle, contracts, retry.",
5
+ "author": "Dammers",
6
+ "license": "MIT",
7
+ "repository": "github:DammersCode/use-signalr",
8
+ "homepage": "https://github.com/DammersCode/use-signalr#readme",
9
+ "bugs": "https://github.com/DammersCode/use-signalr/issues",
10
+ "type": "module",
11
+ "sideEffects": false,
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.build.json",
28
+ "typecheck": "tsc --noEmit",
29
+ "test": "vitest run"
30
+ },
31
+ "peerDependencies": {
32
+ "@microsoft/signalr": ">=8"
33
+ },
34
+ "devDependencies": {
35
+ "@microsoft/signalr": ">=8"
36
+ }
37
+ }