@dammers/use-signalr-svelte 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/LICENSE CHANGED
@@ -1,21 +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.
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 CHANGED
@@ -1,207 +1,57 @@
1
- # @dammers/use-signalr-svelte
2
-
3
- A typed, reusable [SignalR](https://learn.microsoft.com/aspnet/core/signalr) provider and store set for Svelte, driven by your contract.
4
-
5
- [![npm](https://img.shields.io/npm/v/@dammers/use-signalr-svelte.svg)](https://www.npmjs.com/package/@dammers/use-signalr-svelte)
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
- ```ts
10
- const { provideSignalR, hubInvoke } = 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 function and a set of stores/functions, 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 Svelte-specific install and usage.
22
-
23
- ## Install
24
-
25
- ```bash
26
- npm i @dammers/use-signalr-svelte @microsoft/signalr
27
- ```
28
-
29
- Requires `svelte` ≥ 4 and `@microsoft/signalr` ≥ 8 (tested against 8–10).
30
-
31
- ## Usage
32
-
33
- ### 1. Define your contract and create the client
34
-
35
- The **keys of `config.hubs` declare the hubs**. Each hub's `events` (what the server pushes to you) and `methods` (what you invoke) are declared inline with the `event()` and `method()` markers. This is the same contract shape as the React and Solid packages — only the provider and the functions below differ.
36
-
37
- ```ts
38
- // signalr.ts
39
- import { createSignalRClient, event, method } from "@dammers/use-signalr-svelte";
40
-
41
- export const {
42
- provideSignalR,
43
- getSignalR,
44
- onHubEvent,
45
- hubInvoke,
46
- hubSend,
47
- hubTeardown,
48
- hubStatus,
49
- onReconnected,
50
- keepHubAlive,
51
- } = createSignalRClient({
52
- hubs: {
53
- "/hubs/chat": {
54
- events: {
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)
62
- },
63
- },
64
- // global defaults (all optional):
65
- // lazy: false, reconnect: true, maxConnectRetries: 2, logLevel: LogLevel.Information
66
- });
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. Provide the connection in your root layout
72
-
73
- `provideSignalR` is a **function**, not a component — call it once in your root component's `<script>`, before any other function from this client. In SvelteKit, that means `+layout.svelte`.
74
-
75
- ```svelte
76
- <!-- +layout.svelte -->
77
- <script lang="ts">
78
- import { provideSignalR } from "$lib/signalr";
79
- import { accessToken, isAuthenticated } from "$lib/auth";
80
-
81
- let { children } = $props();
82
-
83
- provideSignalR({
84
- baseUrl: "https://api.example.com",
85
- accessTokenFactory: () => accessToken(),
86
- enabled: isAuthenticated, // optional, default true; can be a store or a plain value
87
- onError: (hub, err) => console.error(`Connection to ${hub} failed`, err),
88
- onStatusChange: (hub, status) => {
89
- if (status === "reconnecting") console.warn(`Reconnecting to ${hub}…`);
90
- },
91
- });
92
- </script>
93
-
94
- {@render children()}
95
- ```
96
-
97
- All connection work happens client-side only — `provideSignalR` is safe to call during SSR, since it defers building any connection until the component mounts in the browser.
98
-
99
- ### 3. Use the exported stores/functions — everything below is fully typed
100
-
101
- These work the same way as the React and Solid packages' hooks, with one difference: **`hubStatus` returns a Svelte store**, not a plain value. Read it with the `$` prefix in a component.
102
-
103
- ```svelte
104
- <script lang="ts">
105
- import { onDestroy } from "svelte";
106
- import {
107
- onHubEvent,
108
- hubInvoke,
109
- hubSend,
110
- hubTeardown,
111
- hubStatus,
112
- onReconnected,
113
- keepHubAlive,
114
- getSignalR,
115
- } from "$lib/signalr";
116
-
117
- // Listen to a server event — args inferred from the contract
118
- onHubEvent("/hubs/chat", "ReceiveMessage", (user, message) => {
119
- console.log(user, message);
120
- });
121
-
122
- // Invoke a server method — args + return inferred, waits for connection
123
- const sendMessage = hubInvoke("/hubs/chat", "SendMessage");
124
- await sendMessage(roomId, "hello"); // typed params, Promise<void>
125
-
126
- // Typed fire-and-forget — does not wait for connection; drops if not connected.
127
- // Safe to capture in onDestroy.
128
- const send = hubSend("/hubs/chat", "SendMessage");
129
- await send(roomId, "bye"); // typed args; Promise<boolean> (true = dispatched)
130
-
131
- // Reliable teardown — for a method called in onDestroy. Survives disposal,
132
- // queues while the hub connects (instead of dropping), and holds a lazy hub
133
- // open until it flushes. Best-effort: Promise<boolean> (true = dispatched).
134
- const joinRoom = hubInvoke("/hubs/chat", "JoinRoomAsync");
135
- const leaveRoom = hubTeardown("/hubs/chat", "LeaveRoomAsync");
136
- joinRoom(roomId);
137
- onDestroy(() => {
138
- leaveRoom(roomId);
139
- }); // lands even mid-connect or after disposal
140
-
141
- // Live connection status, as a Svelte store
142
- const status = hubStatus("/hubs/chat");
143
-
144
- // Re-sync after a reconnect, for example to refetch a query
145
- onReconnected("/hubs/chat", () => refetchMessages());
146
-
147
- // Keep a lazy hub connected for this component's lifetime without subscribing
148
- keepHubAlive("/hubs/chat");
149
-
150
- // Last resort: the raw HubConnection (prefer the typed stores/functions above)
151
- const { getConnection } = getSignalR();
152
- getConnection("/hubs/chat")?.send("SendMessage", roomId, "bye");
153
- </script>
154
-
155
- <p>Status: {$status}</p>
156
- ```
157
-
158
- ### Reliable join/leave (session pattern)
159
-
160
- A common pattern joins a session on init and leaves it in `onDestroy`.
161
-
162
- ```svelte
163
- <script lang="ts">
164
- import { onDestroy } from "svelte";
165
-
166
- const joinRoom = hubInvoke("/hubs/chat", "JoinRoomAsync");
167
- const leaveRoom = hubTeardown("/hubs/chat", "LeaveRoomAsync");
168
-
169
- joinRoom(roomId);
170
- onDestroy(() => {
171
- leaveRoom(roomId);
172
- });
173
- </script>
174
- ```
175
-
176
- A plain `hubInvoke` or `hubSend` makes the **leave** unreliable:
177
-
178
- - `hubInvoke` aborts in-flight calls on destroy, so a leave issued in `onDestroy` can be cancelled before it reaches the server.
179
- - `hubSend` drops silently if the hub is not `Connected`, so a leave that races a still-connecting socket (a fast route change, a rapid mount/unmount) is lost.
180
-
181
- `hubTeardown` fixes both problems. It:
182
-
183
- - **survives the calling component's disposal** — it runs detached and is never aborted,
184
- - **queues while connecting** — it waits up to `timeout` (default 10s) for the hub, then sends, instead of dropping,
185
- - **holds a lazy hub open** until the flush completes, even if the disposing component was its last consumer.
186
-
187
- It is best-effort and fire-and-forget: it resolves `true` once dispatched, `false` if the hub never connected in time, and never throws.
188
-
189
- > If your leave already uses `hubInvoke` and only needs to avoid the abort on destroy, pass `{ keepAliveOnUnmount: true }`. This covers the abort case but **not** the still-connecting race. For that race, use `hubTeardown`.
190
-
191
- ## Svelte-specific behavior
192
-
193
- - **`provideSignalR` is a function, not a component.** Call it directly in a `<script>` block during component initialization — most commonly your root layout — instead of wrapping markup in a provider component.
194
- - **`hubStatus` returns a `Readable<HubConnectionStatus>`.** Read the current value with `$status` in markup, or call `.subscribe(...)` directly for more control. This works the same in Svelte 4 and Svelte 5.
195
- - **`baseUrl`, `enabled`, and `connectionKey` accept a `MaybeReadable<T>`** — either a plain value or a Svelte store (`Readable<T>`). Passing a store makes the provider react to it: the connection rebuilds whenever the store's value changes, exactly as if you had passed a new plain value.
196
- - **Hub, event, method names and the options object are read once, during component init.** They are not reactive. If you need a different hub or method for different state, call the function again for each variant rather than expecting it to react to a changed argument.
197
- - **Handlers are live closures.** `onHubEvent`'s handler and `onReconnected`'s callback are captured once, but a normal JS closure sees current values from your component's scope. Memoization is never needed.
198
- - **Join/leave uses component init + `onDestroy`**, imported directly from `"svelte"`. `onDestroy` runs once when the component is destroyed.
199
- - **All connection work is client-side only.** `provideSignalR` defers connecting until the component mounts in the browser (`onMount`, which never runs during SSR), so it is safe to call from a SvelteKit `+layout.svelte` without any SSR guard.
200
-
201
- ## More
202
-
203
- Per-hub config, invoke retry semantics, the send/invoke/teardown comparison, and notes on token rotation live in the [root README](https://github.com/DammersCode/use-signalr#readme). Contributing setup lives in [CONTRIBUTING.md](https://github.com/DammersCode/use-signalr/blob/main/CONTRIBUTING.md).
204
-
205
- ## License
206
-
207
- MIT © [DammersCode](https://github.com/DammersCode)
1
+ # @dammers/use-signalr-svelte
2
+
3
+ Context and stores for typed [SignalR](https://learn.microsoft.com/aspnet/core/signalr) in Svelte. Part of [use-signalr](https://use-signalr.vercel.app).
4
+
5
+ [![npm](https://img.shields.io/npm/v/@dammers/use-signalr-svelte.svg)](https://www.npmjs.com/package/@dammers/use-signalr-svelte)
6
+ [![license](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/DammersCode/use-signalr/blob/main/LICENSE)
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ npm install @dammers/use-signalr-svelte @microsoft/signalr
12
+ ```
13
+
14
+ It needs Svelte ^5.15, `@microsoft/signalr` ^8 || ^9 || ^10, and Node 20.19 or later.
15
+
16
+ ## Example
17
+
18
+ This file declares a hub, connects it, and reads a typed method result:
19
+
20
+ <!-- hero:svelte:start -->
21
+ ```svelte
22
+ <script module lang="ts">
23
+ import { createSignalRClient, method } from "@dammers/use-signalr-svelte";
24
+
25
+ export const { provideSignalR, hubInvoke } = createSignalRClient({
26
+ hubs: {
27
+ "/hubs/rooms": {
28
+ methods: { GetHistory: method<[roomId: string], { text: string }[]>() },
29
+ },
30
+ },
31
+ });
32
+ </script>
33
+
34
+ <script lang="ts">
35
+ provideSignalR({ baseUrl: "https://api.example.com", accessTokenFactory: () => "token" });
36
+
37
+ const getHistory = hubInvoke("/hubs/rooms", "GetHistory");
38
+ let count = $state(0);
39
+ const load = () => getHistory("general").then((m) => (count = m.length)).catch(console.error);
40
+ </script>
41
+
42
+ <button onclick={load}>{count} messages</button>
43
+ ```
44
+ <!-- hero:svelte:end -->
45
+
46
+ ## Documentation
47
+
48
+ - [Quick start](https://use-signalr.vercel.app/docs/svelte/quick-start)
49
+ - [Provider setup](https://use-signalr.vercel.app/docs/svelte/concepts/provider)
50
+ - [Events](https://use-signalr.vercel.app/docs/svelte/concepts/events) and [calls](https://use-signalr.vercel.app/docs/svelte/concepts/calls)
51
+ - [Connection status](https://use-signalr.vercel.app/docs/svelte/concepts/connection-status) and [recovery](https://use-signalr.vercel.app/docs/svelte/concepts/recovery)
52
+ - [API reference](https://use-signalr.vercel.app/docs/svelte/reference/api)
53
+ - [Troubleshooting](https://use-signalr.vercel.app/docs/svelte/reference/troubleshooting)
54
+
55
+ ## License
56
+
57
+ [MIT](https://github.com/DammersCode/use-signalr/blob/main/LICENSE) © [DammersCode](https://github.com/DammersCode)
@@ -7,60 +7,69 @@ import type { HubDef, HubString, InferContract, SignalRClientConfig } from "@dam
7
7
  */
8
8
  export declare function createSignalRClient<const H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): {
9
9
  /**
10
- * Builds, starts, retries, and auto-reconnects every configured hub. Call
11
- * once in your root component's script, before any other function — for
12
- * example `+layout.svelte` in SvelteKit. Pass `baseUrl` and
13
- * `accessTokenFactory`, and gate them with `enabled`. All connection work
14
- * happens client-side only, so this is safe to call during SSR.
10
+ * Builds the session and sets the context. Call it once in your root
11
+ * component's script, before any other function, for example in
12
+ * `+layout.svelte` in SvelteKit. Pass `baseUrl` and `accessTokenFactory`,
13
+ * and gate them with `enabled`. Every hub that is not lazy starts in
14
+ * `onMount`. On the server, the session is disabled and nothing connects,
15
+ * so a call in `onDestroy` fails at once.
15
16
  */
16
- provideSignalR: (props: import("./types").SignalRProviderProps) => void;
17
+ provideSignalR: (props: import("./types.js").SignalRProviderProps<keyof H & `/${string}`>) => void;
17
18
  /**
18
- * Escape hatch to the raw SignalR context (`getConnection`, `getStatus`,
19
- * `isHubConnected`, and more). Prefer the typed stores/functions below.
20
- * Use this only for the underlying `HubConnection` or a point read.
19
+ * Escape hatch to the SignalR context (`getConnection`, `getStatus`,
20
+ * and `waitForConnection`). Call it during component init, below
21
+ * `provideSignalR`. Prefer the typed functions below. Use this only for
22
+ * the underlying `HubConnection` or a point read.
21
23
  */
22
- getSignalR: () => import("./types").SignalRContextValue<InferContract<H>>;
24
+ getSignalR: () => import("@dammers/use-signalr-core").SignalRPublicContext<InferContract<H>>;
23
25
  /**
24
- * Keeps a (possibly lazy) hub connected for the component's lifetime,
25
- * without subscribing to events or status. Acquires at component init,
26
- * releases on destroy.
26
+ * Keeps a hub connected until the component is destroyed, without
27
+ * subscribing to events or status. Call it during component init. It
28
+ * acquires the hub at once and releases it on destroy.
27
29
  */
28
30
  keepHubAlive: (hub: keyof H & `/${string}`) => void;
29
31
  /**
30
- * Subscribes to a typed server event for the component's lifetime.
31
- * Handler args are inferred from your contract. Re-attaches across
32
- * reconnects.
32
+ * Subscribes to a typed server event until the component is destroyed.
33
+ * Call it during component init. Handler arguments come from your
34
+ * contract. The subscription survives reconnects and rebuilds.
33
35
  */
34
36
  onHubEvent: <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;
35
37
  /**
36
38
  * Typed invoker that waits for the connection and resolves with the
37
- * method's return value. Fails fast by default. Opt in to retry for
38
- * idempotent methods only.
39
+ * method's return value. Call it during component init, then call the
40
+ * invoker later. It fails fast by default. Opt in to retry for idempotent
41
+ * methods only. A pending call rejects with an `AbortError` when the
42
+ * component is destroyed, unless `keepAliveOnUnmount` is true. With
43
+ * `keepAliveOnUnmount`, the call also holds a lazy hub open until it settles.
39
44
  */
40
45
  hubInvoke: <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>>;
41
46
  /**
42
- * Typed fire-and-forget sender. Does not wait for the connection: it
43
- * drops the call (resolves `false`) if not connected, otherwise it
44
- * dispatches the call (`true`). Safe in teardowns.
47
+ * Typed fire-and-forget sender. Call it during component init. It does
48
+ * not wait for the connection. It resolves `true` when it sends the call,
49
+ * and `false` when the hub is not connected or the send fails. It never
50
+ * throws, so a cleanup can call it. For a call that must land in a
51
+ * cleanup, use `hubTeardown`.
45
52
  */
46
53
  hubSend: <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>;
47
54
  /**
48
- * Typed RELIABLE teardown sender for a method invoked in a teardown.
49
- * Survives the calling component's disposal, queues while the hub is
50
- * still connecting instead of dropping, and holds a lazy hub open until
51
- * the flush completes. Best-effort: resolves `true` if dispatched,
52
- * `false` if the hub never connected in time. Never throws.
55
+ * Typed teardown sender for a method that you call in `onDestroy`. Call
56
+ * it during component init. It survives the destroy of the component,
57
+ * queues while the hub is still connecting instead of dropping, and holds
58
+ * a lazy hub open until the flush completes. It resolves `true` if it
59
+ * sends the call. It resolves `false` when the hub does not connect in
60
+ * time, when the session is disabled, or when the send fails. It never throws.
53
61
  */
54
62
  hubTeardown: <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>;
55
63
  /**
56
- * Live connection status of a hub, as a Svelte store. Subscribe with `$`
57
- * to re-render only when THIS hub's status changes. Also keeps a lazy hub
58
- * connected while mounted.
64
+ * Live connection status of a hub, as a Svelte store. Call it during
65
+ * component init. Subscribe with `$` to re-render only when this hub's
66
+ * status changes. It also keeps a lazy hub connected until the component
67
+ * is destroyed.
59
68
  */
60
69
  hubStatus: <H_1 extends keyof H & `/${string}`>(hub: H_1) => import("svelte/store").Readable<import("@dammers/use-signalr-core").HubConnectionStatus>;
61
70
  /**
62
71
  * Runs a callback after each reconnect, not the first connect, to refetch
63
- * state that went stale while offline.
72
+ * state that went stale while offline. Call it during component init.
64
73
  */
65
74
  onReconnected: <H_1 extends keyof H & `/${string}`>(hub: H_1, callback: () => void) => void;
66
75
  };
@@ -1,6 +1,6 @@
1
1
  import { hubKeys, resolveHubConfig } from "@dammers/use-signalr-core";
2
- import { createSignalRProvider } from "./internal/create-provider";
3
- import { createSignalRHooks } from "./internal/create-hooks";
2
+ import { createSignalRProvider } from "./internal/create-provider.js";
3
+ import { createSignalRHooks } from "./internal/create-hooks.js";
4
4
  /**
5
5
  * Creates a fully-typed SignalR client. Returns a provider function and a set
6
6
  * of stores/functions, typed against the contract inferred from
@@ -9,67 +9,76 @@ import { createSignalRHooks } from "./internal/create-hooks";
9
9
  */
10
10
  export function createSignalRClient(config) {
11
11
  const hubs = hubKeys(config);
12
- const resolved = new Map(hubs.map((h) => [h, resolveHubConfig(config, config.hubs[h])]));
12
+ const resolved = new Map(hubs.map((h) => [h, resolveHubConfig(config, h)]));
13
13
  const resolve = (hub) => resolved.get(hub);
14
14
  const contextKey = Symbol("use-signalr");
15
15
  const provideSignalR = createSignalRProvider(contextKey, hubs, resolve);
16
16
  const hooks = createSignalRHooks(contextKey);
17
17
  return {
18
18
  /**
19
- * Builds, starts, retries, and auto-reconnects every configured hub. Call
20
- * once in your root component's script, before any other function — for
21
- * example `+layout.svelte` in SvelteKit. Pass `baseUrl` and
22
- * `accessTokenFactory`, and gate them with `enabled`. All connection work
23
- * happens client-side only, so this is safe to call during SSR.
19
+ * Builds the session and sets the context. Call it once in your root
20
+ * component's script, before any other function, for example in
21
+ * `+layout.svelte` in SvelteKit. Pass `baseUrl` and `accessTokenFactory`,
22
+ * and gate them with `enabled`. Every hub that is not lazy starts in
23
+ * `onMount`. On the server, the session is disabled and nothing connects,
24
+ * so a call in `onDestroy` fails at once.
24
25
  */
25
26
  provideSignalR,
26
27
  /**
27
- * Escape hatch to the raw SignalR context (`getConnection`, `getStatus`,
28
- * `isHubConnected`, and more). Prefer the typed stores/functions below.
29
- * Use this only for the underlying `HubConnection` or a point read.
28
+ * Escape hatch to the SignalR context (`getConnection`, `getStatus`,
29
+ * and `waitForConnection`). Call it during component init, below
30
+ * `provideSignalR`. Prefer the typed functions below. Use this only for
31
+ * the underlying `HubConnection` or a point read.
30
32
  */
31
33
  getSignalR: hooks.getSignalR,
32
34
  /**
33
- * Keeps a (possibly lazy) hub connected for the component's lifetime,
34
- * without subscribing to events or status. Acquires at component init,
35
- * releases on destroy.
35
+ * Keeps a hub connected until the component is destroyed, without
36
+ * subscribing to events or status. Call it during component init. It
37
+ * acquires the hub at once and releases it on destroy.
36
38
  */
37
39
  keepHubAlive: hooks.keepHubAlive,
38
40
  /**
39
- * Subscribes to a typed server event for the component's lifetime.
40
- * Handler args are inferred from your contract. Re-attaches across
41
- * reconnects.
41
+ * Subscribes to a typed server event until the component is destroyed.
42
+ * Call it during component init. Handler arguments come from your
43
+ * contract. The subscription survives reconnects and rebuilds.
42
44
  */
43
45
  onHubEvent: hooks.onHubEvent,
44
46
  /**
45
47
  * Typed invoker that waits for the connection and resolves with the
46
- * method's return value. Fails fast by default. Opt in to retry for
47
- * idempotent methods only.
48
+ * method's return value. Call it during component init, then call the
49
+ * invoker later. It fails fast by default. Opt in to retry for idempotent
50
+ * methods only. A pending call rejects with an `AbortError` when the
51
+ * component is destroyed, unless `keepAliveOnUnmount` is true. With
52
+ * `keepAliveOnUnmount`, the call also holds a lazy hub open until it settles.
48
53
  */
49
54
  hubInvoke: hooks.hubInvoke,
50
55
  /**
51
- * Typed fire-and-forget sender. Does not wait for the connection: it
52
- * drops the call (resolves `false`) if not connected, otherwise it
53
- * dispatches the call (`true`). Safe in teardowns.
56
+ * Typed fire-and-forget sender. Call it during component init. It does
57
+ * not wait for the connection. It resolves `true` when it sends the call,
58
+ * and `false` when the hub is not connected or the send fails. It never
59
+ * throws, so a cleanup can call it. For a call that must land in a
60
+ * cleanup, use `hubTeardown`.
54
61
  */
55
62
  hubSend: hooks.hubSend,
56
63
  /**
57
- * Typed RELIABLE teardown sender for a method invoked in a teardown.
58
- * Survives the calling component's disposal, queues while the hub is
59
- * still connecting instead of dropping, and holds a lazy hub open until
60
- * the flush completes. Best-effort: resolves `true` if dispatched,
61
- * `false` if the hub never connected in time. Never throws.
64
+ * Typed teardown sender for a method that you call in `onDestroy`. Call
65
+ * it during component init. It survives the destroy of the component,
66
+ * queues while the hub is still connecting instead of dropping, and holds
67
+ * a lazy hub open until the flush completes. It resolves `true` if it
68
+ * sends the call. It resolves `false` when the hub does not connect in
69
+ * time, when the session is disabled, or when the send fails. It never throws.
62
70
  */
63
71
  hubTeardown: hooks.hubTeardown,
64
72
  /**
65
- * Live connection status of a hub, as a Svelte store. Subscribe with `$`
66
- * to re-render only when THIS hub's status changes. Also keeps a lazy hub
67
- * connected while mounted.
73
+ * Live connection status of a hub, as a Svelte store. Call it during
74
+ * component init. Subscribe with `$` to re-render only when this hub's
75
+ * status changes. It also keeps a lazy hub connected until the component
76
+ * is destroyed.
68
77
  */
69
78
  hubStatus: hooks.hubStatus,
70
79
  /**
71
80
  * Runs a callback after each reconnect, not the first connect, to refetch
72
- * state that went stale while offline.
81
+ * state that went stale while offline. Call it during component init.
73
82
  */
74
83
  onReconnected: hooks.onReconnected,
75
84
  };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- export { createSignalRClient } from "./create-signalr-client";
2
- export { InvokeError, event, method } from "@dammers/use-signalr-core";
3
- export type { StatusStore } from "./status-store";
4
- export type { HubString, HubContract, SignalRContract, SignalRClientConfig, PerHubConfig, HubDef, EventDef, MethodDef, InferContract, ResolvedHubConfig, ReconnectConfig, InvokeOptions, TeardownOptions, HubConnectionStatus, EventName, MethodName, EventArgs, MethodArgs, MethodReturn, } from "@dammers/use-signalr-core";
5
- export type { MaybeReadable, 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 { MaybeReadable, SignalRProviderProps } from "./types.js";
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { createSignalRClient } from "./create-signalr-client";
2
- export { InvokeError, event, method } from "@dammers/use-signalr-core";
1
+ export { createSignalRClient } from "./create-signalr-client.js";
2
+ export { event, method } from "@dammers/use-signalr-core";
@@ -1,14 +1,13 @@
1
1
  import type { Readable } from "svelte/store";
2
- import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions, MethodArgs, MethodName, MethodReturn, SignalRContract } from "@dammers/use-signalr-core";
3
- import type { SignalRContextValue } from "../types";
2
+ import type { EventArgs, EventName, HubConnectionStatus, InvokeOptions, TeardownOptions, MethodName, SignalRContract, SignalRPublicContext } from "@dammers/use-signalr-core";
4
3
  /** Builds the functions bound to one client's context. */
5
4
  export declare function createSignalRHooks<T extends SignalRContract>(contextKey: symbol): {
6
- getSignalR: () => SignalRContextValue<T>;
5
+ getSignalR: () => SignalRPublicContext<T>;
7
6
  keepHubAlive: (hub: keyof T & `/${string}`) => void;
8
7
  hubStatus: <H extends keyof T & `/${string}`>(hub: H) => Readable<HubConnectionStatus>;
9
8
  onReconnected: <H extends keyof T & `/${string}`>(hub: H, callback: () => void) => void;
10
9
  onHubEvent: <H extends keyof T & `/${string}`, E extends EventName<T, H>>(hub: H, event: E, handler: (...args: EventArgs<T, H, E>) => void) => void;
11
- hubInvoke: <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
- hubSend: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M) => (...args: MethodArgs<T, H, M>) => Promise<boolean>;
13
- hubTeardown: <H extends keyof T & `/${string}`, M extends MethodName<T, H>>(hub: H, method: M, options?: TeardownOptions) => (...args: MethodArgs<T, H, M>) => Promise<boolean>;
10
+ hubInvoke: <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>>;
11
+ hubSend: <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>;
12
+ hubTeardown: <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
13
  };
@@ -1,190 +1,68 @@
1
1
  import { getContext, onDestroy } from "svelte";
2
- import { createInvoker, createSender, createTeardownSender } from "@dammers/use-signalr-core";
2
+ import { createAbortScope, createInvoker, createSender, createTeardownSender, } from "@dammers/use-signalr-core";
3
3
  /** Builds the functions bound to one client's context. */
4
4
  export function createSignalRHooks(contextKey) {
5
- /**
6
- * Escape hatch to the raw SignalR context. Prefer the typed stores/functions
7
- * below. Reach for this only when you need the underlying `HubConnection`
8
- * or a point read.
9
- *
10
- * @returns The context value: `getConnection`, `isHubConnected`, `getStatus`,
11
- * `waitForConnection`, `acquire`/`release`, `registerReconnect`, `statusStore`.
12
- * @throws If called outside `provideSignalR`.
13
- */
14
- function getSignalR() {
5
+ function getInternalContext(name) {
15
6
  const ctx = getContext(contextKey);
16
7
  if (!ctx)
17
- throw new Error("getSignalR must be called during component init, below provideSignalR");
8
+ throw new Error(`${name} must be called during component init, below provideSignalR`);
18
9
  return ctx;
19
10
  }
20
- /**
21
- * Keeps a (possibly lazy) hub alive for this component's lifetime, without
22
- * subscribing to events or status. Acquires at component init, releases on
23
- * `onDestroy`.
24
- *
25
- * Most functions already do this internally. Use it directly only when you
26
- * want a lazy hub connected for a component that does not otherwise touch it.
27
- *
28
- * @param hub The hub path to keep connected.
29
- */
11
+ function getSignalR() {
12
+ return getInternalContext("getSignalR").publicContext;
13
+ }
30
14
  function keepHubAlive(hub) {
31
- const { acquire, release } = getSignalR();
15
+ const { acquire, release } = getInternalContext("keepHubAlive");
32
16
  acquire(hub);
33
17
  onDestroy(() => release(hub));
34
18
  }
35
- /**
36
- * Live connection status of a hub, as a Svelte store. Subscribe with `$` in
37
- * a component to re-render only when THIS hub's status changes, not when
38
- * another hub changes. Also keeps the hub alive while mounted, so a lazy
39
- * hub connects on first use.
40
- *
41
- * @param hub The hub path to watch.
42
- * @returns A `Readable<"disconnected" | "connecting" | "connected" | "reconnecting" | "reconnected">`.
43
- */
44
19
  function hubStatus(hub) {
45
- const { statusStore } = getSignalR();
20
+ const { statusStore } = getInternalContext("hubStatus");
46
21
  keepHubAlive(hub);
47
22
  return statusStore.readable(hub);
48
23
  }
49
- /**
50
- * Runs a callback every time a hub reconnects, after a dropped connection
51
- * is re-established, to refetch state that may have gone stale while
52
- * offline. Does NOT fire on the first connect, only on reconnects.
53
- *
54
- * @param hub The hub path to watch.
55
- * @param callback Invoked after each successful reconnect.
56
- */
57
24
  function onReconnected(hub, callback) {
58
- const { registerReconnect } = getSignalR();
25
+ const { registerReconnect } = getInternalContext("onReconnected");
59
26
  keepHubAlive(hub);
60
27
  const unsub = registerReconnect(hub, () => callback());
61
28
  onDestroy(unsub);
62
29
  }
63
- /**
64
- * Subscribes to a typed server event for the lifetime of the component. The
65
- * handler's args are inferred from your contract for `(hub, event)`. The
66
- * subscription attaches once the hub is connected, re-attaches across
67
- * reconnects, and detaches on `onDestroy`.
68
- *
69
- * @param hub The hub path.
70
- * @param event The event name, a key of that hub's `events`.
71
- * @param handler Called with the event's typed args each time the server pushes it.
72
- */
73
30
  function onHubEvent(hub, event, handler) {
74
- const { statusStore, getConnection } = getSignalR();
31
+ const { subscribe } = getInternalContext("onHubEvent");
75
32
  keepHubAlive(hub);
76
- let attachedConn = null;
77
- const listener = (...args) => handler(...args);
78
- const detach = () => {
79
- if (!attachedConn)
80
- return;
81
- attachedConn.off(event, listener);
82
- attachedConn = null;
83
- };
84
- const unsubscribe = statusStore.readable(hub).subscribe((status) => {
85
- if (status !== "connected") {
86
- detach();
87
- return;
88
- }
89
- if (attachedConn)
90
- return; // already attached this connected phase
91
- const connection = getConnection(hub);
92
- if (!connection)
93
- return;
94
- connection.on(event, listener);
95
- attachedConn = connection;
96
- });
97
- onDestroy(() => {
98
- unsubscribe();
99
- detach();
100
- });
33
+ const unsubscribe = subscribe(hub, event, (...args) => handler(...args));
34
+ onDestroy(unsubscribe);
101
35
  }
102
- /**
103
- * Returns a stable, typed function that invokes a hub method and resolves
104
- * with its return value. It waits, up to `timeout`, for the connection
105
- * before it invokes, so calling right after component init is safe.
106
- *
107
- * Special behavior:
108
- * - **Fails fast by default** (`retries: 0`): rethrows the raw server error,
109
- * so callers see the original.
110
- * - **Opt-in retry** for retriable failures (transport drops, timeouts),
111
- * with jittered backoff. Business errors (a `HubException` thrown while
112
- * still connected) are never retried.
113
- * - **At-least-once when retrying.** Enable `retries` only for IDEMPOTENT methods.
114
- * - **Auto-aborts** any in-flight call or retry loop on `onDestroy`, UNLESS
115
- * `keepAliveOnUnmount: true`. For a method invoked in a teardown, set that
116
- * flag, or prefer {@link hubTeardown}, which also handles the
117
- * hub-still-connecting race.
118
- *
119
- * @param hub The hub path.
120
- * @param method The method name, a key of that hub's `methods`.
121
- * @param options Optional `retries`, `timeout`, `backoff`, `isRetriable`, `keepAliveOnUnmount`.
122
- * @returns An async fn that takes the method's typed args and resolves to its typed return.
123
- * @throws The raw error when `retries === 0`. Otherwise an {@link InvokeError}
124
- * that wraps the last failure once attempts are exhausted.
125
- */
126
36
  function hubInvoke(hub, method, options) {
127
- const { waitForConnection, getConnection } = getSignalR();
37
+ const { waitForConnection, getConnection, acquire, release } = getInternalContext("hubInvoke");
128
38
  keepHubAlive(hub);
129
- let abort = null;
39
+ const scope = createAbortScope();
130
40
  onDestroy(() => {
131
41
  if (!options?.keepAliveOnUnmount)
132
- abort?.abort();
42
+ scope.abort();
133
43
  });
134
- return createInvoker({ waitForConnection, getConnection }, hub, method, () => options, (ac) => {
135
- abort = ac;
44
+ return createInvoker({
45
+ target: { waitForConnection, getConnection, acquire, release },
46
+ hub,
47
+ method,
48
+ getOptions: () => options,
49
+ getSignal: scope.signal,
136
50
  });
137
51
  }
138
- /**
139
- * Returns a stable, typed fire-and-forget sender. Unlike {@link hubInvoke},
140
- * it does NOT wait for the connection and does NOT return the method's
141
- * result. If the hub is not Connected, the call is dropped (resolves
142
- * `false`); otherwise it is dispatched (resolves `true`).
143
- *
144
- * Reads the connection at call time and never depends on reactive state, so
145
- * it is safe to capture in a teardown.
146
- *
147
- * @param hub The hub path.
148
- * @param method The method name, a key of that hub's `methods`.
149
- * @returns An async fn that takes the method's typed args and resolves
150
- * `true` if dispatched, `false` if dropped because it was not connected.
151
- */
152
52
  function hubSend(hub, method) {
153
- const { getConnection } = getSignalR();
53
+ const { getConnection } = getInternalContext("hubSend");
154
54
  keepHubAlive(hub);
155
- return createSender(getConnection, hub, method);
55
+ return createSender({ getConnection, hub, method });
156
56
  }
157
- /**
158
- * Returns a stable, typed RELIABLE teardown sender, built for a method
159
- * invoked in a teardown. Unlike {@link hubSend}, which drops a call if
160
- * not yet connected, and {@link hubInvoke}, which aborts in-flight
161
- * calls on `onDestroy`, the returned function:
162
- *
163
- * - **Survives the calling component's disposal.** It runs detached, not
164
- * tied to any subscription or AbortController, so a call issued in
165
- * `onDestroy` still lands.
166
- * - **Queues while connecting.** It waits, up to `timeout`, for the hub to
167
- * (re)connect, then sends, instead of dropping the call.
168
- * - **Holds a lazy hub open** until the flush completes, even when the
169
- * calling component was the last consumer — it acquires and releases
170
- * independently.
171
- * - **Is best-effort and fire-and-forget.** It resolves `true` once
172
- * dispatched, `false` if the hub never connected within `timeout`, and
173
- * never throws.
174
- *
175
- * Also lands when the calling component is destroyed immediately after
176
- * initializing — the queued call still flushes.
177
- *
178
- * @param hub The hub path.
179
- * @param method The teardown method name, a key of that hub's `methods`.
180
- * @param options Optional `timeout` in ms to wait for a connection. Default 10_000.
181
- * @returns An async fn that takes the method's typed args and resolves
182
- * `true` if dispatched, `false` if the hub never connected in time.
183
- */
184
57
  function hubTeardown(hub, method, options) {
185
- const { acquire, release, waitForConnection } = getSignalR();
58
+ const { acquire, release, waitForConnection } = getInternalContext("hubTeardown");
186
59
  keepHubAlive(hub);
187
- return createTeardownSender({ acquire, release, waitForConnection }, hub, method, () => options);
60
+ return createTeardownSender({
61
+ target: { acquire, release, waitForConnection },
62
+ hub,
63
+ method,
64
+ getOptions: () => options,
65
+ });
188
66
  }
189
67
  return {
190
68
  getSignalR,
@@ -1,4 +1,4 @@
1
1
  import type { HubString, ResolvedHubConfig, SignalRContract } from "@dammers/use-signalr-core";
2
- import type { SignalRProviderProps } from "../types";
2
+ import type { SignalRProviderProps } from "../types.js";
3
3
  /** Builds the `provideSignalR` function bound to one client's context. */
4
- export declare function createSignalRProvider<T extends SignalRContract>(contextKey: symbol, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): (props: SignalRProviderProps) => void;
4
+ export declare function createSignalRProvider<T extends SignalRContract>(contextKey: symbol, hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig): (props: SignalRProviderProps<keyof T & `/${string}`>) => void;
@@ -1,6 +1,6 @@
1
1
  import { setContext, onMount } from "svelte";
2
2
  import { derived, readable } from "svelte/store";
3
- import { createStatusStore } from "../status-store";
3
+ import { createStatusStore } from "../status-store.js";
4
4
  import { createSignalRSession } from "@dammers/use-signalr-core";
5
5
  function isReadable(value) {
6
6
  return (typeof value === "object" &&
@@ -9,7 +9,7 @@ function isReadable(value) {
9
9
  typeof value.subscribe === "function");
10
10
  }
11
11
  function toReadable(value) {
12
- return isReadable(value) ? value : readable(value, () => { });
12
+ return isReadable(value) ? value : readable(value);
13
13
  }
14
14
  /** Builds the `provideSignalR` function bound to one client's context. */
15
15
  export function createSignalRProvider(contextKey, hubs, resolve) {
@@ -21,21 +21,40 @@ export function createSignalRProvider(contextKey, hubs, resolve) {
21
21
  statusStore,
22
22
  getAccessToken: () => props.accessTokenFactory(),
23
23
  onStatusChange: (hub, status) => props.onStatusChange?.(hub, status),
24
- onError: (hub, err) => props.onError?.(hub, err),
24
+ onError: (hub, err, info) => props.onError?.(hub, err, info),
25
25
  });
26
26
  const baseUrl$ = toReadable(props.baseUrl);
27
27
  const enabled$ = toReadable(props.enabled ?? true);
28
28
  const connectionKey$ = toReadable(props.connectionKey);
29
- const identity$ = derived([baseUrl$, enabled$, connectionKey$], ([baseUrl, enabled]) => [baseUrl, enabled]);
30
- // All connection work is client-side only: onMount never runs during SSR.
29
+ const identity$ = derived([baseUrl$, enabled$, connectionKey$], ([baseUrl, enabled, connectionKey]) => ({ baseUrl, enabled, connectionKey }));
30
+ // Svelte runs onDestroy but not onMount on the server, so a waiting call must fail at once.
31
+ if (typeof window === "undefined") {
32
+ session.update({ baseUrl: undefined, enabled: false, connectionKey: undefined });
33
+ }
31
34
  onMount(() => {
32
- const unsubscribe = identity$.subscribe(([baseUrl, enabled]) => {
33
- session.stop();
34
- if (!enabled || !baseUrl)
35
+ let first = true;
36
+ let stopped = false;
37
+ let pending;
38
+ const unsubscribe = identity$.subscribe((values) => {
39
+ if (first) {
40
+ first = false;
41
+ session.update(values);
42
+ return;
43
+ }
44
+ const scheduled = pending !== undefined;
45
+ pending = values;
46
+ if (scheduled)
35
47
  return;
36
- session.start(baseUrl);
48
+ queueMicrotask(() => {
49
+ if (stopped || !pending)
50
+ return;
51
+ const latest = pending;
52
+ pending = undefined;
53
+ session.update(latest);
54
+ });
37
55
  });
38
56
  return () => {
57
+ stopped = true;
39
58
  unsubscribe();
40
59
  session.stop();
41
60
  };
@@ -4,9 +4,5 @@ export interface StatusStore<H extends string> extends StatusStoreBase<H> {
4
4
  /** Readable store for one hub's status; subscribe with `$` in components. */
5
5
  readable: (hub: H) => Readable<HubConnectionStatus>;
6
6
  }
7
- /**
8
- * Small store for hub statuses, backed by one Svelte writable per hub,
9
- * created lazily on first access. `set` dedupes by hand since a Svelte
10
- * writable notifies subscribers even on an equal value.
11
- */
7
+ /** Hub statuses, backed by one Svelte writable per hub, created on first access. */
12
8
  export declare function createStatusStore<H extends string>(): StatusStore<H>;
@@ -1,27 +1,18 @@
1
1
  import { writable, get as readStore } from "svelte/store";
2
- /**
3
- * Small store for hub statuses, backed by one Svelte writable per hub,
4
- * created lazily on first access. `set` dedupes by hand since a Svelte
5
- * writable notifies subscribers even on an equal value.
6
- */
2
+ /** Hub statuses, backed by one Svelte writable per hub, created on first access. */
7
3
  export function createStatusStore() {
8
4
  const stores = new Map();
9
5
  const getOrCreate = (hub) => {
10
6
  let store = stores.get(hub);
11
7
  if (!store) {
12
- store = writable("disconnected");
8
+ store = writable("idle");
13
9
  stores.set(hub, store);
14
10
  }
15
11
  return store;
16
12
  };
17
13
  return {
18
14
  get: (hub) => readStore(getOrCreate(hub)),
19
- set: (hub, status) => {
20
- const store = getOrCreate(hub);
21
- if (readStore(store) === status)
22
- return;
23
- store.set(status);
24
- },
25
- readable: (hub) => getOrCreate(hub),
15
+ set: (hub, status) => getOrCreate(hub).set(status),
16
+ readable: (hub) => ({ subscribe: getOrCreate(hub).subscribe }),
26
17
  };
27
18
  }
package/dist/types.d.ts CHANGED
@@ -1,11 +1,17 @@
1
1
  import type { Readable } from "svelte/store";
2
2
  import type { SignalRContract, SignalRProviderPropsBase, SignalRContextValueBase, HubString } from "@dammers/use-signalr-core";
3
- import type { StatusStore } from "./status-store";
3
+ import type { StatusStore } from "./status-store.js";
4
4
  /** A value that can also be supplied as a store, to make the provider react to it. */
5
5
  export type MaybeReadable<T> = T | Readable<T>;
6
- export type SignalRProviderProps = Omit<SignalRProviderPropsBase<never>, "children" | "baseUrl" | "enabled" | "connectionKey"> & {
6
+ export type SignalRProviderProps<THub extends HubString = HubString> = Omit<SignalRProviderPropsBase<THub>, "baseUrl" | "enabled" | "connectionKey"> & {
7
+ /** 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. */
7
8
  baseUrl: MaybeReadable<string | undefined>;
9
+ /**
10
+ * 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`.
11
+ * @default true
12
+ */
8
13
  enabled?: MaybeReadable<boolean>;
14
+ /** A new value rebuilds all connections. Use it to recover from `disconnected`. Pass a user ID or a login counter, not the token. */
9
15
  connectionKey?: MaybeReadable<string | number | undefined>;
10
16
  };
11
17
  export type SignalRContextValue<T extends SignalRContract> = SignalRContextValueBase<T, StatusStore<keyof T & HubString>>;
package/package.json CHANGED
@@ -1,60 +1,63 @@
1
- {
2
- "name": "@dammers/use-signalr-svelte",
3
- "version": "0.4.0",
4
- "description": "Fully-typed multi-hub SignalR provider + stores for Svelte: auto-reconnect, invoke retry, lazy hubs, live status.",
5
- "author": "Dammers",
6
- "license": "MIT",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/DammersCode/use-signalr.git",
10
- "directory": "packages/svelte"
11
- },
12
- "homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/svelte#readme",
13
- "bugs": "https://github.com/DammersCode/use-signalr/issues",
14
- "keywords": [
15
- "svelte",
16
- "sveltekit",
17
- "signalr",
18
- "stores",
19
- "typescript",
20
- "realtime",
21
- "websocket"
22
- ],
23
- "engines": {
24
- "node": ">=18"
25
- },
26
- "type": "module",
27
- "sideEffects": false,
28
- "main": "./dist/index.js",
29
- "types": "./dist/index.d.ts",
30
- "exports": {
31
- ".": {
32
- "types": "./dist/index.d.ts",
33
- "import": "./dist/index.js"
34
- }
35
- },
36
- "files": [
37
- "dist"
38
- ],
39
- "publishConfig": {
40
- "access": "public"
41
- },
42
- "scripts": {
43
- "build": "tsc -p tsconfig.build.json",
44
- "typecheck": "tsc --noEmit",
45
- "test": "vitest run"
46
- },
47
- "dependencies": {
48
- "@dammers/use-signalr-core": "0.4.0"
49
- },
50
- "peerDependencies": {
51
- "@microsoft/signalr": ">=8",
52
- "svelte": ">=4"
53
- },
54
- "devDependencies": {
55
- "@microsoft/signalr": ">=8",
56
- "svelte": "^5.0.0",
57
- "@sveltejs/vite-plugin-svelte": "^7.3.0",
58
- "@testing-library/svelte": "^5.4.2"
59
- }
60
- }
1
+ {
2
+ "name": "@dammers/use-signalr-svelte",
3
+ "version": "1.0.0",
4
+ "description": "Fully-typed multi-hub SignalR provider + stores for Svelte: auto-reconnect, invoke retry, lazy hubs, live status.",
5
+ "author": "Dammers",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/DammersCode/use-signalr.git",
10
+ "directory": "packages/svelte"
11
+ },
12
+ "homepage": "https://use-signalr.vercel.app/docs/svelte",
13
+ "bugs": "https://github.com/DammersCode/use-signalr/issues",
14
+ "keywords": [
15
+ "svelte",
16
+ "sveltekit",
17
+ "signalr",
18
+ "stores",
19
+ "typescript",
20
+ "realtime",
21
+ "websocket"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20.19"
25
+ },
26
+ "type": "module",
27
+ "sideEffects": false,
28
+ "main": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./dist/index.d.ts",
33
+ "import": "./dist/index.js",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./package.json": "./package.json"
37
+ },
38
+ "files": [
39
+ "dist"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "scripts": {
45
+ "prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
46
+ "build": "tsc -p tsconfig.build.json",
47
+ "typecheck": "tsc --noEmit",
48
+ "test": "vitest run"
49
+ },
50
+ "dependencies": {
51
+ "@dammers/use-signalr-core": "1.0.0"
52
+ },
53
+ "peerDependencies": {
54
+ "@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0",
55
+ "svelte": "^5.15.0"
56
+ },
57
+ "devDependencies": {
58
+ "@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0",
59
+ "svelte": "^5.15.0",
60
+ "@sveltejs/vite-plugin-svelte": "^7.3.0",
61
+ "@testing-library/svelte": "^5.4.2"
62
+ }
63
+ }