@dammers/use-signalr-lit 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,203 +1,63 @@
1
- # @dammers/use-signalr-lit
2
-
3
- Typed SignalR Reactive Controllers for Lit. A session shares core connections between custom elements.
4
-
5
- [![npm](https://img.shields.io/npm/v/@dammers/use-signalr-lit.svg)](https://www.npmjs.com/package/@dammers/use-signalr-lit)
6
- [![types](https://img.shields.io/badge/types-included-blue.svg)](#api)
7
- [![license](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)
8
-
9
- ```ts
10
- const { createSession } = createSignalRClient({
11
- hubs: {
12
- "/hubs/chat": {
13
- methods: { Join: method<[room: string]>() },
14
- },
15
- },
16
- });
17
- ```
18
-
19
- One factory call infers every hub, event, method, argument, and result type. Reactive Controllers adapt the shared core session to Lit.
20
-
21
- The [root README](https://github.com/DammersCode/use-signalr#readme) documents shared configuration and call behavior. This document covers Lit-specific installation and usage.
22
-
23
- ## Install
24
-
25
- ```bash
26
- npm i @dammers/use-signalr-lit @microsoft/signalr lit
27
- ```
28
-
29
- This package requires Lit 3 or later. It does not require `@lit/context`.
30
-
31
- ## Usage
32
-
33
- ### 1. Define the contract and create a shared session
34
-
35
- Create the client once. Then create and export one shared session for the application.
36
-
37
- ```ts
38
- import { createSignalRClient, event, method } from "@dammers/use-signalr-lit";
39
-
40
- export const signalR = createSignalRClient({
41
- hubs: {
42
- "/hubs/chat": {
43
- lazy: true,
44
- events: { Receive: event<[user: string, text: string]>() },
45
- methods: {
46
- Join: method<[room: string]>(),
47
- Typing: method<[room: string]>(),
48
- Leave: method<[room: string]>(),
49
- },
50
- },
51
- },
52
- });
53
-
54
- export const signalRSession = signalR.createSession({
55
- baseUrl: "https://api.example.com",
56
- accessTokenFactory: () => getAccessToken(),
57
- });
58
- ```
59
-
60
- The factory does not start connections. The first connected controller starts the shared session.
61
-
62
- ### 2. Attach a hub controller
63
-
64
- Create one hub controller in each custom element that uses a hub.
65
-
66
- ```ts
67
- import { LitElement, html } from "lit";
68
- import { signalRSession } from "./signalr";
69
-
70
- class ChatView extends LitElement {
71
- private readonly chat = signalRSession.hub(this, "/hubs/chat", {
72
- reactiveStatus: true,
73
- });
74
- private readonly join = this.chat.invoke("Join");
75
- private readonly leave = this.chat.teardown("Leave");
76
-
77
- constructor() {
78
- super();
79
- this.chat.on("Receive", (user, text) => console.log(user, text));
80
- this.chat.onReconnected(() => this.loadMessages());
81
- }
82
-
83
- render() { return html`<p>${this.chat.status}</p>`; }
84
- }
85
- customElements.define("chat-view", ChatView);
86
- ```
87
-
88
- The controller acquires the lazy hub in `hostConnected()`. It releases the hub and event listeners in `hostDisconnected()`.
89
-
90
- ### 3. Invoke, send, and teardown
91
-
92
- The call factories preserve the method types from the contract.
93
-
94
- ```ts
95
- private readonly join = this.chat.invoke("Join");
96
- private readonly typing = this.chat.send("Typing");
97
- private readonly leave = this.chat.teardown("Leave");
98
-
99
- async enterRoom(room: string) {
100
- await this.join(room);
101
- }
102
-
103
- override disconnectedCallback() {
104
- super.disconnectedCallback();
105
- void this.leave("general");
106
- }
107
- ```
108
-
109
- ## Reactive and imperative events
110
-
111
- Set `reactiveStatus: true` when status changes must render the host. The controller requests updates only for that hub. Events are imperative. An event handler does not request a render. Call `this.requestUpdate()` in the handler when event data changes rendered state.
112
-
113
- `on(event, handler)` returns an unsubscribe function. Multiple handlers can use the same event. `onReconnected(callback)` runs after reconnect.
114
-
115
- ## Calls and lazy hubs
116
-
117
- `invoke(method, options?)` waits for a connection and returns the typed result. It aborts pending retry work when the host disconnects unless `keepAliveOnUnmount` is true.
118
-
119
- `send(method)` returns `false` when the hub is disconnected. `teardown(method, options?)` waits for a connection and remains active after host disconnection. Use teardown calls for leave operations.
120
-
121
- `invoke` accepts a `timeout`. It bounds only the wait for a connected hub before dispatch. SignalR cannot cancel an invocation after dispatch.
122
-
123
- Lazy hubs connect when a controller host connects. They stop after all hosts disconnect and the configured `graceMs` period passes.
124
-
125
- Set `graceMs` for each hub in the client configuration. After the last host disconnects, the connection stays open for `graceMs` milliseconds. If a new host connects inside that window, the connection stays. The default is `0`.
126
-
127
- ```ts
128
- createSignalRClient({
129
- hubs: {
130
- "/hubs/chat": { lazy: true, graceMs: 5000 },
131
- },
132
- });
133
- ```
134
-
135
- Eager hubs remain active until `signalRSession.stop()` runs.
136
-
137
- ## `InvokeError`
138
-
139
- `invoke` throws `InvokeError` when its retry budget is exhausted. The error carries `cause` (the last underlying error), `attempts` (the total number of attempts), and `retriable` (whether the final failure was classed as retriable).
140
-
141
- `InvokeError` is thrown only when you set `retries` above `0`. With the default `retries: 0`, the raw server error propagates unchanged.
142
-
143
- ## Sharing across custom elements
144
-
145
- Export the session from a normal module. Import the same session into each custom element that needs SignalR.
146
-
147
- This pattern does not require a global application root or `@lit/context`. Components in separate DOM trees can share the same session instance.
148
-
149
- Create a different session when an application needs an independent base URL or authentication boundary. Call `signalRSession.stop()` during logout or application shutdown.
150
-
151
- The current token is read through `accessTokenFactory` during each negotiation. Token rotation does not create a new session.
152
-
153
- ## Session options are read once
154
-
155
- The session reads `baseUrl` and `enabled` once, when the first host connects. There is no `connectionKey`.
156
-
157
- To change either option, call `session.stop()` and create a new session with the new values. This is intentional. Lit has no application-wide provider to watch for a changed option.
158
-
159
- ```ts
160
- signalRSession.stop();
161
- export const signalRSession = signalR.createSession({ baseUrl: nextUrl });
162
- ```
163
-
164
- Every other adapter rebuilds its connections when `baseUrl`, `enabled`, or `connectionKey` change.
165
-
166
- ## Raw escape hatch
167
-
168
- `session.context` exposes the raw core context: `getConnection`, `isHubConnected`, and `getStatus`. Use it only when the typed controller surface cannot express a call.
169
-
170
- ```ts
171
- signalRSession.context.getConnection("/hubs/chat")?.send("Typing", "general");
172
- ```
173
-
174
- This member has the same role as `useSignalR()` in React, `getSignalR()` in Svelte, and `injectSignalR()` in Angular.
175
-
176
- ## SSR
177
-
178
- Package import, client creation, session creation, and controller construction do not start connections. Lit calls `hostConnected()` only in the browser.
179
-
180
- ## API
181
-
182
- | Export | Description |
183
- | --- | --- |
184
- | `createSignalRClient(config)` | Creates a typed client factory. |
185
- | `createSession(options)` | Creates an explicit shared runtime session. |
186
- | `session.hub(host, hub, options?)` | Creates a per-hub Reactive Controller. |
187
- | `controller.status` | Reads the current hub status. |
188
- | `controller.on()` | Registers a typed imperative event handler. |
189
- | `controller.invoke()` | Creates a typed invoker. |
190
- | `controller.send()` | Creates a typed lossy sender. |
191
- | `controller.teardown()` | Creates a typed reliable teardown sender. |
192
- | `controller.onReconnected()` | Registers a callback that runs after reconnect. |
193
- | `session.context` | Reads the raw core context: `getConnection`, `isHubConnected`, `getStatus`. |
194
- | `session.stop()` | Stops all connections in the shared session. |
195
- | `InvokeError` | Wraps the last invoke failure after configured retries are exhausted. |
196
-
197
- ## More
198
-
199
- Read the [root README](https://github.com/DammersCode/use-signalr#readme) for shared connection options and retry behavior.
200
-
201
- ## License
202
-
203
- MIT © [DammersCode](https://github.com/DammersCode)
1
+ # @dammers/use-signalr-lit
2
+
3
+ Reactive controllers for typed [SignalR](https://learn.microsoft.com/aspnet/core/signalr) in Lit. Part of [use-signalr](https://use-signalr.vercel.app).
4
+
5
+ [![npm](https://img.shields.io/npm/v/@dammers/use-signalr-lit.svg)](https://www.npmjs.com/package/@dammers/use-signalr-lit)
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-lit @microsoft/signalr
12
+ ```
13
+
14
+ It needs Lit ^3, `@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:lit:start -->
21
+ ```ts
22
+ import { LitElement, html } from "lit";
23
+ import { customElement, state } from "lit/decorators.js";
24
+ import { createSignalRClient, method } from "@dammers/use-signalr-lit";
25
+
26
+ const { createSession } = createSignalRClient({
27
+ hubs: {
28
+ "/hubs/rooms": {
29
+ methods: { GetHistory: method<[roomId: string], { text: string }[]>() },
30
+ },
31
+ },
32
+ });
33
+ const session = createSession({ baseUrl: "https://api.example.com", accessTokenFactory: () => "token" });
34
+
35
+ @customElement("history-count")
36
+ export class HistoryCount extends LitElement {
37
+ private rooms = session.hub(this, "/hubs/rooms");
38
+ private getHistory = this.rooms.invoke("GetHistory");
39
+ @state() private count = 0;
40
+
41
+ private load() {
42
+ this.getHistory("general").then((m) => (this.count = m.length)).catch(console.error);
43
+ }
44
+
45
+ render() {
46
+ return html`<button @click=${this.load}>${this.count} messages</button>`;
47
+ }
48
+ }
49
+ ```
50
+ <!-- hero:lit:end -->
51
+
52
+ ## Documentation
53
+
54
+ - [Quick start](https://use-signalr.vercel.app/docs/lit/quick-start)
55
+ - [Session setup](https://use-signalr.vercel.app/docs/lit/concepts/provider)
56
+ - [Events](https://use-signalr.vercel.app/docs/lit/concepts/events) and [calls](https://use-signalr.vercel.app/docs/lit/concepts/calls)
57
+ - [Connection status](https://use-signalr.vercel.app/docs/lit/concepts/connection-status) and [recovery](https://use-signalr.vercel.app/docs/lit/concepts/recovery)
58
+ - [API reference](https://use-signalr.vercel.app/docs/lit/reference/api)
59
+ - [Troubleshooting](https://use-signalr.vercel.app/docs/lit/reference/troubleshooting)
60
+
61
+ ## License
62
+
63
+ [MIT](https://github.com/DammersCode/use-signalr/blob/main/LICENSE) © [DammersCode](https://github.com/DammersCode)
@@ -1,17 +1,40 @@
1
1
  import type { ReactiveController, ReactiveControllerHost } from "lit";
2
- import type { EventArgs, EventName, HubConnectionStatus, HubDef, HubString, InferContract, InvokeOptions, MethodName, SignalRClientConfig, SignalRContract, TeardownOptions } from "@dammers/use-signalr-core";
3
- import type { SignalRContextValue, SignalRSessionOptions } from "./types.js";
2
+ import type { EventArgs, EventName, HubConnectionStatus, HubDef, HubString, InferContract, InvokeOptions, MethodName, ResolvedHubConfig, SignalRClientConfig, SignalRContract, TeardownOptions } from "@dammers/use-signalr-core";
3
+ import type { SignalRContextValue, SignalRSessionOptions, SignalRSessionUpdate } from "./types.js";
4
+ /** Creates a typed SignalR client. Call `createSession` once to get a session for your app. */
4
5
  export declare function createSignalRClient<const H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): {
6
+ /** Builds a session that starts, retries, and reconnects every configured hub. It starts when the first host connects. Pass `baseUrl` and `accessTokenFactory`, and gate them with `enabled`. */
5
7
  createSession(options: SignalRSessionOptions<keyof H & `/${string}`>): {
8
+ /** Creates a `HubController` for one hub on a Lit host. The hub connects while the host is connected. */
6
9
  hub: <H_1 extends keyof H & `/${string}`>(host: ReactiveControllerHost, name: H_1, controllerOptions?: {
10
+ /** Set to `false` to not request a host update on each status change. The default is `true`. */
7
11
  reactiveStatus?: boolean;
8
12
  } | undefined) => HubController<InferContract<H>, H_1>;
13
+ /** Changes session options, for example a new `baseUrl` or `enabled`. Values set before the first host connects apply when it connects. It restarts a stopped session. An `undefined` `accessTokenFactory` keeps the old one. */
14
+ update: (partial: Partial<Pick<SignalRSessionOptions<`/${string}`>, "baseUrl" | "enabled" | "connectionKey" | "accessTokenFactory">>) => void;
15
+ /** Stops every hub and releases the connections. The session stays stopped until the next `update()`. */
9
16
  stop: () => void;
10
- context: import("@dammers/use-signalr-core").SignalRContextValueBase<InferContract<H>, import("./status-store.js").StatusStore<keyof H & `/${string}`>>;
17
+ /** Escape hatch to the SignalR context (`getConnection`, `getStatus`, and `waitForConnection`). Use this only for the underlying `HubConnection` or a point read. */
18
+ context: import("@dammers/use-signalr-core").SignalRPublicContext<InferContract<H>>;
11
19
  };
12
20
  };
13
- declare class HubController<T extends SignalRContract, H extends keyof T & HubString> implements ReactiveController {
21
+ declare function createRuntime<T extends SignalRContract>(hubs: Array<keyof T & HubString>, resolve: (hub: keyof T & HubString) => ResolvedHubConfig, options: SignalRSessionOptions<keyof T & HubString>): {
22
+ /** Creates a `HubController` for one hub on a Lit host. The hub connects while the host is connected. */
23
+ hub: <H extends keyof T & `/${string}`>(host: ReactiveControllerHost, name: H, controllerOptions?: {
24
+ /** Set to `false` to not request a host update on each status change. The default is `true`. */
25
+ reactiveStatus?: boolean;
26
+ }) => HubController<T, H>;
27
+ /** Changes session options, for example a new `baseUrl` or `enabled`. Values set before the first host connects apply when it connects. It restarts a stopped session. An `undefined` `accessTokenFactory` keeps the old one. */
28
+ update: (partial: SignalRSessionUpdate) => void;
29
+ /** Stops every hub and releases the connections. The session stays stopped until the next `update()`. */
30
+ stop: () => void;
31
+ /** Escape hatch to the SignalR context (`getConnection`, `getStatus`, and `waitForConnection`). Use this only for the underlying `HubConnection` or a point read. */
32
+ context: import("@dammers/use-signalr-core").SignalRPublicContext<T>;
33
+ };
34
+ export type LitSignalRSession<T extends SignalRContract> = ReturnType<typeof createRuntime<T>>;
35
+ export declare class HubController<T extends SignalRContract, H extends keyof T & HubString> implements ReactiveController {
14
36
  private readonly host;
37
+ /** Name of the hub this controller uses. */
15
38
  readonly hub: H;
16
39
  private readonly context;
17
40
  private readonly start;
@@ -19,20 +42,30 @@ declare class HubController<T extends SignalRContract, H extends keyof T & HubSt
19
42
  private connected;
20
43
  private unsubscribeStatus?;
21
44
  private readonly reconnectEntries;
22
- private readonly activeInvokes;
23
- private readonly listeners;
24
- constructor(host: ReactiveControllerHost, hub: H, context: SignalRContextValue<T>, start: () => void, reactiveStatus: boolean);
45
+ private readonly abortScope;
46
+ private readonly eventEntries;
47
+ constructor(host: ReactiveControllerHost,
48
+ /** Name of the hub this controller uses. */
49
+ hub: H, context: SignalRContextValue<T>, start: () => void, reactiveStatus: boolean);
50
+ /** Live connection status of the hub. Requests a host update on each change unless `reactiveStatus` is `false`. */
25
51
  get status(): HubConnectionStatus;
52
+ /** Lit calls this when the host connects. It acquires the hub, and does nothing during a server render. */
26
53
  hostConnected(): void;
54
+ /** Lit calls this when the host disconnects. Pending calls abort at the end of the task, unless the host connects again first. */
27
55
  hostDisconnected(): void;
56
+ /** Disconnects the controller and removes it from the host. */
57
+ dispose(): void;
58
+ /** Subscribes to a typed server event while the host is connected. Handler args are inferred from your contract. Returns an unsubscribe function. */
28
59
  on<E extends EventName<T, H>>(event: E, handler: (...args: EventArgs<T, H, E>) => void): () => void;
60
+ /** Runs a callback after each reconnect, not the first connect, to refetch state that went stale while offline. */
29
61
  onReconnected(callback: () => void): () => void;
62
+ /** Typed invoker that waits for the connection and resolves with the method's return value. Fails fast by default. Opt in to retry for idempotent methods only. */
30
63
  invoke<M extends MethodName<T, 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>>;
64
+ /** Typed fire-and-forget sender. It does not wait for the connection. It resolves `true` when it sends the call, and `false` when the hub is not connected and it drops the call. It never throws, so a cleanup can call it. For a call that must land in a cleanup, use `teardown`. */
31
65
  send<M extends MethodName<T, H>>(method: M): (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<boolean>;
66
+ /** Typed teardown sender for a method invoked in a cleanup. Survives host disconnect, queues while the hub is still connecting, and holds a lazy hub open until the flush completes. Never throws. */
32
67
  teardown<M extends MethodName<T, H>>(method: M, options?: TeardownOptions): (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<boolean>;
33
- private attachAll;
34
- private attach;
35
- private detachAll;
36
- private detach;
68
+ private subscribeEntry;
69
+ private unsubscribeEntry;
37
70
  }
38
71
  export {};
@@ -1,45 +1,69 @@
1
- import { createInvoker, createSender, createSignalRSession, createTeardownSender, hubKeys, resolveHubConfig, } from "@dammers/use-signalr-core";
1
+ import { createAbortScope, createInvoker, createSender, createSignalRSession, createTeardownSender, hubKeys, resolveHubConfig, } from "@dammers/use-signalr-core";
2
+ import { isServer } from "lit";
2
3
  import { createStatusStore } from "./status-store.js";
4
+ /** Creates a typed SignalR client. Call `createSession` once to get a session for your app. */
3
5
  export function createSignalRClient(config) {
4
6
  const hubs = hubKeys(config);
5
- const resolved = new Map(hubs.map((hub) => [hub, resolveHubConfig(config, config.hubs[hub])]));
7
+ const resolved = new Map(hubs.map((hub) => [hub, resolveHubConfig(config, hub)]));
6
8
  return {
9
+ /** Builds a session that starts, retries, and reconnects every configured hub. It starts when the first host connects. Pass `baseUrl` and `accessTokenFactory`, and gate them with `enabled`. */
7
10
  createSession(options) {
8
11
  return createRuntime(hubs, (hub) => resolved.get(hub), options);
9
12
  },
10
13
  };
11
14
  }
12
15
  function createRuntime(hubs, resolve, options) {
16
+ let values = { ...options };
17
+ let stopped = false;
18
+ let hasHost = false;
13
19
  const statusStore = createStatusStore();
14
20
  const session = createSignalRSession({
15
21
  hubs,
16
22
  resolve,
17
23
  statusStore,
18
- getAccessToken: () => options.accessTokenFactory(),
24
+ getAccessToken: () => values.accessTokenFactory(),
19
25
  onStatusChange: (hub, status) => options.onStatusChange?.(hub, status),
20
- onError: (hub, error) => options.onError?.(hub, error),
26
+ onError: (hub, error, info) => options.onError?.(hub, error, info),
21
27
  });
22
- let started = false;
23
- const ensureStarted = () => {
24
- if (started || options.enabled === false || !options.baseUrl)
28
+ const sync = () => {
29
+ if (stopped)
25
30
  return;
26
- started = true;
27
- session.start(options.baseUrl);
31
+ session.update({
32
+ baseUrl: values.baseUrl,
33
+ enabled: values.enabled,
34
+ connectionKey: values.connectionKey,
35
+ });
28
36
  };
29
37
  function hub(host, name, controllerOptions) {
30
- return new HubController(host, name, session.context, ensureStarted, controllerOptions?.reactiveStatus ?? false);
38
+ return new HubController(host, name, session.context, () => {
39
+ hasHost = true;
40
+ sync();
41
+ }, controllerOptions?.reactiveStatus ?? true);
31
42
  }
32
43
  return {
44
+ /** Creates a `HubController` for one hub on a Lit host. The hub connects while the host is connected. */
33
45
  hub,
46
+ /** Changes session options, for example a new `baseUrl` or `enabled`. Values set before the first host connects apply when it connects. It restarts a stopped session. An `undefined` `accessTokenFactory` keeps the old one. */
47
+ update: (partial) => {
48
+ const { accessTokenFactory, ...rest } = partial;
49
+ values = { ...values, ...rest, ...(accessTokenFactory && { accessTokenFactory }) };
50
+ stopped = false;
51
+ if (hasHost)
52
+ sync();
53
+ },
54
+ /** Stops every hub and releases the connections. The session stays stopped until the next `update()`. */
34
55
  stop: () => {
35
- started = false;
56
+ stopped = true;
36
57
  session.stop();
37
58
  },
38
- context: session.context,
59
+ /** Escape hatch to the SignalR context (`getConnection`, `getStatus`, and `waitForConnection`). Use this only for the underlying `HubConnection` or a point read. */
60
+ context: session.publicContext,
39
61
  };
40
62
  }
41
- class HubController {
42
- constructor(host, hub, context, start, reactiveStatus) {
63
+ export class HubController {
64
+ constructor(host,
65
+ /** Name of the hub this controller uses. */
66
+ hub, context, start, reactiveStatus) {
43
67
  this.host = host;
44
68
  this.hub = hub;
45
69
  this.context = context;
@@ -47,105 +71,112 @@ class HubController {
47
71
  this.reactiveStatus = reactiveStatus;
48
72
  this.connected = false;
49
73
  this.reconnectEntries = new Set();
50
- this.activeInvokes = new Set();
51
- this.listeners = new Map();
74
+ this.abortScope = createAbortScope();
75
+ this.eventEntries = new Set();
52
76
  host.addController(this);
53
77
  }
78
+ /** Live connection status of the hub. Requests a host update on each change unless `reactiveStatus` is `false`. */
54
79
  get status() {
55
80
  return this.context.statusStore.get(this.hub);
56
81
  }
82
+ /** Lit calls this when the host connects. It acquires the hub, and does nothing during a server render. */
57
83
  hostConnected() {
84
+ if (isServer || this.connected)
85
+ return;
58
86
  this.connected = true;
59
87
  this.start();
60
88
  this.context.acquire(this.hub);
61
- this.unsubscribeStatus = this.context.statusStore.subscribe(this.hub, () => {
62
- if (this.status === "connected")
63
- this.attachAll();
64
- else if (this.status !== "reconnected")
65
- this.detachAll();
66
- if (this.reactiveStatus)
67
- this.host.requestUpdate();
68
- });
89
+ if (this.reactiveStatus) {
90
+ this.unsubscribeStatus = this.context.statusStore.subscribe(this.hub, () => this.host.requestUpdate());
91
+ this.host.requestUpdate();
92
+ }
93
+ this.eventEntries.forEach((entry) => this.subscribeEntry(entry));
69
94
  this.reconnectEntries.forEach((entry) => {
70
- entry.unsubscribe = this.context.registerReconnect(this.hub, entry.callback);
95
+ entry.unsubscribe = this.context.registerReconnect(this.hub, entry.run);
71
96
  });
72
- if (this.status === "connected")
73
- this.attachAll();
74
- if (this.reactiveStatus)
75
- this.host.requestUpdate();
76
97
  }
98
+ /** Lit calls this when the host disconnects. Pending calls abort at the end of the task, unless the host connects again first. */
77
99
  hostDisconnected() {
100
+ if (!this.connected)
101
+ return;
78
102
  this.connected = false;
79
103
  this.unsubscribeStatus?.();
80
104
  this.unsubscribeStatus = undefined;
105
+ this.eventEntries.forEach((entry) => this.unsubscribeEntry(entry));
81
106
  this.reconnectEntries.forEach((entry) => {
82
107
  entry.unsubscribe?.();
83
108
  entry.unsubscribe = undefined;
84
109
  });
85
- this.activeInvokes.forEach((controller) => controller.abort());
86
- this.activeInvokes.clear();
87
- this.detachAll();
110
+ queueMicrotask(() => {
111
+ if (!this.connected)
112
+ this.abortScope.abort();
113
+ });
88
114
  this.context.release(this.hub);
89
115
  }
116
+ /** Disconnects the controller and removes it from the host. */
117
+ dispose() {
118
+ this.hostDisconnected();
119
+ this.host.removeController(this);
120
+ }
121
+ /** Subscribes to a typed server event while the host is connected. Handler args are inferred from your contract. Returns an unsubscribe function. */
90
122
  on(event, handler) {
91
123
  const entry = {
92
- handler: handler,
124
+ event: String(event),
125
+ handle: (...args) => handler(...args),
93
126
  };
94
- let entries = this.listeners.get(String(event));
95
- if (!entries)
96
- this.listeners.set(String(event), (entries = new Set()));
97
- entries.add(entry);
98
- this.attach(event, entry);
127
+ this.eventEntries.add(entry);
128
+ if (this.connected)
129
+ this.subscribeEntry(entry);
99
130
  return () => {
100
- this.detach(event, entry);
101
- entries.delete(entry);
102
- if (entries.size === 0)
103
- this.listeners.delete(String(event));
131
+ this.unsubscribeEntry(entry);
132
+ this.eventEntries.delete(entry);
104
133
  };
105
134
  }
135
+ /** Runs a callback after each reconnect, not the first connect, to refetch state that went stale while offline. */
106
136
  onReconnected(callback) {
107
- const entry = { callback };
137
+ const entry = { run: () => callback() };
108
138
  this.reconnectEntries.add(entry);
109
139
  if (this.connected) {
110
- entry.unsubscribe = this.context.registerReconnect(this.hub, callback);
140
+ entry.unsubscribe = this.context.registerReconnect(this.hub, entry.run);
111
141
  }
112
142
  return () => {
113
143
  entry.unsubscribe?.();
114
144
  this.reconnectEntries.delete(entry);
115
145
  };
116
146
  }
147
+ /** Typed invoker that waits for the connection and resolves with the method's return value. Fails fast by default. Opt in to retry for idempotent methods only. */
117
148
  invoke(method, options) {
118
- return createInvoker(this.context, this.hub, method, () => options, (controller) => {
119
- if (!options?.keepAliveOnUnmount)
120
- this.activeInvokes.add(controller);
121
- }, (controller) => this.activeInvokes.delete(controller));
149
+ return createInvoker({
150
+ target: this.context,
151
+ hub: this.hub,
152
+ method,
153
+ getOptions: () => options,
154
+ getSignal: () => (options?.keepAliveOnUnmount ? undefined : this.abortScope.signal()),
155
+ });
122
156
  }
157
+ /** Typed fire-and-forget sender. It does not wait for the connection. It resolves `true` when it sends the call, and `false` when the hub is not connected and it drops the call. It never throws, so a cleanup can call it. For a call that must land in a cleanup, use `teardown`. */
123
158
  send(method) {
124
- return createSender(this.context.getConnection, this.hub, method);
159
+ return createSender({
160
+ getConnection: this.context.getConnection,
161
+ hub: this.hub,
162
+ method,
163
+ });
125
164
  }
165
+ /** Typed teardown sender for a method invoked in a cleanup. Survives host disconnect, queues while the hub is still connecting, and holds a lazy hub open until the flush completes. Never throws. */
126
166
  teardown(method, options) {
127
- return createTeardownSender(this.context, this.hub, method, () => options);
128
- }
129
- attachAll() {
130
- this.listeners.forEach((entries, event) => entries.forEach((entry) => this.attach(event, entry)));
131
- }
132
- attach(event, entry) {
133
- this.detach(event, entry);
134
- if (!this.connected || this.status !== "connected")
135
- return;
136
- const connection = this.context.getConnection(this.hub);
137
- if (!connection)
138
- return;
139
- entry.listener = (...args) => entry.handler(...args);
140
- connection.on(event, entry.listener);
167
+ return createTeardownSender({
168
+ target: this.context,
169
+ hub: this.hub,
170
+ method,
171
+ getOptions: () => options,
172
+ });
141
173
  }
142
- detachAll() {
143
- this.listeners.forEach((entries, event) => entries.forEach((entry) => this.detach(event, entry)));
174
+ subscribeEntry(entry) {
175
+ this.unsubscribeEntry(entry);
176
+ entry.unsubscribe = this.context.subscribe(this.hub, entry.event, entry.handle);
144
177
  }
145
- detach(event, entry) {
146
- if (!entry.listener)
147
- return;
148
- this.context.getConnection(this.hub)?.off(event, entry.listener);
149
- entry.listener = undefined;
178
+ unsubscribeEntry(entry) {
179
+ entry.unsubscribe?.();
180
+ entry.unsubscribe = undefined;
150
181
  }
151
182
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { createSignalRClient } from "./create-signalr-client.js";
2
- export { InvokeError, event, method } from "@dammers/use-signalr-core";
3
- export type { SignalRContextValue, SignalRSessionOptions } from "./types.js";
4
- export type { EventArgs, EventDef, EventName, HubConnectionStatus, HubContract, HubDef, HubString, InferContract, InvokeOptions, MethodArgs, MethodDef, MethodName, MethodReturn, PerHubConfig, ReconnectConfig, ResolvedHubConfig, SignalRClientConfig, SignalRContract, TeardownOptions, } from "@dammers/use-signalr-core";
2
+ export type { HubController, LitSignalRSession } from "./create-signalr-client.js";
3
+ export { event, method } from "@dammers/use-signalr-core";
4
+ export type { SignalRSessionOptions, SignalRSessionUpdate, } from "./types.js";
5
+ export type { EventArgs, EventDef, EventName, HubConnectionStatus, SignalRErrorInfo, SignalRPublicContext, HubContract, HubDef, HubString, InferContract, InvokeOptions, MethodArgs, MethodDef, MethodName, MethodReturn, PerHubConfig, HubProtocolConfig, ConfigureBuilder, BuilderContext, HttpOptions, ReconnectConfig, SignalRClientConfig, SignalRContract, TeardownOptions, } from "@dammers/use-signalr-core";
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  export { createSignalRClient } from "./create-signalr-client.js";
2
- export { InvokeError, event, method } from "@dammers/use-signalr-core";
2
+ export { event, method } from "@dammers/use-signalr-core";
@@ -2,9 +2,9 @@ export function createStatusStore() {
2
2
  const values = new Map();
3
3
  const listeners = new Map();
4
4
  return {
5
- get: (hub) => values.get(hub) ?? "disconnected",
5
+ get: (hub) => values.get(hub) ?? "idle",
6
6
  set: (hub, status) => {
7
- if (values.get(hub) === status)
7
+ if ((values.get(hub) ?? "idle") === status)
8
8
  return;
9
9
  values.set(hub, status);
10
10
  listeners.get(hub)?.forEach((listener) => listener());
package/dist/types.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import type { HubConnectionStatus, HubString, SignalRContract, SignalRContextValueBase } from "@dammers/use-signalr-core";
1
+ import type { HubConnectionStatus, SignalRErrorInfo, HubString, SignalRContract, SignalRContextValueBase, SignalRProviderPropsBase } from "@dammers/use-signalr-core";
2
2
  import type { StatusStore } from "./status-store.js";
3
- export interface SignalRSessionOptions<H extends HubString = HubString> {
4
- baseUrl: string | undefined;
5
- accessTokenFactory: () => string | Promise<string>;
6
- enabled?: boolean;
3
+ export interface SignalRSessionOptions<H extends HubString = HubString> extends SignalRProviderPropsBase<H> {
4
+ /** Runs when the status of a hub changes. The session reads it once when it is created, so `update()` does not change it. */
7
5
  onStatusChange?: (hub: H, status: HubConnectionStatus) => void;
8
- onError?: (hub: H, error: unknown) => void;
6
+ /** Runs on a connection error and on an error that your callback throws. `info.source` is `"connection"` or `"callback"`. The session reads it once when it is created, so `update()` does not change it. */
7
+ onError?: (hub: H, error: unknown, info: SignalRErrorInfo) => void;
9
8
  }
9
+ export type SignalRSessionUpdate = Partial<Pick<SignalRSessionOptions, "baseUrl" | "enabled" | "connectionKey" | "accessTokenFactory">>;
10
10
  export type SignalRContextValue<T extends SignalRContract> = SignalRContextValueBase<T, StatusStore<keyof T & HubString>>;
package/package.json CHANGED
@@ -1,58 +1,60 @@
1
- {
2
- "name": "@dammers/use-signalr-lit",
3
- "version": "0.4.0",
4
- "description": "Fully-typed SignalR Reactive Controllers for Lit.",
5
- "author": "Dammers",
6
- "license": "MIT",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/DammersCode/use-signalr.git",
10
- "directory": "packages/lit"
11
- },
12
- "homepage": "https://github.com/DammersCode/use-signalr/tree/main/packages/lit#readme",
13
- "bugs": {
14
- "url": "https://github.com/DammersCode/use-signalr/issues"
15
- },
16
- "keywords": [
17
- "signalr",
18
- "typescript",
19
- "lit",
20
- "web-components"
21
- ],
22
- "engines": {
23
- "node": ">=18"
24
- },
25
- "type": "module",
26
- "sideEffects": false,
27
- "main": "./dist/index.js",
28
- "types": "./dist/index.d.ts",
29
- "exports": {
30
- ".": {
31
- "types": "./dist/index.d.ts",
32
- "import": "./dist/index.js"
33
- }
34
- },
35
- "files": [
36
- "dist"
37
- ],
38
- "publishConfig": {
39
- "access": "public"
40
- },
41
- "scripts": {
42
- "prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
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
- "lit": ">=3"
53
- },
54
- "devDependencies": {
55
- "@microsoft/signalr": ">=8",
56
- "lit": "^3.3.1"
57
- }
58
- }
1
+ {
2
+ "name": "@dammers/use-signalr-lit",
3
+ "version": "1.0.0",
4
+ "description": "Fully-typed SignalR Reactive Controllers for Lit.",
5
+ "author": "Dammers",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/DammersCode/use-signalr.git",
10
+ "directory": "packages/lit"
11
+ },
12
+ "homepage": "https://use-signalr.vercel.app/docs/lit",
13
+ "bugs": {
14
+ "url": "https://github.com/DammersCode/use-signalr/issues"
15
+ },
16
+ "keywords": [
17
+ "signalr",
18
+ "typescript",
19
+ "lit",
20
+ "web-components"
21
+ ],
22
+ "engines": {
23
+ "node": ">=20.19"
24
+ },
25
+ "type": "module",
26
+ "sideEffects": false,
27
+ "main": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js",
33
+ "default": "./dist/index.js"
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "files": [
38
+ "dist"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "scripts": {
44
+ "prebuild": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
45
+ "build": "tsc -p tsconfig.build.json",
46
+ "typecheck": "tsc --noEmit",
47
+ "test": "vitest run"
48
+ },
49
+ "dependencies": {
50
+ "@dammers/use-signalr-core": "1.0.0"
51
+ },
52
+ "peerDependencies": {
53
+ "@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0",
54
+ "lit": "^3.0.0"
55
+ },
56
+ "devDependencies": {
57
+ "@microsoft/signalr": "^8.0.0 || ^9.0.0 || ^10.0.0",
58
+ "lit": "^3.0.0"
59
+ }
60
+ }