@dammers/use-signalr-core 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.
@@ -1,21 +1,55 @@
1
1
  import { HubConnectionBuilder, HubConnectionState } from "@microsoft/signalr";
2
- import { isRetriableConnectError } from "./config";
3
- const CONNECT_RETRY_BASE_MS = 2500;
2
+ import { assertProtocolFitsTransport, isRetriableConnectError, joinHubUrl } from "./config.js";
3
+ const RECOVER_DELAY_STEP_MS = 2500;
4
+ const RECOVER_DELAY_MAX_MS = 30000;
4
5
  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
- */
6
+ /** SignalR passes no error on a clean close, and after it gave up its auto-reconnect. */
7
+ function cleanCloseError(afterReconnectAttempts) {
8
+ return new Error(afterReconnectAttempts
9
+ ? "Reconnect retries exhausted"
10
+ : "The server or a proxy closed the connection.");
11
+ }
12
+ function isThenable(value) {
13
+ return typeof value?.then === "function";
14
+ }
15
+ /** Runs a user callback. A throw or a rejection goes to onError. A failure of onError is dropped. */
16
+ export function runUserCallback(hub, callback, onError) {
17
+ const report = (err) => {
18
+ try {
19
+ const result = onError(hub, err);
20
+ if (isThenable(result))
21
+ result.then(undefined, noop);
22
+ }
23
+ catch {
24
+ // Nothing is left to report to.
25
+ }
26
+ };
27
+ try {
28
+ const result = callback();
29
+ if (isThenable(result))
30
+ result.then(undefined, report);
31
+ }
32
+ catch (err) {
33
+ report(err);
34
+ }
35
+ }
36
+ /** Owns the hub connections of one provider generation: build, start with recovery, lazy ref-counted stop. */
10
37
  export function createConnectionManager(deps) {
11
- const { baseUrl, hubs, resolve, getAccessToken, refCounts, stopTimers, reconnectListeners, onStatus, onError, isCurrent, } = deps;
38
+ const { baseUrl, hubs, resolve, getAccessToken, refCounts, stopTimers, reconnectListeners, connectedBefore, dispatch, onStatus, isCurrent, } = deps;
39
+ const report = (hub, error, source) => runUserCallback(hub, () => deps.onError(hub, error, { source }), noop);
40
+ const onError = (hub, error) => report(hub, error, "connection");
41
+ const onCallbackError = (hub, error) => report(hub, error, "callback");
12
42
  const built = new Map();
43
+ const recoverTimers = new Map();
44
+ const attempts = new Map();
45
+ const misconfigured = new Set();
13
46
  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);
47
+ const setStatus = (hub, status, error) => {
48
+ runUserCallback(hub, () => onStatus(hub, status, error), onCallbackError);
49
+ };
50
+ // Fire-and-forget keeps the API synchronous. A rejection still reaches onError.
51
+ const stopConnection = (hub, connection) => {
52
+ void connection.stop().catch((err) => onError(hub, err));
19
53
  };
20
54
  const clearStopTimer = (hub) => {
21
55
  const id = stopTimers.get(hub);
@@ -24,6 +58,14 @@ export function createConnectionManager(deps) {
24
58
  stopTimers.delete(hub);
25
59
  }
26
60
  };
