@dammers/use-signalr-lit 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DammersCode
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,203 @@
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)
@@ -0,0 +1,38 @@
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";
4
+ export declare function createSignalRClient<const H extends Record<HubString, HubDef>>(config: SignalRClientConfig<H>): {
5
+ createSession(options: SignalRSessionOptions<keyof H & `/${string}`>): {
6
+ hub: <H_1 extends keyof H & `/${string}`>(host: ReactiveControllerHost, name: H_1, controllerOptions?: {
7
+ reactiveStatus?: boolean;
8
+ } | undefined) => HubController<InferContract<H>, H_1>;
9
+ stop: () => void;
10
+ context: import("@dammers/use-signalr-core").SignalRContextValueBase<InferContract<H>, import("./status-store.js").StatusStore<keyof H & `/${string}`>>;
11
+ };
12
+ };
13
+ declare class HubController<T extends SignalRContract, H extends keyof T & HubString> implements ReactiveController {
14
+ private readonly host;
15
+ readonly hub: H;
16
+ private readonly context;
17
+ private readonly start;
18
+ private readonly reactiveStatus;
19
+ private connected;
20
+ private unsubscribeStatus?;
21
+ private readonly reconnectEntries;
22
+ private readonly activeInvokes;
23
+ private readonly listeners;
24
+ constructor(host: ReactiveControllerHost, hub: H, context: SignalRContextValue<T>, start: () => void, reactiveStatus: boolean);
25
+ get status(): HubConnectionStatus;
26
+ hostConnected(): void;
27
+ hostDisconnected(): void;
28
+ on<E extends EventName<T, H>>(event: E, handler: (...args: EventArgs<T, H, E>) => void): () => void;
29
+ onReconnected(callback: () => void): () => void;
30
+ 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>>;
31
+ send<M extends MethodName<T, H>>(method: M): (...args: import("@dammers/use-signalr-core").MethodArgs<T, H, M>) => Promise<boolean>;
32
+ 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;
37
+ }
38
+ export {};
@@ -0,0 +1,151 @@
1
+ import { createInvoker, createSender, createSignalRSession, createTeardownSender, hubKeys, resolveHubConfig, } from "@dammers/use-signalr-core";
2
+ import { createStatusStore } from "./status-store.js";
3
+ export function createSignalRClient(config) {
4
+ const hubs = hubKeys(config);
5
+ const resolved = new Map(hubs.map((hub) => [hub, resolveHubConfig(config, config.hubs[hub])]));
6
+ return {
7
+ createSession(options) {
8
+ return createRuntime(hubs, (hub) => resolved.get(hub), options);
9
+ },
10
+ };
11
+ }
12
+ function createRuntime(hubs, resolve, options) {
13
+ const statusStore = createStatusStore();
14
+ const session = createSignalRSession({
15
+ hubs,
16
+ resolve,
17
+ statusStore,
18
+ getAccessToken: () => options.accessTokenFactory(),
19
+ onStatusChange: (hub, status) => options.onStatusChange?.(hub, status),
20
+ onError: (hub, error) => options.onError?.(hub, error),
21
+ });
22
+ let started = false;
23
+ const ensureStarted = () => {
24
+ if (started || options.enabled === false || !options.baseUrl)
25
+ return;
26
+ started = true;
27
+ session.start(options.baseUrl);
28
+ };
29
+ function hub(host, name, controllerOptions) {
30
+ return new HubController(host, name, session.context, ensureStarted, controllerOptions?.reactiveStatus ?? false);
31
+ }
32
+ return {
33
+ hub,
34
+ stop: () => {
35
+ started = false;
36
+ session.stop();
37
+ },
38
+ context: session.context,
39
+ };
40
+ }
41
+ class HubController {
42
+ constructor(host, hub, context, start, reactiveStatus) {
43
+ this.host = host;
44
+ this.hub = hub;
45
+ this.context = context;
46
+ this.start = start;
47
+ this.reactiveStatus = reactiveStatus;
48
+ this.connected = false;
49
+ this.reconnectEntries = new Set();
50
+ this.activeInvokes = new Set();
51
+ this.listeners = new Map();
52
+ host.addController(this);
53
+ }
54
+ get status() {
55
+ return this.context.statusStore.get(this.hub);
56
+ }
57
+ hostConnected() {
58
+ this.connected = true;
59
+ this.start();
60
+ 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
+ });
69
+ this.reconnectEntries.forEach((entry) => {
70
+ entry.unsubscribe = this.context.registerReconnect(this.hub, entry.callback);
71
+ });
72
+ if (this.status === "connected")
73
+ this.attachAll();
74
+ if (this.reactiveStatus)
75
+ this.host.requestUpdate();
76
+ }
77
+ hostDisconnected() {
78
+ this.connected = false;
79
+ this.unsubscribeStatus?.();
80
+ this.unsubscribeStatus = undefined;
81
+ this.reconnectEntries.forEach((entry) => {
82
+ entry.unsubscribe?.();
83
+ entry.unsubscribe = undefined;
84
+ });
85
+ this.activeInvokes.forEach((controller) => controller.abort());
86
+ this.activeInvokes.clear();
87
+ this.detachAll();
88
+ this.context.release(this.hub);
89
+ }
90
+ on(event, handler) {
91
+ const entry = {
92
+ handler: handler,
93
+ };
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);
99
+ return () => {
100
+ this.detach(event, entry);
101
+ entries.delete(entry);
102
+ if (entries.size === 0)
103
+ this.listeners.delete(String(event));
104
+ };
105
+ }
106
+ onReconnected(callback) {
107
+ const entry = { callback };
108
+ this.reconnectEntries.add(entry);
109
+ if (this.connected) {
110
+ entry.unsubscribe = this.context.registerReconnect(this.hub, callback);
111
+ }
112
+ return () => {
113
+ entry.unsubscribe?.();
114
+ this.reconnectEntries.delete(entry);
115
+ };
116
+ }
117
+ 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));
122
+ }
123
+ send(method) {
124
+ return createSender(this.context.getConnection, this.hub, method);
125
+ }
126
+ 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);
141
+ }
142
+ detachAll() {
143
+ this.listeners.forEach((entries, event) => entries.forEach((entry) => this.detach(event, entry)));
144
+ }
145
+ detach(event, entry) {
146
+ if (!entry.listener)
147
+ return;
148
+ this.context.getConnection(this.hub)?.off(event, entry.listener);
149
+ entry.listener = undefined;
150
+ }
151
+ }
@@ -0,0 +1,4 @@
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";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { createSignalRClient } from "./create-signalr-client.js";
2
+ export { InvokeError, event, method } from "@dammers/use-signalr-core";
@@ -0,0 +1,5 @@
1
+ import type { StatusStore as StatusStoreBase } from "@dammers/use-signalr-core";
2
+ export interface StatusStore<H extends string> extends StatusStoreBase<H> {
3
+ subscribe: (hub: H, listener: () => void) => () => void;
4
+ }
5
+ export declare function createStatusStore<H extends string>(): StatusStore<H>;
@@ -0,0 +1,20 @@
1
+ export function createStatusStore() {
2
+ const values = new Map();
3
+ const listeners = new Map();
4
+ return {
5
+ get: (hub) => values.get(hub) ?? "disconnected",
6
+ set: (hub, status) => {
7
+ if (values.get(hub) === status)
8
+ return;
9
+ values.set(hub, status);
10
+ listeners.get(hub)?.forEach((listener) => listener());
11
+ },
12
+ subscribe: (hub, listener) => {
13
+ let set = listeners.get(hub);
14
+ if (!set)
15
+ listeners.set(hub, (set = new Set()));
16
+ set.add(listener);
17
+ return () => set.delete(listener);
18
+ },
19
+ };
20
+ }
@@ -0,0 +1,10 @@
1
+ import type { HubConnectionStatus, HubString, SignalRContract, SignalRContextValueBase } from "@dammers/use-signalr-core";
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;
7
+ onStatusChange?: (hub: H, status: HubConnectionStatus) => void;
8
+ onError?: (hub: H, error: unknown) => void;
9
+ }
10
+ export type SignalRContextValue<T extends SignalRContract> = SignalRContextValueBase<T, StatusStore<keyof T & HubString>>;
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,58 @@
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
+ }