@streamotter/client 0.1.0-rc.1

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 Orca Solutions
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,121 @@
1
+ # @streamotter/client
2
+
3
+ The StreamOtter browser SDK. Subscribe to a **state channel** served by a [StreamOtter gateway](https://www.npmjs.com/package/@streamotter/gateway): each subscription gets an authoritative snapshot, then full-state updates in revision order. It also reports whether the view is verifiably current (`live`) or not (`stale`), so a screen is never silently wrong.
4
+
5
+ > **Release candidate.** `0.1.0-rc.1` is published under the `next` tag. Package versions follow SemVer independently of the V1 protocol (`protocolVersion: 1`).
6
+
7
+ ```bash
8
+ npm install @streamotter/client@next
9
+ ```
10
+
11
+ Transport: Socket.IO 4.8.3 over WebSocket only. Targets current evergreen browsers. ESM only, with TypeScript declarations included.
12
+
13
+ ## Subscribe
14
+
15
+ Generate your channel types from the project configuration (`streamotter generate`, from [`@streamotter/cli`](https://www.npmjs.com/package/@streamotter/cli)), then:
16
+
17
+ ```ts
18
+ import { createClient } from "@streamotter/client";
19
+ import { channelVersions, type AppChannels } from "./generated/streamotter.generated.js";
20
+
21
+ const client = createClient<AppChannels>({
22
+ origin: "https://app.example.com", // default: the page's origin
23
+ // path: "/streamotter/socket.io", // default
24
+ getToken: ({ signal }) => session.getAccessToken(signal) // your application's session token
25
+ });
26
+
27
+ const job = client.subscribe("jobProgress", {
28
+ channelVersion: channelVersions.jobProgress,
29
+ params: { jobId: "job_1" }
30
+ });
31
+ job.on("data", event => render(event.data)); // full state; replace, don't merge
32
+ job.on("state", ({ state }) => showDeliveryState(state));
33
+ job.on("error", error => console.warn(`[${error.code}] ${error.message}`));
34
+ await job.ready({ timeoutMs: 30_000 }); // resolves at the next `live`
35
+ ```
36
+
37
+ `subscribe()` returns immediately and starts in the next microtask, so listeners attached synchronously never miss the snapshot. Data events are not replayed to listeners added later. Each `data` event carries `kind` (`"snapshot"` or `"update"`), `revision` (a decimal string), `data`, and `receivedAt`.
38
+
39
+ The gateway decides who may see what. `getToken` supplies your application's own session token, which the gateway's `authenticate` handler verifies. The browser never chooses its tenant.
40
+
41
+ ## Render the delivery state
42
+
43
+ | State | Meaning | What to show |
44
+ | --- | --- | --- |
45
+ | `authorizing`, `synchronizing` | Checking access, loading the snapshot | A loading state. Keep any previous data visibly provisional. |
46
+ | `live` | Synchronized with the gateway while its source is healthy | The data as current. |
47
+ | `stale` | Connection loss, source outage, overflow, or a snapshot timeout. The SDK is recovering automatically. | The last data, marked as possibly out of date. |
48
+ | `resync-required` | Automatic recovery used its attempts (three per incident) | A retry action that calls `job.resync()`. |
49
+ | `failed` | Terminal: access denied (`FORBIDDEN`), a handler failed, or the data was invalid | The error. To try again, create a new subscription. |
50
+ | `closed` | Unsubscribed, or the client was closed | Nothing. |
51
+
52
+ `live` means synchronized up to the gateway's drain boundary. It is not a wall-clock freshness guarantee. Treat every other state as "may be stale".
53
+
54
+ The client has its own connection state (`client.state`, `client.on("state", …)`): `idle`, `connecting`, `connected`, `reconnecting`, `auth-required`, `closed`. Network failures reconnect automatically with full-jitter backoff (500 ms up to 30 s) while subscriptions are active, and every active subscription gets a fresh snapshot. `auth-required` means the token was rejected or expired, or `getToken` failed or timed out (10 s). Refresh the user's session, then call `client.reconnect()`. If the signed-in account changes, the old subscriptions close with `UNAUTHENTICATED` instead of showing the previous user's data.
55
+
56
+ ## Handle errors
57
+
58
+ Every failure is a `StreamError`: `{ code, message, retryable, requestId, details? }`. Promises (`ready`, `resync`, `reconnect`) reject with it, and `error` listeners receive it. `isStreamError(value)` narrows unknown values.
59
+
60
+ - `FORBIDDEN`: this user may not see this channel instance. Unknown channels also return `FORBIDDEN`, so nothing leaks. Don't retry.
61
+ - `UNAUTHENTICATED`: the session is invalid or expired. Re-authenticate, then `client.reconnect()`.
62
+ - `RESYNC_REQUIRED`, `TIMEOUT`, `SOURCE_UNAVAILABLE`, `OVERLOADED`: may work later. Offer a retry, but don't loop.
63
+ - `INVALID_PARAMS`: the parameters don't match the channel's schema.
64
+ - `CLIENT_CLOSED`: the client was closed.
65
+
66
+ A listener that throws, or returns a rejected promise, fails its subscription with `HANDLER_FAILED`. Keep listeners cheap: state replacement, not heavy processing.
67
+
68
+ ## Clean up
69
+
70
+ ```ts
71
+ await job.unsubscribe(); // idempotent; resolves after the gateway confirms (at most 5 s)
72
+ await client.close(); // closes every subscription and the connection, permanently
73
+ ```
74
+
75
+ Unsubscribe when a view unmounts. Close a shared client only when its owning application scope ends.
76
+
77
+ ## React hook pattern
78
+
79
+ Create one client per signed-in session and one subscription per mounted component:
80
+
81
+ ```tsx
82
+ import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
83
+ import { createClient, type Client, type StreamError, type SubscriptionState } from "@streamotter/client";
84
+ import { channelVersions, type AppChannels, type JobProgress } from "./generated/streamotter.generated.js";
85
+
86
+ const ClientContext = createContext<Client<AppChannels> | null>(null);
87
+
88
+ export function StreamOtterProvider({ getToken, children }: { getToken: () => Promise<string>; children: ReactNode }) {
89
+ const client = useMemo(() => createClient<AppChannels>({ getToken }), [getToken]);
90
+ useEffect(() => () => { void client.close(); }, [client]);
91
+ return <ClientContext.Provider value={client}>{children}</ClientContext.Provider>;
92
+ }
93
+
94
+ export function useJobProgress(jobId: string) {
95
+ const client = useContext(ClientContext);
96
+ const [data, setData] = useState<JobProgress | null>(null);
97
+ const [state, setState] = useState<SubscriptionState>("idle");
98
+ const [error, setError] = useState<StreamError | null>(null);
99
+ useEffect(() => {
100
+ if (client === null) return;
101
+ setData(null);
102
+ setError(null);
103
+ const job = client.subscribe("jobProgress", { channelVersion: channelVersions.jobProgress, params: { jobId } });
104
+ const offData = job.on("data", event => setData(event.data));
105
+ const offState = job.on("state", change => setState(change.state));
106
+ const offError = job.on("error", setError);
107
+ return () => { offData(); offState(); offError(); void job.unsubscribe(); };
108
+ }, [client, jobId]);
109
+ return { data, state, error, live: state === "live" };
110
+ }
111
+ ```
112
+
113
+ Pass a stable `getToken` (for example from `useCallback`) so the client is not recreated on every render. The [reference application](https://github.com/jfricano/StreamOtter/tree/main/examples/order-dashboard) has vanilla TypeScript and React versions of this pattern, including denied access and reconnection.
114
+
115
+ ## More
116
+
117
+ - [V1 API specification](https://github.com/jfricano/StreamOtter/blob/main/docs/V1_API.md): SDK (§4), states and synchronization (§5), errors (§9)
118
+ - [Implementation status](https://github.com/jfricano/StreamOtter/blob/main/docs/IMPLEMENTATION_STATUS.md): what is verified, and the known limitations (for example, automated browser checks cover Chromium only)
119
+ - [Repository](https://github.com/jfricano/StreamOtter) · [Issues](https://github.com/jfricano/StreamOtter/issues)
120
+
121
+ MIT License © 2026 Orca Solutions
@@ -0,0 +1,34 @@
1
+ import { type ChannelMap, type Client, type ClientOptions, type ConnectionState, type StateChange, type StreamError, type Subscription, type Unlisten, type WaitOptions } from "@streamotter/contracts";
2
+ import { Connection } from "./connection.ts";
3
+ import { type ManagedSubscription, type SubscriptionOwner } from "./subscription.ts";
4
+ /**
5
+ * Browser SDK client. Owns one Socket.IO connection at a time, reconnects with
6
+ * full-jitter backoff while subscriptions are active, suspends on authentication
7
+ * rejection until reconnect(), refreshes before token expiry, and closes prior
8
+ * subscriptions when the authenticated identity changes.
9
+ */
10
+ export declare class StreamClient<C extends ChannelMap> implements Client<C>, SubscriptionOwner {
11
+ #private;
12
+ constructor(options: ClientOptions);
13
+ get state(): ConnectionState;
14
+ get closed(): boolean;
15
+ get authRequired(): boolean;
16
+ get connection(): Connection | null;
17
+ register(subscription: ManagedSubscription): void;
18
+ unregister(subscription: ManagedSubscription): void;
19
+ controlTimedOut(connection: Connection): void;
20
+ randomId(): string;
21
+ logListenerFailure(error: unknown): void;
22
+ subscribe<K extends keyof C & string>(channel: K, options: {
23
+ channelVersion: C[K]["version"];
24
+ params: C[K]["params"];
25
+ }): Subscription<C[K]["data"]>;
26
+ on(event: "state", listener: (state: StateChange<ConnectionState>) => void): Unlisten;
27
+ on(event: "error", listener: (error: StreamError) => void): Unlisten;
28
+ /** Obtains a new token, replaces the connection, and recreates active subscriptions with fresh snapshots. */
29
+ reconnect(options?: WaitOptions): Promise<void>;
30
+ close(): Promise<void>;
31
+ }
32
+ /** Creates an idle client; it connects when the first subscription starts. */
33
+ export declare function createClient<C extends ChannelMap>(options: ClientOptions): Client<C>;
34
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,UAAU,EAAE,KAAK,MAAM,EAAE,KAAK,aAAa,EAAE,KAAK,eAAe,EACzD,KAAK,WAAW,EAAE,KAAK,WAAW,EAAE,KAAK,YAAY,EAAE,KAAK,QAAQ,EAAE,KAAK,WAAW,EACpG,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAsB,KAAK,mBAAmB,EAAE,KAAK,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAuBzG;;;;;GAKG;AACH,qBAAa,YAAY,CAAC,CAAC,SAAS,UAAU,CAAE,YAAW,MAAM,CAAC,CAAC,CAAC,EAAE,iBAAiB;;gBAsBzE,OAAO,EAAE,aAAa;IAUlC,IAAI,KAAK,IAAI,eAAe,CAE3B;IAID,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED,IAAI,YAAY,IAAI,OAAO,CAE1B;IAED,IAAI,UAAU,IAAI,UAAU,GAAG,IAAI,CAElC;IAED,QAAQ,CAAC,YAAY,EAAE,mBAAmB,GAAG,IAAI;IAYjD,UAAU,CAAC,YAAY,EAAE,mBAAmB,GAAG,IAAI;IAInD,eAAe,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI;IAM7C,QAAQ,IAAI,MAAM;IAIlB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;IAMxC,SAAS,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,EAAE;QAAE,cAAc,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAA;KAAE,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;IAanJ,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,WAAW,CAAC,eAAe,CAAC,KAAK,IAAI,GAAG,QAAQ;IACrF,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,GAAG,QAAQ;IAUpE,6GAA6G;IAC7G,SAAS,CAAC,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAmB/C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAgSvB;AAED,8EAA8E;AAC9E,wBAAgB,YAAY,CAAC,CAAC,SAAS,UAAU,EAAE,OAAO,EAAE,aAAa,GAAG,MAAM,CAAC,CAAC,CAAC,CAEpF"}
package/dist/client.js ADDED
@@ -0,0 +1,462 @@
1
+ import { asStreamOtterError, DEFAULT_READY_TIMEOUT_MS, DEFAULT_SOCKET_PATH, GET_TOKEN_TIMEOUT_MS, parseUtcTimestamp, RECONNECT_BASE_MS, RECONNECT_CAP_MS, streamError, StreamOtterError, TOKEN_REFRESH_LEAD_MS } from "@streamotter/contracts";
2
+ import { Connection } from "./connection.js";
3
+ import { ClientSubscription } from "./subscription.js";
4
+ function resolveOrigin(origin) {
5
+ const candidate = origin ?? globalThis.location?.origin;
6
+ if (typeof candidate !== "string") {
7
+ throw new StreamOtterError("INVALID_REQUEST", { message: "origin is required outside a browser page." });
8
+ }
9
+ let url;
10
+ try {
11
+ url = new URL(candidate);
12
+ }
13
+ catch {
14
+ throw new StreamOtterError("INVALID_REQUEST", { message: "origin must be an absolute http(s) origin." });
15
+ }
16
+ if ((url.protocol !== "http:" && url.protocol !== "https:") || url.origin !== candidate.replace(/\/$/, "")) {
17
+ throw new StreamOtterError("INVALID_REQUEST", { message: "origin must be an absolute http(s) origin without a path." });
18
+ }
19
+ return url.origin;
20
+ }
21
+ function randomId() {
22
+ return globalThis.crypto.randomUUID();
23
+ }
24
+ /**
25
+ * Browser SDK client. Owns one Socket.IO connection at a time, reconnects with
26
+ * full-jitter backoff while subscriptions are active, suspends on authentication
27
+ * rejection until reconnect(), refreshes before token expiry, and closes prior
28
+ * subscriptions when the authenticated identity changes.
29
+ */
30
+ export class StreamClient {
31
+ #origin;
32
+ #path;
33
+ #getToken;
34
+ #stateListeners = new Set();
35
+ #errorListeners = new Set();
36
+ #subscriptions = new Set();
37
+ #state = "idle";
38
+ #connection = null;
39
+ #identityKey = null;
40
+ #generation = 0;
41
+ #connecting = false;
42
+ #suspended = false;
43
+ #closed = false;
44
+ #everConnected = false;
45
+ #attempt = 0;
46
+ #lastConnectionError = null;
47
+ #reconnectTimer = null;
48
+ #refreshTimer = null;
49
+ #tokenAbort = null;
50
+ #closing = null;
51
+ constructor(options) {
52
+ if (typeof options !== "object" || options === null || typeof options.getToken !== "function") {
53
+ throw new StreamOtterError("INVALID_REQUEST", { message: "createClient requires a getToken function." });
54
+ }
55
+ this.#origin = resolveOrigin(options.origin);
56
+ this.#path = options.path ?? DEFAULT_SOCKET_PATH;
57
+ if (!this.#path.startsWith("/"))
58
+ throw new StreamOtterError("INVALID_REQUEST", { message: "path must start with /." });
59
+ this.#getToken = options.getToken;
60
+ }
61
+ get state() {
62
+ return this.#state;
63
+ }
64
+ // --- SubscriptionOwner ---------------------------------------------------------------
65
+ get closed() {
66
+ return this.#closed;
67
+ }
68
+ get authRequired() {
69
+ return this.#suspended;
70
+ }
71
+ get connection() {
72
+ return this.#connection !== null && this.#connection.connected ? this.#connection : null;
73
+ }
74
+ register(subscription) {
75
+ if (this.#closed)
76
+ return;
77
+ this.#subscriptions.add(subscription);
78
+ if (this.#suspended) {
79
+ subscription.authRequired(this.#lastConnectionError ?? streamError("UNAUTHENTICATED"));
80
+ return;
81
+ }
82
+ const connection = this.connection;
83
+ if (connection !== null)
84
+ subscription.attach(connection);
85
+ else
86
+ this.#ensureConnection();
87
+ }
88
+ unregister(subscription) {
89
+ this.#subscriptions.delete(subscription);
90
+ }
91
+ controlTimedOut(connection) {
92
+ if (connection !== this.#connection)
93
+ return;
94
+ // After an ambiguous control request, rebuild on a new connection instead of retrying on this one.
95
+ connection.close();
96
+ }
97
+ randomId() {
98
+ return randomId();
99
+ }
100
+ logListenerFailure(error) {
101
+ console.error("[streamotter] listener failed", error);
102
+ }
103
+ // --- public API ------------------------------------------------------------------------
104
+ subscribe(channel, options) {
105
+ if (this.#closed)
106
+ throw new StreamOtterError("CLIENT_CLOSED");
107
+ if (typeof channel !== "string" || typeof options !== "object" || options === null
108
+ || typeof options.channelVersion !== "number" || typeof options.params !== "object" || options.params === null) {
109
+ throw new StreamOtterError("INVALID_REQUEST", { message: "subscribe requires a channel name, channelVersion, and params." });
110
+ }
111
+ const unsupported = Object.keys(options).find(key => key !== "channelVersion" && key !== "params");
112
+ if (unsupported !== undefined) {
113
+ throw new StreamOtterError("UNSUPPORTED_CAPABILITY", { message: `"${unsupported}" is not supported by this SDK version.` });
114
+ }
115
+ return new ClientSubscription(this, channel, options.channelVersion, { ...options.params });
116
+ }
117
+ on(event, listener) {
118
+ const set = (event === "state" ? this.#stateListeners : event === "error" ? this.#errorListeners : undefined);
119
+ if (set === undefined || typeof listener !== "function") {
120
+ throw new StreamOtterError("INVALID_REQUEST", { message: "on() accepts \"state\" or \"error\" with a function." });
121
+ }
122
+ set.add(listener);
123
+ return () => { set.delete(listener); };
124
+ }
125
+ /** Obtains a new token, replaces the connection, and recreates active subscriptions with fresh snapshots. */
126
+ reconnect(options) {
127
+ if (this.#closed)
128
+ return Promise.reject(new StreamOtterError("CLIENT_CLOSED"));
129
+ this.#suspended = false;
130
+ this.#lastConnectionError = null;
131
+ this.#attempt = 0;
132
+ this.#clearReconnectTimer();
133
+ const previous = this.#connection;
134
+ this.#connection = null;
135
+ this.#connecting = false;
136
+ this.#generation++;
137
+ if (previous !== null) {
138
+ previous.close();
139
+ for (const subscription of this.#subscriptions)
140
+ subscription.detach();
141
+ }
142
+ const wait = this.#waitForConnection(options);
143
+ void this.#connect(true);
144
+ return wait;
145
+ }
146
+ close() {
147
+ if (this.#closing !== null)
148
+ return this.#closing;
149
+ this.#closed = true;
150
+ this.#generation++;
151
+ this.#clearReconnectTimer();
152
+ this.#clearRefreshTimer();
153
+ this.#tokenAbort?.abort();
154
+ const error = streamError("CLIENT_CLOSED");
155
+ for (const subscription of [...this.#subscriptions])
156
+ subscription.terminateLocally("closed", error, false);
157
+ this.#subscriptions.clear();
158
+ this.#connection?.close();
159
+ this.#connection = null;
160
+ this.#setState("closed");
161
+ this.#stateListeners.clear();
162
+ this.#errorListeners.clear();
163
+ this.#closing = Promise.resolve();
164
+ return this.#closing;
165
+ }
166
+ // --- connection management -------------------------------------------------------------
167
+ #ensureConnection() {
168
+ if (this.#closed || this.#suspended || this.#connecting || this.#reconnectTimer !== null)
169
+ return;
170
+ if (this.#connection !== null)
171
+ return;
172
+ void this.#connect(false);
173
+ }
174
+ async #connect(explicit) {
175
+ if (this.#closed)
176
+ return;
177
+ const generation = ++this.#generation;
178
+ this.#connecting = true;
179
+ this.#setState(this.#everConnected && !explicit ? "reconnecting" : "connecting");
180
+ let opened;
181
+ try {
182
+ opened = await this.#open();
183
+ }
184
+ catch (error) {
185
+ if (generation !== this.#generation)
186
+ return;
187
+ this.#connecting = false;
188
+ this.#handleConnectFailure(error);
189
+ return;
190
+ }
191
+ if (generation !== this.#generation) {
192
+ opened.connection.close();
193
+ return;
194
+ }
195
+ this.#connecting = false;
196
+ this.#adopt(opened.connection, opened.hello);
197
+ }
198
+ /** getToken (ten-second deadline) then a new authenticated connection. */
199
+ async #open() {
200
+ const controller = new AbortController();
201
+ this.#tokenAbort = controller;
202
+ let token;
203
+ let timer;
204
+ try {
205
+ token = await Promise.race([
206
+ Promise.resolve().then(() => this.#getToken({ signal: controller.signal })),
207
+ new Promise((_resolve, reject) => {
208
+ timer = setTimeout(() => {
209
+ controller.abort();
210
+ reject(streamError("UNAUTHENTICATED", { message: "getToken did not resolve within ten seconds.", retryable: true }));
211
+ }, GET_TOKEN_TIMEOUT_MS);
212
+ })
213
+ ]);
214
+ }
215
+ catch (error) {
216
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "UNAUTHENTICATED")
217
+ throw error;
218
+ throw streamError("UNAUTHENTICATED", { message: "getToken failed; call reconnect() once the application session is available.", retryable: true });
219
+ }
220
+ finally {
221
+ clearTimeout(timer);
222
+ if (this.#tokenAbort === controller)
223
+ this.#tokenAbort = null;
224
+ }
225
+ if (typeof token !== "string" || token.length === 0) {
226
+ throw streamError("UNAUTHENTICATED", { message: "getToken must resolve to a non-empty string.", retryable: false });
227
+ }
228
+ let connection = null;
229
+ const events = {
230
+ state: (frame) => this.#route(connection, frame.subscriptionId, sub => sub.handleState(connection, frame)),
231
+ data: (frame) => this.#route(connection, frame.subscriptionId, sub => sub.handleData(connection, frame)),
232
+ error: (frame) => this.#handleErrorFrame(connection, frame),
233
+ disconnect: () => this.#handleDisconnect(connection)
234
+ };
235
+ connection = new Connection({ origin: this.#origin, path: this.#path, token, events });
236
+ const hello = await connection.ready;
237
+ return { connection, hello };
238
+ }
239
+ #adopt(connection, hello) {
240
+ if (this.#closed) {
241
+ connection.close();
242
+ return;
243
+ }
244
+ const previous = this.#connection;
245
+ this.#connection = connection;
246
+ if (previous !== null && previous !== connection)
247
+ previous.close();
248
+ if (this.#identityKey !== null && hello.identityKey !== this.#identityKey) {
249
+ // Never carry a previous user's view across an account switch.
250
+ const error = streamError("UNAUTHENTICATED", { message: "The authenticated identity changed; create new subscriptions for the new identity." });
251
+ for (const subscription of [...this.#subscriptions])
252
+ subscription.terminateLocally("closed", error, true);
253
+ this.#subscriptions.clear();
254
+ this.#emitError(error);
255
+ }
256
+ this.#identityKey = hello.identityKey;
257
+ this.#everConnected = true;
258
+ this.#attempt = 0;
259
+ this.#lastConnectionError = null;
260
+ this.#setState("connected");
261
+ this.#scheduleRefresh(hello.authExpiresAt);
262
+ for (const subscription of [...this.#subscriptions])
263
+ subscription.attach(connection);
264
+ }
265
+ #handleConnectFailure(error) {
266
+ this.#lastConnectionError = error;
267
+ this.#emitError(error);
268
+ const suspend = error.code === "UNAUTHENTICATED" || error.code === "FORBIDDEN"
269
+ || error.code === "INVALID_REQUEST" || error.code === "UNSUPPORTED_CAPABILITY";
270
+ if (suspend)
271
+ this.#suspend(error);
272
+ else
273
+ this.#scheduleReconnect();
274
+ }
275
+ #handleDisconnect(connection) {
276
+ if (connection === null || connection !== this.#connection)
277
+ return;
278
+ this.#connection = null;
279
+ this.#clearRefreshTimer();
280
+ const error = this.#lastConnectionError;
281
+ const reason = error?.code;
282
+ for (const subscription of this.#subscriptions)
283
+ subscription.detach(reason);
284
+ if (this.#closed)
285
+ return;
286
+ if (error !== null && error.code === "UNAUTHENTICATED" && !error.retryable) {
287
+ this.#suspend(error);
288
+ return;
289
+ }
290
+ if (error !== null && error.code === "UNAUTHENTICATED")
291
+ this.#attempt = 0; // Expiry: reconnect promptly.
292
+ this.#scheduleReconnect();
293
+ }
294
+ #suspend(error) {
295
+ this.#suspended = true;
296
+ this.#clearReconnectTimer();
297
+ this.#setState("auth-required", error.code);
298
+ for (const subscription of [...this.#subscriptions])
299
+ subscription.authRequired(error);
300
+ }
301
+ #scheduleReconnect() {
302
+ if (this.#closed || this.#suspended)
303
+ return;
304
+ this.#clearReconnectTimer();
305
+ if (this.#subscriptions.size === 0) {
306
+ this.#setState("idle");
307
+ return;
308
+ }
309
+ this.#setState("reconnecting", this.#lastConnectionError?.code);
310
+ const ceiling = Math.min(RECONNECT_CAP_MS, RECONNECT_BASE_MS * 2 ** this.#attempt);
311
+ this.#attempt++;
312
+ const delay = Math.random() * ceiling;
313
+ this.#reconnectTimer = setTimeout(() => {
314
+ this.#reconnectTimer = null;
315
+ if (this.#subscriptions.size === 0) {
316
+ this.#setState("idle");
317
+ return;
318
+ }
319
+ void this.#connect(false);
320
+ }, delay);
321
+ }
322
+ #scheduleRefresh(authExpiresAt) {
323
+ this.#clearRefreshTimer();
324
+ const expiresAt = parseUtcTimestamp(authExpiresAt);
325
+ if (!Number.isFinite(expiresAt))
326
+ return;
327
+ const delay = expiresAt - TOKEN_REFRESH_LEAD_MS - Date.now();
328
+ if (delay <= 0 || delay > 2_147_000_000)
329
+ return;
330
+ this.#refreshTimer = setTimeout(() => {
331
+ this.#refreshTimer = null;
332
+ void this.#refresh(expiresAt);
333
+ }, delay);
334
+ }
335
+ /** Replaces the connection with a freshly authenticated one before the token expires. */
336
+ async #refresh(expiresAt) {
337
+ if (this.#closed || this.#suspended || this.#connection === null)
338
+ return;
339
+ const generation = this.#generation;
340
+ try {
341
+ const opened = await this.#open();
342
+ if (generation !== this.#generation || this.#closed || this.#suspended) {
343
+ opened.connection.close();
344
+ return;
345
+ }
346
+ this.#generation++;
347
+ this.#adopt(opened.connection, opened.hello);
348
+ }
349
+ catch (error) {
350
+ if (generation !== this.#generation)
351
+ return;
352
+ this.#emitError(error);
353
+ if (Date.now() + 5_000 < expiresAt) {
354
+ this.#refreshTimer = setTimeout(() => {
355
+ this.#refreshTimer = null;
356
+ void this.#refresh(expiresAt);
357
+ }, 5_000);
358
+ }
359
+ }
360
+ }
361
+ #waitForConnection(options) {
362
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
363
+ const signal = options?.signal;
364
+ if (signal?.aborted)
365
+ return Promise.reject(new StreamOtterError("CANCELLED"));
366
+ return new Promise((resolve, reject) => {
367
+ const cleanup = () => {
368
+ clearTimeout(timer);
369
+ signal?.removeEventListener("abort", onAbort);
370
+ unlisten();
371
+ };
372
+ const onAbort = () => { cleanup(); reject(new StreamOtterError("CANCELLED")); };
373
+ const timer = setTimeout(() => {
374
+ cleanup();
375
+ reject(new StreamOtterError("TIMEOUT", { message: `The client did not connect within ${timeoutMs} ms.` }));
376
+ }, timeoutMs);
377
+ const unlisten = this.#onInternalState(state => {
378
+ if (state === "connected") {
379
+ cleanup();
380
+ resolve();
381
+ }
382
+ else if (state === "auth-required") {
383
+ cleanup();
384
+ reject(asStreamOtterError(this.#lastConnectionError ?? streamError("UNAUTHENTICATED")));
385
+ }
386
+ else if (state === "closed") {
387
+ cleanup();
388
+ reject(new StreamOtterError("CLIENT_CLOSED"));
389
+ }
390
+ });
391
+ signal?.addEventListener("abort", onAbort, { once: true });
392
+ });
393
+ }
394
+ #internalStateListeners = new Set();
395
+ #onInternalState(listener) {
396
+ this.#internalStateListeners.add(listener);
397
+ return () => { this.#internalStateListeners.delete(listener); };
398
+ }
399
+ #route(connection, subscriptionId, handle) {
400
+ if (connection === null || connection !== this.#connection)
401
+ return;
402
+ for (const subscription of this.#subscriptions) {
403
+ if (subscription.id === subscriptionId) {
404
+ handle(subscription);
405
+ return;
406
+ }
407
+ }
408
+ }
409
+ #handleErrorFrame(connection, frame) {
410
+ if (connection === null || connection !== this.#connection)
411
+ return;
412
+ if (frame.subscriptionId !== undefined) {
413
+ this.#route(connection, frame.subscriptionId, subscription => subscription.handleError(connection, frame.error));
414
+ return;
415
+ }
416
+ this.#lastConnectionError = frame.error;
417
+ this.#emitError(frame.error);
418
+ }
419
+ #setState(state, reason) {
420
+ if (this.#state === state)
421
+ return;
422
+ this.#state = state;
423
+ const change = reason === undefined ? { state } : { state, reason };
424
+ for (const listener of [...this.#internalStateListeners])
425
+ listener(state);
426
+ for (const listener of [...this.#stateListeners]) {
427
+ try {
428
+ listener(change);
429
+ }
430
+ catch (error) {
431
+ this.logListenerFailure(error);
432
+ }
433
+ }
434
+ }
435
+ #emitError(error) {
436
+ for (const listener of [...this.#errorListeners]) {
437
+ try {
438
+ listener(error);
439
+ }
440
+ catch (cause) {
441
+ this.logListenerFailure(cause);
442
+ }
443
+ }
444
+ }
445
+ #clearReconnectTimer() {
446
+ if (this.#reconnectTimer !== null) {
447
+ clearTimeout(this.#reconnectTimer);
448
+ this.#reconnectTimer = null;
449
+ }
450
+ }
451
+ #clearRefreshTimer() {
452
+ if (this.#refreshTimer !== null) {
453
+ clearTimeout(this.#refreshTimer);
454
+ this.#refreshTimer = null;
455
+ }
456
+ }
457
+ }
458
+ /** Creates an idle client; it connects when the first subscription starts. */
459
+ export function createClient(options) {
460
+ return new StreamClient(options);
461
+ }
462
+ //# sourceMappingURL=client.js.map