61
+ const clearRecoverTimer = (hub) => {
62
+ const id = recoverTimers.get(hub);
63
+ if (id !== undefined) {
64
+ clearTimeout(id);
65
+ recoverTimers.delete(hub);
66
+ }
67
+ attempts.delete(hub);
68
+ };
27
69
  const applyReconnect = (builder, reconnect) => {
28
70
  if (reconnect === true)
29
71
  builder.withAutomaticReconnect();
@@ -32,80 +74,132 @@ export function createConnectionManager(deps) {
32
74
  else if (reconnect !== false)
33
75
  builder.withAutomaticReconnect(reconnect);
34
76
  };
77
+ const buildConnection = (hub, rc) => {
78
+ const protocol = typeof rc.hubProtocol === "function" ? rc.hubProtocol() : rc.hubProtocol;
79
+ if (protocol)
80
+ assertProtocolFitsTransport(hub, protocol, rc.httpOptions);
81
+ let builder = new HubConnectionBuilder().withUrl(joinHubUrl(baseUrl, hub), {
82
+ ...rc.httpOptions,
83
+ accessTokenFactory: () => Promise.resolve(getAccessToken()),
84
+ });
85
+ if (protocol)
86
+ builder = builder.withHubProtocol(protocol);
87
+ builder = builder.configureLogging(rc.logLevel);
88
+ applyReconnect(builder, rc.reconnect);
89
+ for (const configure of rc.configureBuilders)
90
+ builder = configure(builder, { hub, baseUrl });
91
+ return builder.build();
92
+ };
93
+ const runReconnectListeners = (hub) => {
94
+ [...(reconnectListeners.get(hub) ?? [])].forEach((cb) => runUserCallback(hub, cb, onCallbackError));
95
+ };
35
96
  const buildAndStart = (hub) => {
36
- if (disposing || built.has(hub))
97
+ if (disposing || built.has(hub) || misconfigured.has(hub))
37
98
  return;
38
99
  clearStopTimer(hub);
39
100
  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
- };
101
+ let conn;
102
+ try {
103
+ conn = buildConnection(hub, rc);
104
+ }
105
+ catch (err) {
106
+ // A build error comes from the app config, so a retry cannot fix it.
107
+ attempts.delete(hub);
108
+ misconfigured.add(hub);
109
+ setStatus(hub, "disconnected", err);
110
+ onError(hub, err);
111
+ return;
112
+ }
113
+ const entry = { connection: conn, stopping: false, reconnecting: false };
63
114
  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");
115
+ // Bind before start() so early pushes arrive.
116
+ for (const ev of rc.events) {
117
+ conn.on(ev, (...args) => {
118
+ if (!isCurrent() || built.get(hub) !== entry)
119
+ return;
120
+ dispatch(hub, ev, args);
121
+ });
122
+ }
123
+ const fail = (err, republishStatus) => {
124
+ if (built.get(hub) !== entry)
125
+ return;
126
+ if (!isRetriableConnectError(err)) {
127
+ attempts.delete(hub);
128
+ setStatus(hub, "disconnected", err);
129
+ onError(hub, err);
69
130
  return;
70
131
  }
71
- setStatus(hub, "disconnected");
72
- onError(hub, err);
132
+ built.delete(hub);
133
+ if (!desired().has(hub)) {
134
+ attempts.delete(hub);
135
+ connectedBefore.delete(hub);
136
+ setStatus(hub, "idle");
137
+ return;
138
+ }
139
+ const attempt = (attempts.get(hub) ?? 0) + 1;
140
+ attempts.set(hub, attempt);
141
+ if (attempt === 1)
142
+ onError(hub, err);
143
+ if (republishStatus)
144
+ setStatus(hub, "connecting");
145
+ const delay = Math.min(RECOVER_DELAY_STEP_MS * attempt, RECOVER_DELAY_MAX_MS);
146
+ const id = setTimeout(() => {
147
+ recoverTimers.delete(hub);
148
+ if (!isCurrent() || !desired().has(hub))
149
+ return;
150
+ buildAndStart(hub);
151
+ }, delay);
152
+ recoverTimers.set(hub, id);
153
+ };
154
+ // SignalR has no removal API, so attach lifecycle handlers once.
155
+ conn.onclose((err) => {
156
+ // A stale generation's late callback must never overwrite the live one's status.
157
+ if (!isCurrent() || built.get(hub) !== entry)
158
+ return;
159
+ if (disposing)
160
+ return;
161
+ fail(err ?? cleanCloseError(entry.reconnecting), true);
162
+ });
163
+ conn.onreconnecting(() => {
164
+ if (!isCurrent() || built.get(hub) !== entry)
165
+ return;
166
+ entry.reconnecting = true;
167
+ setStatus(hub, "reconnecting");
73
168
  });
74
- conn.onreconnecting(() => setStatus(hub, "reconnecting"));
75
169
  conn.onreconnected(() => {
76
- entry.resolveReady();
77
- if (!disposing && isCurrent()) {
78
- onStatus(hub, "reconnected");
79
- reconnectListeners.get(hub)?.forEach((cb) => cb());
80
- }
170
+ if (!isCurrent() || built.get(hub) !== entry)
171
+ return;
172
+ entry.reconnecting = false;
81
173
  setStatus(hub, "connected");
174
+ if (disposing)
175
+ return;
176
+ runReconnectListeners(hub);
82
177
  });
83
- let retries = 0;
84
178
  const start = async () => {
85
- if (disposing || entry.stopping)
86
- return;
87
179
  if (conn.state !== HubConnectionState.Disconnected)
88
180
  return;
181
+ if (disposing || entry.stopping)
182
+ return;
89
183
  try {
90
184
  await conn.start();
91
- if (disposing || entry.stopping)
92
- return;
93
- entry.resolveReady();
94
- setStatus(hub, "connected");
95
185
  }
96
186
  catch (err) {
97
- if (disposing || entry.stopping)
98
- return;
99
- if (!isRetriableConnectError(err) || retries >= rc.maxConnectRetries) {
100
- setStatus(hub, "disconnected");
101
- onError(hub, err);
187
+ if (disposing || entry.stopping || !isCurrent())
102
188
  return;
103
- }
104
- retries += 1;
105
- setStatus(hub, "disconnected");
106
- setTimeout(start, CONNECT_RETRY_BASE_MS * retries);
189
+ fail(err, false);
190
+ return;
107
191
  }
192
+ if (disposing || entry.stopping)
193
+ return;
194
+ attempts.delete(hub);
195
+ const recovered = connectedBefore.has(hub);
196
+ connectedBefore.add(hub);
197
+ setStatus(hub, "connected");
198
+ if (recovered && !disposing)
199
+ runReconnectListeners(hub);
108
200
  };
201
+ if (!attempts.has(hub))
202
+ setStatus(hub, "connecting");
109
203
  void start();
110
204
  };
111
205
  const scheduleStop = (hub) => {
@@ -115,6 +209,8 @@ export function createConnectionManager(deps) {
115
209
  const { graceMs } = resolve(hub);
116
210
  clearStopTimer(hub);
117
211
  const stopNow = () => {
212
+ if (disposing)
213
+ return;
118
214
  stopTimers.delete(hub);
119
215
  if ((refCounts.get(hub) ?? 0) > 0)
120
216
  return; // re-acquired during the grace period
@@ -123,8 +219,10 @@ export function createConnectionManager(deps) {
123
219
  return;
124
220
  e.stopping = true;
125
221
  built.delete(hub);
126
- setStatus(hub, "disconnected");
127
- void e.connection.stop();
222
+ attempts.delete(hub);
223
+ connectedBefore.delete(hub);
224
+ setStatus(hub, "idle");
225
+ stopConnection(hub, e.connection);
128
226
  };
129
227
  if (graceMs <= 0)
130
228
  queueMicrotask(stopNow);
@@ -146,41 +244,39 @@ export function createConnectionManager(deps) {
146
244
  if (disposing)
147
245
  return;
148
246
  const want = desired();
149
- for (const hub of want)
150
- if (!built.has(hub))
247
+ for (const hub of want) {
248
+ if (!built.has(hub) && !recoverTimers.has(hub))
151
249
  buildAndStart(hub);
250
+ }
152
251
  for (const hub of built.keys())
153
252
  if (!want.has(hub))
154
253
  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;
254
+ for (const hub of [...misconfigured]) {
255
+ if (want.has(hub))
256
+ continue;
257
+ misconfigured.delete(hub);
258
+ connectedBefore.delete(hub);
259
+ setStatus(hub, "idle");
161
260
  }
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;
261
+ for (const hub of [...recoverTimers.keys()]) {
262
+ if (want.has(hub))
263
+ continue;
264
+ clearRecoverTimer(hub);
265
+ connectedBefore.delete(hub);
266
+ setStatus(hub, "idle");
175
267
  }
176
- throw new Error(`Timeout waiting for SignalR connection to ${hub} (${timeoutMs}ms)`);
177
268
  };
269
+ const getConnection = (hub) => built.get(hub)?.connection ?? null;
178
270
  const dispose = () => {
179
271
  disposing = true;
180
272
  stopTimers.forEach((id) => clearTimeout(id));
181
273
  stopTimers.clear();
182
- built.forEach((e) => void e.connection.stop());
274
+ recoverTimers.forEach((id) => clearTimeout(id));
275
+ recoverTimers.clear();
276
+ attempts.clear();
277
+ misconfigured.clear();
278
+ built.forEach((e, hub) => stopConnection(hub, e.connection));
183
279
  // refCounts are kept across rebuilds on purpose.
184
280
  };
185
- return { reconcile, getConnection, waitForConnection, dispose };
281
+ return { reconcile, getConnection, dispose };
186
282
  }
package/dist/context.d.ts CHANGED
@@ -1,32 +1,48 @@
1
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. */
2
+ import type { HubConnectionStatus, HubString, SignalRContract, SignalRErrorInfo } from "./types.js";
3
+ export interface SignalRProviderPropsBase<THub extends string = HubString> {
4
+ /** Base URL of the SignalR server. The library adds the hub paths from the contract and removes a trailing slash. A new value rebuilds all connections. `undefined` or `""` disables the session. Use `"/"` for the same origin. */
6
5
  baseUrl: string | undefined;
7
- /** Returns the bearer token. Read on every (re)negotiate, so token rotation
8
- * needs no connection rebuild. */
6
+ /** Returns the bearer token. The library calls it on each negotiate and on each auto-reconnect attempt. A token change needs no rebuild. */
9
7
  accessTokenFactory: () => string | Promise<string>;
10
- /** When false, all connections stop and clear. Default true. */
8
+ /**
9
+ * When `false`, all hubs stop and the status is `idle`. An invoke that waits for the connection rejects at once with an error named `SignalRDisabledError`.
10
+ * @default true
11
+ */
11
12
  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. */
13
+ /** A new value rebuilds all connections. Use it to recover from `disconnected`. Pass a user ID or a login counter, not the token. */
14
14
  connectionKey?: string | number;
15
- onStatusChange?: (hub: HubString, status: HubConnectionStatus) => void;
16
- onError?: (hub: HubString, error: unknown) => void;
15
+ /** Runs when the status of a hub changes. */
16
+ onStatusChange?: (hub: THub, status: HubConnectionStatus) => void;
17
+ /** Runs on a connection error and on an error that your callback throws. `info.source` is `"connection"` or `"callback"`. */
18
+ onError?: (hub: THub, error: unknown, info: SignalRErrorInfo) => void;
17
19
  }
18
- export interface SignalRContextValueBase<T extends SignalRContract, TStore> {
20
+ /** The small context the public accessor of each adapter returns. */
21
+ export interface SignalRPublicContext<T extends SignalRContract> {
22
+ /** The live `HubConnection` of the hub, or `null` when none exists. */
19
23
  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. */
24
+ /** Point read of the hub's current status. In a reactive scope of a signal-based framework (Solid, Vue, Angular), the read tracks. */
23
25
  getStatus: (hub: keyof T & HubString) => HubConnectionStatus;
24
- waitForConnection: (hub: keyof T & HubString, timeoutMs: number) => Promise<HubConnection>;
25
- /** Status store backing `useHubStatus`. */
26
+ /**
27
+ * Resolves once the hub is connected. Waits across stop, start, and rebuilds.
28
+ * Rejects after `timeoutMs`, or with `signal.reason` (an `AbortError` for a plain `abort()`) when `signal` aborts.
29
+ * Rejects at once when the last update disabled the session, or when the hub stopped after a non-retriable error.
30
+ * On the server no connection starts. The wait rejects at once if the adapter disables the session there, and ends with the timeout otherwise.
31
+ */
32
+ waitForConnection: (hub: keyof T & HubString, timeoutMs: number, signal?: AbortSignal) => Promise<HubConnection>;
33
+ }
34
+ /** The full context that adapters use inside their own hooks. Not public API. */
35
+ export interface SignalRContextValueBase<T extends SignalRContract, TStore> extends SignalRPublicContext<T> {
36
+ /** The frozen object that the public accessor returns. */
37
+ publicContext: SignalRPublicContext<T>;
38
+ /** The store that you passed to the session. */
26
39
  statusStore: TStore;
27
- /** Lazy ref-count: keeps a hub alive while a consumer is mounted. */
40
+ /** Raises the lazy reference count of a hub. A lazy hub stays connected while the count is above 0. */
28
41
  acquire: (hub: keyof T & HubString) => void;
42
+ /** Lowers the lazy reference count of a hub. */
29
43
  release: (hub: keyof T & HubString) => void;
30
- /** Registers a reconnect callback for a hub. Returns an unsubscribe fn. */
44
+ /** Registers a callback that runs after each reconnect, not after the first connect. Returns an unsubscribe function. */
31
45
  registerReconnect: (hub: keyof T & HubString, cb: () => void) => () => void;
46
+ /** Registers an event handler. The handler survives rebuilds. Returns an unsubscribe function. */
47
+ subscribe: (hub: keyof T & HubString, event: string, handler: (...args: unknown[]) => void) => () => void;
32
48
  }
@@ -0,0 +1,9 @@
1
+ /** The `name` values of the errors that `waitForConnection` rejects with. */
2
+ export declare const SIGNALR_ERROR_NAMES: {
3
+ readonly disabled: "SignalRDisabledError";
4
+ readonly disconnected: "SignalRDisconnectedError";
5
+ readonly timeout: "SignalRTimeoutError";
6
+ };
7
+ export declare function namedError(name: (typeof SIGNALR_ERROR_NAMES)[keyof typeof SIGNALR_ERROR_NAMES], message: string): Error;
8
+ /** A wait on a disabled or failed hub cannot succeed by waiting longer. */
9
+ export declare function isFinalWaitError(error: unknown): boolean;
package/dist/errors.js ADDED
@@ -0,0 +1,16 @@
1
+ /** The `name` values of the errors that `waitForConnection` rejects with. */
2
+ export const SIGNALR_ERROR_NAMES = {
3
+ disabled: "SignalRDisabledError",
4
+ disconnected: "SignalRDisconnectedError",
5
+ timeout: "SignalRTimeoutError",
6
+ };
7
+ export function namedError(name, message) {
8
+ const error = new Error(message);
9
+ error.name = name;
10
+ return error;
11
+ }
12
+ /** A wait on a disabled or failed hub cannot succeed by waiting longer. */
13
+ export function isFinalWaitError(error) {
14
+ return (error instanceof Error &&
15
+ (error.name === SIGNALR_ERROR_NAMES.disabled || error.name === SIGNALR_ERROR_NAMES.disconnected));
16
+ }
@@ -1,12 +1,9 @@
1
1
  import type { HubConnection } from "@microsoft/signalr";
2
- import type { HubConnectionStatus } from "./types";
3
2
  /** Live state for one hub connection, owned by the connection manager. */
4
3
  export interface HubEntry {
5
4
  connection: HubConnection;
6
- status: HubConnectionStatus;
7
- /** Resolves once Connected. Replaced on each rebuild. */
8
- ready: Promise<void>;
9
- resolveReady: () => void;
10
5
  /** Set before stop(), so the start() catch never reconnects a stopped hub. */
11
6
  stopping: boolean;
7
+ /** True from onreconnecting to onreconnected. A close in between means SignalR gave up. */
8
+ reconnecting: boolean;
12
9
  }
package/dist/index.d.ts CHANGED
@@ -1,11 +1,9 @@
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";
1
+ export { event, method } from "./types.js";
2
+ export type { HubString, HubContract, SignalRContract, EventDef, MethodDef, HubDef, InferContract, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, HubConnectionStatus, SignalRErrorInfo, ReconnectConfig, HubProtocolConfig, HttpOptions, ConfigureBuilder, BuilderContext, PerHubConfig, SignalRClientConfig, ResolvedHubConfig, InvokeOptions, TeardownOptions, } from "./types.js";
3
+ export { hubKeys, resolveHubConfig } from "./config.js";
4
+ export type { StatusStore } from "./status-store.js";
5
+ export type { SignalRProviderPropsBase, SignalRContextValueBase, SignalRPublicContext, } from "./context.js";
6
+ export { createAbortScope, createInvoker, createSender, createTeardownSender, } from "./calls.js";
7
+ export type { AbortScope, CallTarget, InvokerOptions } from "./calls.js";
8
+ export { createSignalRSession } from "./session.js";
9
+ export type { SignalRSession, SignalRSessionDeps, SignalRSessionValues } from "./session.js";
package/dist/index.js CHANGED
@@ -1,5 +1,4 @@
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";
1
+ export { event, method } from "./types.js";
2
+ export { hubKeys, resolveHubConfig } from "./config.js";
3
+ export { createAbortScope, createInvoker, createSender, createTeardownSender, } from "./calls.js";
4
+ export { createSignalRSession } from "./session.js";
package/dist/retry.d.ts CHANGED
@@ -1,34 +1,8 @@
1
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
- */
2
+ export declare const DEFAULT_BACKOFF: readonly number[];
3
+ /** Keyed on connection state: a drop retries, a server error thrown while connected does not. */
30
4
  export declare function isRetriableInvokeError(error: unknown, connection: HubConnection): boolean;
31
5
  /** Resolves the backoff delay for an attempt, capped and jittered. */
32
- export declare function resolveBackoff(backoff: number[] | ((attempt: number) => number), attempt: number): number;
6
+ export declare function resolveBackoff(backoff: readonly number[] | ((attempt: number) => number), attempt: number): number;
33
7
  /** setTimeout wrapped as a cancellable promise. */
34
8
  export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
package/dist/retry.js CHANGED
@@ -1,33 +1,7 @@
1
1
  import { AbortError, HttpError, HubConnectionState, TimeoutError, } from "@microsoft/signalr";
2
- export const DEFAULT_BACKOFF = [250, 1000, 3000, 5000];
2
+ export const DEFAULT_BACKOFF = Object.freeze([250, 1000, 3000, 5000]);
3
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
- */
4
+ /** Keyed on connection state: a drop retries, a server error thrown while connected does not. */
31
5
  export function isRetriableInvokeError(error, connection) {
32
6
  if (connection.state !== HubConnectionState.Connected)
33
7
  return true;
@@ -39,7 +13,7 @@ export function isRetriableInvokeError(error, connection) {
39
13
  const s = error.statusCode;
40
14
  return s === 0 || s === 408 || s === 429 || s >= 500;
41
15
  }
42
- return false; // Connected + plain Error: a server business error, no retry
16
+ return false;
43
17
  }
44
18
  /** Resolves the backoff delay for an attempt, capped and jittered. */
45
19
  export function resolveBackoff(backoff, attempt) {
@@ -51,11 +25,18 @@ export function resolveBackoff(backoff, attempt) {
51
25
  }
52
26
  /** setTimeout wrapped as a cancellable promise. */
53
27
  export function sleep(ms, signal) {
28
+ // An already-aborted signal never fires "abort", so check before listening.
29
+ if (signal?.aborted)
30
+ return Promise.reject(signal.reason);
54
31
  return new Promise((resolve, reject) => {
55
- const t = setTimeout(resolve, ms);
56
- signal?.addEventListener("abort", () => {
32
+ const onAbort = () => {
57
33
  clearTimeout(t);
58
- reject(new AbortError("aborted"));
59
- });
34
+ reject(signal?.reason);
35
+ };
36
+ const t = setTimeout(() => {
37
+ signal?.removeEventListener("abort", onAbort);
38
+ resolve();
39
+ }, ms);
40
+ signal?.addEventListener("abort", onAbort);
60
41
  });
61
42
  }