react-websocket 3.1.0 → 3.3.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/dist/index.d.cts CHANGED
@@ -1,3 +1,5 @@
1
+
2
+ //#region src/types.d.ts
1
3
  /**
2
4
  * Where to connect: a URL, or a function that returns one (sync or async).
3
5
  *
@@ -24,90 +26,111 @@ type UrlSource = string | (() => string | Promise<string>);
24
26
  type Status = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed';
25
27
  /** The client's state as seen by React. A new object is created on every change. */
26
28
  interface Snapshot<In> {
27
- /** Connection state. */
28
- readonly status: Status;
29
- /** Most recent message (after `parse`/`json` and `schema`), kept across reconnects. */
30
- readonly lastMessage: In | undefined;
31
- /** Consecutive failed attempts since the last successful open. `0` while open. */
32
- readonly attempt: number;
29
+ /** Connection state. */
30
+ readonly status: Status;
31
+ /** Most recent message (after `parse`/`json` and `schema`), kept across reconnects. */
32
+ readonly lastMessage: In | undefined;
33
+ /** Consecutive failed attempts since the last successful open. `0` while open. */
34
+ readonly attempt: number;
33
35
  }
34
36
  /** Details of a closed connection, from the browser's `CloseEvent`. */
35
37
  interface CloseInfo {
36
- /** Close code: `1000` is a normal close, `1006` an abnormal one (e.g. network loss), `4000`–`4999` are yours. */
37
- readonly code: number;
38
- /** Close reason sent by the side that closed the connection. Often empty. */
39
- readonly reason: string;
40
- /** Whether the closing handshake completed. */
41
- readonly wasClean: boolean;
38
+ /** Close code: `1000` is a normal close, `1006` an abnormal one (e.g. network loss), `4000`–`4999` are yours. */
39
+ readonly code: number;
40
+ /** Close reason sent by the side that closed the connection. Often empty. */
41
+ readonly reason: string;
42
+ /** Whether the closing handshake completed. */
43
+ readonly wasClean: boolean;
42
44
  }
43
45
  /** Anything `WebSocket.prototype.send` accepts: a string, `Blob`, `ArrayBuffer` or typed array. */
44
46
  type SendData = Parameters<WebSocket['send']>[0];
45
47
  /** Reconnect timing. Delay before attempt `n` = `min(maxDelay, minDelay * factor ** (n - 1))`, minus jitter. */
46
48
  interface ReconnectOptions {
47
- /**
48
- * Maximum consecutive reconnect attempts. When the last one fails too, the client
49
- * gives up: the status becomes `closed` and `ready` rejects. `0` never retries.
50
- * @default Infinity
51
- */
52
- maxAttempts?: number;
53
- /**
54
- * Delay before the first retry, in ms.
55
- * @default 1000
56
- */
57
- minDelay?: number;
58
- /**
59
- * Upper bound for the delay, in ms.
60
- * @default 30000
61
- */
62
- maxDelay?: number;
63
- /**
64
- * Backoff multiplier applied per attempt.
65
- * @default 2
66
- */
67
- factor?: number;
68
- /**
69
- * Randomly shave up to this fraction (0–1) off each delay, so that many clients
70
- * dropped at once don't all reconnect at the same moment.
71
- * @default 0.5
72
- */
73
- jitter?: number;
74
- /**
75
- * Called on every unexpected close. Return `false` to stop reconnecting.
76
- *
77
- * @example
78
- * ```ts
79
- * // Don't retry when the server rejects our credentials.
80
- * shouldReconnect: close => close.code !== 4001
81
- * ```
82
- * @default () => true
83
- */
84
- shouldReconnect?: (close: CloseInfo) => boolean;
49
+ /**
50
+ * Maximum consecutive reconnect attempts. When the last one fails too, the client
51
+ * gives up: the status becomes `closed` and `ready` rejects. `0` never retries.
52
+ * @default Infinity
53
+ */
54
+ maxAttempts?: number;
55
+ /**
56
+ * Delay before the first retry, in ms.
57
+ * @default 1000
58
+ */
59
+ minDelay?: number;
60
+ /**
61
+ * Upper bound for the delay, in ms.
62
+ * @default 30000
63
+ */
64
+ maxDelay?: number;
65
+ /**
66
+ * Backoff multiplier applied per attempt.
67
+ * @default 2
68
+ */
69
+ factor?: number;
70
+ /**
71
+ * Randomly shave up to this fraction (0–1) off each delay, so that many clients
72
+ * dropped at once don't all reconnect at the same moment.
73
+ * @default 0.5
74
+ */
75
+ jitter?: number;
76
+ /**
77
+ * Called on every unexpected close. Return `false` to stop reconnecting.
78
+ *
79
+ * @example
80
+ * ```ts
81
+ * // Don't retry when the server rejects our credentials.
82
+ * shouldReconnect: close => close.code !== 4001
83
+ * ```
84
+ * @default () => true
85
+ */
86
+ shouldReconnect?: (close: CloseInfo) => boolean;
85
87
  }
86
88
  /** Application-level keep-alive. Useful behind proxies that drop idle connections. */
87
89
  interface HeartbeatOptions {
88
- /** Send `message` every `interval` ms while open. */
89
- interval: number;
90
- /**
91
- * Sent as-is (it is not passed through `serialize` or `json`).
92
- * @default 'ping'
93
- */
94
- message?: string;
95
- /** Incoming data equal to this string is swallowed instead of being delivered as a message. */
96
- pong?: string;
97
- /**
98
- * If nothing at all arrives within this many ms after a ping, the connection is
99
- * treated as dead: it closes with code `4000` and reconnects.
100
- */
101
- timeout?: number;
90
+ /** Send `message` every `interval` ms while open. */
91
+ interval: number;
92
+ /**
93
+ * Sent as-is (it is not passed through `serialize` or `json`).
94
+ * @default 'ping'
95
+ */
96
+ message?: string;
97
+ /** Incoming data equal to this string is swallowed instead of being delivered as a message. */
98
+ pong?: string;
99
+ /**
100
+ * If nothing at all arrives within this many ms after a ping, the connection is
101
+ * treated as dead: it closes with code `4000` and reconnects.
102
+ */
103
+ timeout?: number;
104
+ }
105
+ /** Per-message options for `send()`. */
106
+ interface SendOptions {
107
+ /**
108
+ * Drop the message instead of queueing it when the socket isn't open. For data that
109
+ * is stale by the time a reconnect finishes, such as player input or cursor positions.
110
+ * @default false
111
+ */
112
+ volatile?: boolean;
113
+ /**
114
+ * Keep only the newest queued message with this key. Sending again with the same key
115
+ * while disconnected replaces the earlier one, which moves to the back of the queue.
116
+ * For state where only the latest value matters, such as "my position is now (x, y)".
117
+ */
118
+ key?: string;
119
+ /**
120
+ * Called if the message is dropped from the queue without being sent: replaced by a
121
+ * newer message with the same `key`, or evicted by `queue.limit`. Not called when the
122
+ * queue is cleared because the client closed or gave up.
123
+ */
124
+ onDrop?: () => void;
102
125
  }
103
126
  /** Bounds for the send queue. */
104
127
  interface QueueOptions {
105
- /**
106
- * Maximum number of messages held while not connected. When full, the oldest
107
- * message is dropped.
108
- * @default Infinity
109
- */
110
- limit?: number;
128
+ /**
129
+ * Maximum number of messages held while not connected. When full, the oldest
130
+ * message is dropped.
131
+ * @default Infinity
132
+ */
133
+ limit?: number;
111
134
  }
112
135
  /**
113
136
  * The minimal [Standard Schema v1](https://standardschema.dev) interface, implemented
@@ -115,24 +138,24 @@ interface QueueOptions {
115
138
  * import this; pass your schema object directly.
116
139
  */
117
140
  interface StandardSchemaV1<Input = unknown, Output = Input> {
118
- readonly '~standard': {
119
- readonly version: 1;
120
- readonly vendor: string;
121
- readonly validate: (value: unknown) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
122
- readonly types?: {
123
- readonly input: Input;
124
- readonly output: Output;
125
- } | undefined;
126
- };
141
+ readonly '~standard': {
142
+ readonly version: 1;
143
+ readonly vendor: string;
144
+ readonly validate: (value: unknown) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
145
+ readonly types?: {
146
+ readonly input: Input;
147
+ readonly output: Output;
148
+ } | undefined;
149
+ };
127
150
  }
128
151
  /** The result of a Standard Schema `validate` call. */
129
152
  type StandardSchemaResult<Output> = {
130
- readonly value: Output;
131
- readonly issues?: undefined;
153
+ readonly value: Output;
154
+ readonly issues?: undefined;
132
155
  } | {
133
- readonly issues: ReadonlyArray<{
134
- readonly message: string;
135
- }>;
156
+ readonly issues: ReadonlyArray<{
157
+ readonly message: string;
158
+ }>;
136
159
  };
137
160
  /**
138
161
  * Connection options, shared by `createWebSocket(url, options)` and `useWebSocket(url, options)`.
@@ -141,66 +164,66 @@ type StandardSchemaResult<Output> = {
141
164
  * @typeParam Out - Type accepted by `send()`.
142
165
  */
143
166
  interface WebSocketOptions<In = unknown, Out = unknown> {
144
- /** Sub-protocol(s) passed to the `WebSocket` constructor. */
145
- protocols?: string | string[];
146
- /**
147
- * How binary messages are exposed.
148
- * @default 'blob'
149
- */
150
- binaryType?: BinaryType;
151
- /**
152
- * `JSON.parse` incoming and `JSON.stringify` outgoing messages. Messages that fail
153
- * to parse are reported to `onError` as a {@link MessageError} and not delivered.
154
- * @default false
155
- */
156
- json?: boolean;
157
- /**
158
- * Custom decoder for incoming `event.data`. Takes precedence over `json`.
159
- * Throwing reports a {@link MessageError} and drops the message.
160
- */
161
- parse?: (data: unknown) => unknown;
162
- /** Custom encoder for outgoing messages. Takes precedence over `json`. */
163
- serialize?: (message: Out) => SendData;
164
- /**
165
- * Validate incoming messages (after parsing) with any Standard Schema library.
166
- * Invalid messages are reported to `onError` as a {@link MessageError} and not delivered.
167
- * The message type `In` is inferred from it.
168
- *
169
- * @example
170
- * ```ts
171
- * createWebSocket(url, { json: true, schema: z.object({ price: z.number() }) });
172
- * ```
173
- */
174
- schema?: StandardSchemaV1<unknown, In>;
175
- /**
176
- * Reconnect with exponential backoff after an unexpected close. `false` disables it.
177
- * @default true
178
- */
179
- reconnect?: boolean | ReconnectOptions;
180
- /** Send a ping on an interval and, optionally, reconnect when the server goes quiet. */
181
- heartbeat?: HeartbeatOptions;
182
- /**
183
- * Buffer `send()` calls made while not connected and send them, in order, on open
184
- * (right after `open` listeners run).
185
- * `false` drops them instead. `{ limit }` caps the buffer, dropping the oldest.
186
- * The queue is cleared by `close()` or when the client gives up.
187
- * @default true
188
- */
189
- queue?: boolean | QueueOptions;
190
- /**
191
- * Receives debug messages about connection attempts, retries and dropped messages.
192
- * @example
193
- * ```ts
194
- * logger: console.debug
195
- * ```
196
- */
197
- logger?: (message: string, ...details: unknown[]) => void;
198
- /**
199
- * `WebSocket` implementation to use, e.g. a mock in tests or the `ws` package in Node.
200
- * When omitted, the global `WebSocket` is used in browsers. During a server render
201
- * (no `window`), nothing connects unless an implementation is passed.
202
- */
203
- WebSocket?: typeof WebSocket;
167
+ /** Sub-protocol(s) passed to the `WebSocket` constructor. */
168
+ protocols?: string | string[];
169
+ /**
170
+ * How binary messages are exposed.
171
+ * @default 'blob'
172
+ */
173
+ binaryType?: BinaryType;
174
+ /**
175
+ * `JSON.parse` incoming and `JSON.stringify` outgoing messages. Messages that fail
176
+ * to parse are reported to `onError` as a {@link MessageError} and not delivered.
177
+ * @default false
178
+ */
179
+ json?: boolean;
180
+ /**
181
+ * Custom decoder for incoming `event.data`. Takes precedence over `json`.
182
+ * Throwing reports a {@link MessageError} and drops the message.
183
+ */
184
+ parse?: (data: unknown) => unknown;
185
+ /** Custom encoder for outgoing messages. Takes precedence over `json`. */
186
+ serialize?: (message: Out) => SendData;
187
+ /**
188
+ * Validate incoming messages (after parsing) with any Standard Schema library.
189
+ * Invalid messages are reported to `onError` as a {@link MessageError} and not delivered.
190
+ * The message type `In` is inferred from it.
191
+ *
192
+ * @example
193
+ * ```ts
194
+ * createWebSocket(url, { json: true, schema: z.object({ price: z.number() }) });
195
+ * ```
196
+ */
197
+ schema?: StandardSchemaV1<unknown, In>;
198
+ /**
199
+ * Reconnect with exponential backoff after an unexpected close. `false` disables it.
200
+ * @default true
201
+ */
202
+ reconnect?: boolean | ReconnectOptions;
203
+ /** Send a ping on an interval and, optionally, reconnect when the server goes quiet. */
204
+ heartbeat?: HeartbeatOptions;
205
+ /**
206
+ * Buffer `send()` calls made while not connected and send them, in order, on open
207
+ * (right after `open` listeners run).
208
+ * `false` drops them instead. `{ limit }` caps the buffer, dropping the oldest.
209
+ * The queue is cleared by `close()` or when the client gives up.
210
+ * @default true
211
+ */
212
+ queue?: boolean | QueueOptions;
213
+ /**
214
+ * Receives debug messages about connection attempts, retries and dropped messages.
215
+ * @example
216
+ * ```ts
217
+ * logger: console.debug
218
+ * ```
219
+ */
220
+ logger?: (message: string, ...details: unknown[]) => void;
221
+ /**
222
+ * `WebSocket` implementation to use, e.g. a mock in tests or the `ws` package in Node.
223
+ * When omitted, the global `WebSocket` is used in browsers. During a server render
224
+ * (no `window`), nothing connects unless an implementation is passed.
225
+ */
226
+ WebSocket?: typeof WebSocket;
204
227
  }
205
228
  /**
206
229
  * Reported via the `error` event (and `onError`) when an incoming message can't be
@@ -213,36 +236,36 @@ interface WebSocketOptions<In = unknown, Out = unknown> {
213
236
  * }
214
237
  * ```
215
238
  */
216
- declare class MessageError extends Error {
217
- /** The raw `event.data` that failed. */
218
- readonly data: unknown;
219
- /** Schema validation issues, when the message failed `schema`. */
220
- readonly issues: ReadonlyArray<{
221
- readonly message: string;
222
- }> | undefined;
223
- constructor(message: string, data: unknown, options?: {
224
- cause?: unknown;
225
- issues?: ReadonlyArray<{
226
- readonly message: string;
227
- }>;
228
- });
239
+ export declare class MessageError extends Error {
240
+ /** The raw `event.data` that failed. */
241
+ readonly data: unknown;
242
+ /** Schema validation issues, when the message failed `schema`. */
243
+ readonly issues: ReadonlyArray<{
244
+ readonly message: string;
245
+ }> | undefined;
246
+ constructor(message: string, data: unknown, options?: {
247
+ cause?: unknown;
248
+ issues?: ReadonlyArray<{
249
+ readonly message: string;
250
+ }>;
251
+ });
229
252
  }
230
253
  /** Events emitted by a client. Subscribe with `client.on(type, listener)` or `useWebSocketEvent`. */
231
254
  interface EventMap<In> {
232
- /**
233
- * The socket opened (initially or after a reconnect). Listeners run before queued
234
- * messages are sent, so a handshake sent from here goes out first.
235
- */
236
- open: (event: Event) => void;
237
- /** A message arrived and passed `parse` and `schema`. */
238
- message: (message: In, event: MessageEvent) => void;
239
- /** A socket closed, whether it will be retried or not. */
240
- close: (close: CloseInfo) => void;
241
- /**
242
- * A socket error `Event`, a {@link MessageError} for an undecodable or invalid message,
243
- * or the `Error` thrown by the `WebSocket` constructor or a `url` function.
244
- */
245
- error: (error: Event | MessageError | Error) => void;
255
+ /**
256
+ * The socket opened (initially or after a reconnect). Listeners run before queued
257
+ * messages are sent, so a handshake sent from here goes out first.
258
+ */
259
+ open: (event: Event) => void;
260
+ /** A message arrived and passed `parse` and `schema`. */
261
+ message: (message: In, event: MessageEvent) => void;
262
+ /** A socket closed, whether it will be retried or not. */
263
+ close: (close: CloseInfo) => void;
264
+ /**
265
+ * A socket error `Event`, a {@link MessageError} for an undecodable or invalid message,
266
+ * or the `Error` thrown by the `WebSocket` constructor or a `url` function.
267
+ */
268
+ error: (error: Event | MessageError | Error) => void;
246
269
  }
247
270
  /**
248
271
  * A WebSocket connection that reconnects, queues, decodes and can be shared.
@@ -256,64 +279,72 @@ interface EventMap<In> {
256
279
  * @typeParam Out - Type accepted by `send()`.
257
280
  */
258
281
  interface WebSocketClient<In = unknown, Out = unknown> {
259
- /** The URL (or URL function) the client was created with. */
260
- readonly url: UrlSource;
261
- /**
262
- * A promise that resolves once the socket has opened. Reading it starts an idle client.
263
- *
264
- * It stays resolved through automatic reconnects, so `use(client.ready)` shows a
265
- * Suspense fallback only for the first connection, never on a network blip; use
266
- * `status` to show reconnects. It rejects when the client gives up reconnecting, when
267
- * `close()` is called, and during a server render. After that, `connect()` or
268
- * `reconnect()` make it a new pending promise.
269
- *
270
- * It is safe to pass to React 19's `use()`: the same promise is returned until its state
271
- * changes, and it carries `status`/`value`/`reason` so `use()` doesn't suspend when it is
272
- * already settled.
273
- */
274
- readonly ready: Promise<void>;
275
- /** The current underlying `WebSocket`, if any. An escape hatch; prefer the client's methods. */
276
- readonly socket: WebSocket | null;
277
- /** Subscribe to snapshot changes. Compatible with `useSyncExternalStore`. Returns an unsubscribe function. */
278
- subscribe(listener: () => void): () => void;
279
- /** The current {@link Snapshot}. Returns the same object until something changes. */
280
- getSnapshot(): Snapshot<In>;
281
- /**
282
- * Listen to an event. Returns an unsubscribe function. Listener errors are re-thrown
283
- * asynchronously, so one failing listener doesn't break the others.
284
- */
285
- on<K extends keyof EventMap<In>>(type: K, listener: EventMap<In>[K]): () => void;
286
- /**
287
- * Send a message (encoded with `serialize`/`json` if configured). If the socket isn't
288
- * open, the message is queued and sent on open (see the `queue` option).
289
- * @returns `true` if it was sent immediately, `false` if it was queued or dropped.
290
- */
291
- send(message: Out): boolean;
292
- /**
293
- * Start connecting, and keep the connection open even when no hook is using the
294
- * client, until `close()` is called. Does nothing if already connecting or open.
295
- */
296
- connect(): void;
297
- /**
298
- * Close the connection and stop reconnecting. The status becomes `closed` and the
299
- * send queue is cleared. Mounted hooks stay mounted; call `connect()` or `reconnect()`
300
- * to start again.
301
- * @param code - Close code. @default 1000
302
- */
303
- close(code?: number, reason?: string): void;
304
- /**
305
- * Drop the current socket (if any) and connect again immediately, resetting the
306
- * backoff. Also restarts a `closed` client.
307
- */
308
- reconnect(): void;
309
- /**
310
- * Hold the connection open until the returned function is called. This is what the
311
- * hooks use; call it yourself to integrate with non-React code.
312
- * @returns A release function (safe to call more than once).
313
- */
314
- acquire(): () => void;
282
+ /** The URL (or URL function) the client was created with. */
283
+ readonly url: UrlSource;
284
+ /**
285
+ * A promise that resolves once the socket has opened. Reading it starts an idle client.
286
+ *
287
+ * It stays resolved through automatic reconnects, so `use(client.ready)` shows a
288
+ * Suspense fallback only for the first connection, never on a network blip; use
289
+ * `status` to show reconnects. It rejects when the client gives up reconnecting, when
290
+ * `close()` is called, and during a server render. After that, `connect()` or
291
+ * `reconnect()` make it a new pending promise.
292
+ *
293
+ * It is safe to pass to React 19's `use()`: the same promise is returned until its state
294
+ * changes, and it carries `status`/`value`/`reason` so `use()` doesn't suspend when it is
295
+ * already settled.
296
+ */
297
+ readonly ready: Promise<void>;
298
+ /** The current underlying `WebSocket`, if any. An escape hatch; prefer the client's methods. */
299
+ readonly socket: WebSocket | null;
300
+ /** Subscribe to snapshot changes. Compatible with `useSyncExternalStore`. Returns an unsubscribe function. */
301
+ subscribe(listener: () => void): () => void;
302
+ /** The current {@link Snapshot}. Returns the same object until something changes. */
303
+ getSnapshot(): Snapshot<In>;
304
+ /**
305
+ * Listen to an event. Returns an unsubscribe function. Listener errors are re-thrown
306
+ * asynchronously, so one failing listener doesn't break the others.
307
+ */
308
+ on<K extends keyof EventMap<In>>(type: K, listener: EventMap<In>[K]): () => void;
309
+ /**
310
+ * Send a message (encoded with `serialize`/`json` if configured). If the socket isn't
311
+ * open, the message is queued and sent on open (see the `queue` option), unless
312
+ * `options.volatile` is set.
313
+ * @returns `true` if it was sent immediately, `false` if it was queued or dropped.
314
+ *
315
+ * @example
316
+ * ```ts
317
+ * game.send({ type: 'input', dx, dy }, { volatile: true }); // never replayed after a reconnect
318
+ * game.send({ type: 'position', x, y }, { key: 'position' }); // only the newest is queued
319
+ * ```
320
+ */
321
+ send(message: Out, options?: SendOptions): boolean;
322
+ /**
323
+ * Start connecting, and keep the connection open even when no hook is using the
324
+ * client, until `close()` is called. Does nothing if already connecting or open.
325
+ */
326
+ connect(): void;
327
+ /**
328
+ * Close the connection and stop reconnecting. The status becomes `closed` and the
329
+ * send queue is cleared. Mounted hooks stay mounted; call `connect()` or `reconnect()`
330
+ * to start again.
331
+ * @param code - Close code. @default 1000
332
+ */
333
+ close(code?: number, reason?: string): void;
334
+ /**
335
+ * Drop the current socket (if any) and connect again immediately, resetting the
336
+ * backoff. Also restarts a `closed` client.
337
+ */
338
+ reconnect(): void;
339
+ /**
340
+ * Hold the connection open until the returned function is called. This is what the
341
+ * hooks use; call it yourself to integrate with non-React code.
342
+ * @returns A release function (safe to call more than once).
343
+ */
344
+ acquire(): () => void;
315
345
  }
316
-
346
+ //#endregion
347
+ //#region src/client.d.ts
317
348
  /**
318
349
  * Create a WebSocket client, usually at module level, to share across components.
319
350
  *
@@ -333,17 +364,302 @@ interface WebSocketClient<In = unknown, Out = unknown> {
333
364
  * export const chat = createWebSocket<ChatIn, ChatOut>('wss://api.example.com/chat', { json: true });
334
365
  * ```
335
366
  */
336
- declare function createWebSocket<In = unknown, Out = unknown>(url: UrlSource, options?: WebSocketOptions<In, Out>): WebSocketClient<In, Out>;
337
-
367
+ export declare function createWebSocket<In = unknown, Out = unknown>(url: UrlSource, options?: WebSocketOptions<In, Out>): WebSocketClient<In, Out>;
368
+ //#endregion
369
+ //#region src/latency.d.ts
370
+ /** Options for {@link createWebSocketLatency}: how pings and pongs look on the wire. */
371
+ interface WebSocketLatencyOptions<In, Out> {
372
+ /** The ping message, tagged with `id`. Sent with `volatile`, so pings are never queued. */
373
+ ping: (id: number) => Out;
374
+ /**
375
+ * Recognize a pong: return the `id` of the ping it answers, and the server's clock
376
+ * (`Date.now()` on the server, in ms) when it replied. Return `undefined` (or `null`)
377
+ * for any other message. Without `time`, only the round-trip time is measured.
378
+ */
379
+ pong: (message: In) => {
380
+ id: number | string;
381
+ time?: number;
382
+ } | null | undefined;
383
+ /**
384
+ * How often to ping while open, in ms. The first ping goes out as soon as the socket opens.
385
+ * @default 2000
386
+ */
387
+ interval?: number;
388
+ /**
389
+ * How many recent measurements to keep. `rtt` is their median, and `offset` comes from
390
+ * the one with the lowest round trip, the most accurate estimate.
391
+ * @default 5
392
+ */
393
+ samples?: number;
394
+ }
395
+ /** Latest latency measurements. A new object is created on every change. */
396
+ interface Latency {
397
+ /** Round-trip time in ms: the median of recent pings. `undefined` until the first pong. */
398
+ readonly rtt: number | undefined;
399
+ /**
400
+ * Estimated server clock minus local clock, in ms. Add it to `Date.now()` for server time.
401
+ * `undefined` until a pong carries `time`.
402
+ */
403
+ readonly offset: number | undefined;
404
+ }
405
+ /** Round-trip time and server clock offset for one client. Create with {@link createWebSocketLatency}. */
406
+ interface WebSocketLatency {
407
+ /** The client being measured. Hooks reading the latency keep it connected. */
408
+ readonly client: WebSocketClient<any, any>;
409
+ /** The current {@link Latency}. Returns the same object until it changes. */
410
+ getSnapshot(): Latency;
411
+ /** Called whenever a measurement changes. Compatible with `useSyncExternalStore`. */
412
+ subscribe(listener: () => void): () => void;
413
+ /** The estimated server time: `Date.now() + offset`, or `Date.now()` before any estimate. */
414
+ serverNow(): number;
415
+ /** Ping now instead of waiting for the next interval. Does nothing unless the socket is open. */
416
+ ping(): void;
417
+ /** Stop pinging and listening. Only needed for instances created dynamically. */
418
+ dispose(): void;
419
+ }
420
+ /**
421
+ * Measure round-trip time and estimate the server's clock, for ping displays, countdowns
422
+ * and timestamps that must agree across players.
423
+ *
424
+ * Pings are sent on an interval while the socket is open, and paused otherwise. Measurements
425
+ * from a previous connection are discarded on reconnect, but the last values stay readable
426
+ * until new ones arrive. It doesn't open the connection by itself.
427
+ *
428
+ * Pongs are ordinary messages: they also reach `onMessage`, `lastMessage` and state stores.
429
+ *
430
+ * @example
431
+ * ```ts
432
+ * export const latency = createWebSocketLatency(game, {
433
+ * ping: id => ({ type: 'ping', id }),
434
+ * pong: message => (message.type === 'pong' ? { id: message.id, time: message.time } : undefined)
435
+ * });
436
+ *
437
+ * // In a component:
438
+ * const { rtt } = useWebSocketLatency(latency);
439
+ *
440
+ * // Anywhere: seconds left in a round that ends at the server's `endsAt`.
441
+ * const left = (endsAt - latency.serverNow()) / 1000;
442
+ * ```
443
+ */
444
+ export declare function createWebSocketLatency<In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketLatencyOptions<NoInfer<In>, NoInfer<Out>>): WebSocketLatency;
445
+ //#endregion
446
+ //#region src/requests.d.ts
447
+ /** Options for {@link createWebSocketRequests}: how requests and replies look on the wire. */
448
+ interface WebSocketRequestsOptions<Req, In, Out> {
449
+ /**
450
+ * Build the outgoing message for `request(message)`, tagged with `id`. Annotate `message`
451
+ * to type what `request()` accepts.
452
+ */
453
+ send: (message: Req, id: number) => Out;
454
+ /**
455
+ * The id an incoming message replies to, or `undefined` (or `null`) if it isn't a reply.
456
+ * A string id matches the number it was sent as, so either echo works.
457
+ */
458
+ reply: (message: In) => number | string | null | undefined;
459
+ /**
460
+ * Called on a reply. Return something other than `undefined` to reject the request with
461
+ * it instead of resolving, e.g. for a server-side error reply.
462
+ */
463
+ error?: (message: In) => unknown;
464
+ /**
465
+ * Default time to wait for a reply, in ms. `Infinity` waits forever.
466
+ * @default 10000
467
+ */
468
+ timeout?: number;
469
+ }
470
+ /** Per-call options for {@link WebSocketRequests.request}. */
471
+ interface RequestOptions extends SendOptions {
472
+ /** Time to wait for a reply, in ms. Overrides the manager's `timeout`. */
473
+ timeout?: number;
474
+ /** Abort the request. It rejects with `signal.reason`. A late reply is ignored. */
475
+ signal?: AbortSignal;
476
+ }
477
+ /** Request/response over one client. Create with {@link createWebSocketRequests}. */
478
+ interface WebSocketRequests<Req, In> {
479
+ /** The client requests are sent on. */
480
+ readonly client: WebSocketClient<any, any>;
481
+ /**
482
+ * Send a request and resolve with its reply. Holds the connection until it settles.
483
+ *
484
+ * Rejects with a `TimeoutError` `DOMException` after `timeout`, with `signal.reason` when
485
+ * aborted, and with an `Error` when the connection it was sent on closes (the reply can
486
+ * no longer arrive) or the client stops. A request made while disconnected is queued like
487
+ * any other message and waits for the connection; it rejects if it is dropped from the
488
+ * queue (replaced by a newer request with the same `key`, or evicted by `queue.limit`).
489
+ */
490
+ request(message: Req, options?: RequestOptions): Promise<In>;
491
+ /** Number of requests waiting for a reply. */
492
+ pending(): number;
493
+ /** Reject every pending request and stop listening. Only needed for managers created dynamically. */
494
+ dispose(): void;
495
+ }
496
+ /**
497
+ * Send requests and await their replies, matched by an id the library generates.
498
+ *
499
+ * Replies are ordinary messages: they also reach `onMessage`, `lastMessage` and state stores.
500
+ *
501
+ * @example
502
+ * ```ts
503
+ * type Request = { type: 'join'; room: string } | { type: 'leave' };
504
+ *
505
+ * export const rpc = createWebSocketRequests(game, {
506
+ * send: (message: Request, id) => ({ ...message, id }),
507
+ * reply: message => (message.type === 'reply' ? message.id : undefined),
508
+ * error: message => (message.type === 'reply' && message.error ? new Error(message.error) : undefined)
509
+ * });
510
+ *
511
+ * const reply = await rpc.request({ type: 'join', room: 'lobby' }, { timeout: 5000 });
512
+ * ```
513
+ */
514
+ export declare function createWebSocketRequests<Req, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketRequestsOptions<Req, NoInfer<In>, NoInfer<Out>>): WebSocketRequests<Req, In>;
515
+ //#endregion
516
+ //#region src/responder.d.ts
517
+ /** What `request` returns for a request: any object with these fields, such as the message itself. */
518
+ type RequestFields = {
519
+ id: number | string;
520
+ method: string;
521
+ params?: unknown;
522
+ timeout?: number;
523
+ };
524
+ /**
525
+ * The type of `params` in `Q`, keeping `undefined` when they're optional and giving `undefined`
526
+ * when there are none. (Inferring `params?: P` directly would drop the `undefined`.)
527
+ */
528
+ type ParamsOf<Q> = Q extends unknown ? 'params' extends keyof Q ? Q['params' & keyof Q] : undefined : never;
529
+ /**
530
+ * Options for {@link createWebSocketResponder}: how the server's requests and your replies look
531
+ * on the wire.
532
+ *
533
+ * @typeParam Q - What `request` returns. Handlers receive its `params`.
534
+ * @typeParam R - What handlers return, from the annotation on `respond`'s `result`.
535
+ */
536
+ interface WebSocketResponderOptions<Q extends RequestFields, R, In, Out> {
537
+ /**
538
+ * Recognize a request from the server: its `id`, the `method` handlers are registered for,
539
+ * and the `params` they receive. Return `undefined` (or `null`) for any other message.
540
+ * A `timeout` (in ms) overrides the manager's for this request.
541
+ *
542
+ * `params` come from the server, so validate them before acting on them.
543
+ */
544
+ request: (message: In) => Q | null | undefined;
545
+ /** Build the reply to request `id`. Annotate `result` to type what handlers return. */
546
+ respond: (id: number | string, result: R) => Out;
547
+ /**
548
+ * Build the error reply to request `id`: what a handler threw, a `NotFoundError` `DOMException`
549
+ * when nothing is registered for the method, a `TimeoutError` after `timeout`, or an
550
+ * `AbortError` from `dispose()`.
551
+ */
552
+ error: (id: number | string, error: unknown) => Out;
553
+ /**
554
+ * The id of a request the server withdrew, or `undefined` (or `null`) if the message isn't a
555
+ * cancellation. The request's `signal` aborts and nothing is sent.
556
+ */
557
+ cancel?: (message: In) => number | string | null | undefined;
558
+ /**
559
+ * Time to answer a request, in ms. When it runs out, the `error` reply (a `TimeoutError`)
560
+ * is sent and the request's `signal` aborts.
561
+ * @default Infinity
562
+ */
563
+ timeout?: number;
564
+ }
565
+ /** A request from the server that hasn't been answered yet. */
566
+ interface IncomingRequest<P = unknown, R = unknown> {
567
+ /** The id the server sent. Replies carry it back. */
568
+ readonly id: number | string;
569
+ /** The method it was sent for. */
570
+ readonly method: string;
571
+ /** The `params` from `request`. They come from the server, so validate them. */
572
+ readonly params: P;
573
+ /**
574
+ * Aborts when the answer is no longer wanted: the server cancelled the request, it timed out,
575
+ * the connection it arrived on closed, the responder was disposed, or it was answered with
576
+ * `respond` or `reject` while its handler was still running.
577
+ */
578
+ readonly signal: AbortSignal;
579
+ /**
580
+ * Reply with `result`. Only the first answer counts.
581
+ * @returns `true` if the reply was sent, `false` if the request was already answered or is gone.
582
+ */
583
+ respond(result: R): boolean;
584
+ /**
585
+ * Reply with an error, built by the `error` option. Only the first answer counts.
586
+ * @returns `true` if the reply was sent, `false` if the request was already answered or is gone.
587
+ */
588
+ reject(error: unknown): boolean;
589
+ }
590
+ /**
591
+ * Answers a request in code. Return (or resolve) the result to reply with it; throw (or reject)
592
+ * to send the `error` reply instead.
593
+ */
594
+ type RequestHandler<P = unknown, R = unknown> = (params: P, request: IncomingRequest<P, R>) => R | PromiseLike<R>;
595
+ /** Answers the server's requests on one client. Create with {@link createWebSocketResponder}. */
596
+ interface WebSocketResponder<P = unknown, R = unknown> {
597
+ /** The client requests arrive on. Hooks reading the responder keep it connected. */
598
+ readonly client: WebSocketClient<any, any>;
599
+ /**
600
+ * Answer requests for `method` until the returned function is called.
601
+ *
602
+ * With a `handler`, requests are answered in code. Without one, they wait in
603
+ * {@link getSnapshot} until something calls `respond` or `reject` on them, e.g. a dialog
604
+ * that asks the user. When several registrations exist for one method, the newest one takes
605
+ * new requests, and unregistering it hands them back to the previous one. Requests for a
606
+ * method with no registration get a `NotFoundError` reply.
607
+ *
608
+ * @returns An unregister function (safe to call more than once). Requests already waiting stay.
609
+ */
610
+ onRequest(method: string, handler?: RequestHandler<P, R>): () => void;
611
+ /**
612
+ * Requests waiting for an answer from outside a handler, oldest first. Returns the same array
613
+ * until it changes.
614
+ */
615
+ getSnapshot(): readonly IncomingRequest<P, R>[];
616
+ /** Called whenever {@link getSnapshot} changes. Compatible with `useSyncExternalStore`. */
617
+ subscribe(listener: () => void): () => void;
618
+ /**
619
+ * Stop answering: send an `AbortError` reply to every request in flight and stop listening.
620
+ * Only needed for responders created dynamically.
621
+ */
622
+ dispose(): void;
623
+ }
624
+ /**
625
+ * Answer requests the server sends: run a handler for tools that only exist in the browser
626
+ * (selection, clipboard, geolocation), or let a person answer, e.g. to approve an agent's action.
627
+ * The reverse of `createWebSocketRequests`.
628
+ *
629
+ * Every request gets exactly one reply while its connection lives: the handler's result, an
630
+ * `error` reply when it throws, has no registration or times out. When the connection a request
631
+ * arrived on closes, the request is dropped and nothing is sent, since the server can't match a
632
+ * reply on a new connection. Replies are never queued.
633
+ *
634
+ * Requests are ordinary messages: they also reach `onMessage`, `lastMessage` and state stores.
635
+ *
636
+ * @example
637
+ * ```ts
638
+ * export const tools = createWebSocketResponder(agent, {
639
+ * request: message => (message.type === 'call' ? message : undefined),
640
+ * respond: (id, result: unknown) => ({ type: 'result', id, result }),
641
+ * error: (id, error) => ({ type: 'result', id, error: String(error) })
642
+ * });
643
+ *
644
+ * tools.onRequest('get_selection', () => window.getSelection()?.toString() ?? '');
645
+ *
646
+ * // In a component: requests a person answers.
647
+ * const approvals = useAgentApproval(tools, 'approve');
648
+ * approvals[0]?.respond({ approved: true });
649
+ * ```
650
+ */
651
+ export declare function createWebSocketResponder<Q extends RequestFields, R, In, const Out>(client: WebSocketClient<In, Out>, options: WebSocketResponderOptions<Q, R, NoInfer<In>, NoInfer<Out>>): WebSocketResponder<ParamsOf<Q>, R>;
652
+ //#endregion
653
+ //#region src/state.d.ts
338
654
  /** Options for {@link createWebSocketState}. */
339
655
  interface WebSocketStateOptions<S, In> {
340
- /** The state before any message arrives, and what `reset()` returns to. */
341
- initialState: S;
342
- /**
343
- * Fold one incoming message into the state. Must be pure: return a new object for a
344
- * change, or the same `state` to ignore the message (subscribers aren't notified).
345
- */
346
- reduce: (state: S, message: In) => S;
656
+ /** The state before any message arrives, and what `reset()` returns to. */
657
+ initialState: S;
658
+ /**
659
+ * Fold one incoming message into the state. Must be pure: return a new object for a
660
+ * change, or the same `state` to ignore the message (subscribers aren't notified).
661
+ */
662
+ reduce: (state: S, message: In) => S;
347
663
  }
348
664
  /**
349
665
  * State derived from a client's messages. Read it with `useWebSocketState(store, selector)`,
@@ -352,20 +668,20 @@ interface WebSocketStateOptions<S, In> {
352
668
  * @typeParam S - The state type. Don't use a function type: `setState` treats functions as updaters.
353
669
  */
354
670
  interface WebSocketState<S> {
355
- /** The client whose messages this store reduces. Hooks reading the store keep it connected. */
356
- readonly client: WebSocketClient<any, any>;
357
- /** The `initialState` it was created with. Used for server rendering and hydration. */
358
- readonly initialState: S;
359
- /** The current state. Returns the same object until it changes. */
360
- getState(): S;
361
- /** Called whenever the state changes. Compatible with `useSyncExternalStore`. */
362
- subscribe(listener: () => void): () => void;
363
- /** Replace the state, or update it from the current one, e.g. for optimistic updates. */
364
- setState(update: S | ((state: S) => S)): void;
365
- /** Go back to `initialState`. */
366
- reset(): void;
367
- /** Stop reducing messages. Only needed for stores created dynamically rather than at module level. */
368
- dispose(): void;
671
+ /** The client whose messages this store reduces. Hooks reading the store keep it connected. */
672
+ readonly client: WebSocketClient<any, any>;
673
+ /** The `initialState` it was created with. Used for server rendering and hydration. */
674
+ readonly initialState: S;
675
+ /** The current state. Returns the same object until it changes. */
676
+ getState(): S;
677
+ /** Called whenever the state changes. Compatible with `useSyncExternalStore`. */
678
+ subscribe(listener: () => void): () => void;
679
+ /** Replace the state, or update it from the current one, e.g. for optimistic updates. */
680
+ setState(update: S | ((state: S) => S)): void;
681
+ /** Go back to `initialState`. */
682
+ reset(): void;
683
+ /** Stop reducing messages. Only needed for stores created dynamically rather than at module level. */
684
+ dispose(): void;
369
685
  }
370
686
  /**
371
687
  * Keep state derived from a client's messages, like a reducer that runs on every message.
@@ -385,28 +701,29 @@ interface WebSocketState<S> {
385
701
  * const acme = useWebSocketState(priceState, state => state.ACME);
386
702
  * ```
387
703
  */
388
- declare function createWebSocketState<S, In>(client: WebSocketClient<In, any>, options: WebSocketStateOptions<S, NoInfer<In>>): WebSocketState<S>;
389
-
704
+ export declare function createWebSocketState<S, In>(client: WebSocketClient<In, any>, options: WebSocketStateOptions<S, NoInfer<In>>): WebSocketState<S>;
705
+ //#endregion
706
+ //#region src/topics.d.ts
390
707
  /** Options for {@link createWebSocketTopics}: the messages your server expects. */
391
708
  interface WebSocketTopicsOptions<Out> {
392
- /** The message that subscribes to `topic`. */
393
- subscribe: (topic: string) => Out;
394
- /** The message that unsubscribes from `topic`. Omit it if your server has none. */
395
- unsubscribe?: (topic: string) => Out;
709
+ /** The message that subscribes to `topic`. */
710
+ subscribe: (topic: string) => Out;
711
+ /** The message that unsubscribes from `topic`. Omit it if your server has none. */
712
+ unsubscribe?: (topic: string) => Out;
396
713
  }
397
714
  /** Reference-counted topic subscriptions on one client. Create with {@link createWebSocketTopics}. */
398
715
  interface WebSocketTopics {
399
- /** The client the subscription messages are sent on. */
400
- readonly client: WebSocketClient<any, any>;
401
- /**
402
- * Hold a subscription to `topic`, and the client's connection, until the returned
403
- * function is called. The release function is safe to call more than once.
404
- */
405
- acquire(topic: string): () => void;
406
- /** The topics currently held, in the order they were first acquired. */
407
- active(): string[];
408
- /** Stop managing subscriptions. Only needed for managers created dynamically. */
409
- dispose(): void;
716
+ /** The client the subscription messages are sent on. */
717
+ readonly client: WebSocketClient<any, any>;
718
+ /**
719
+ * Hold a subscription to `topic`, and the client's connection, until the returned
720
+ * function is called. The release function is safe to call more than once.
721
+ */
722
+ acquire(topic: string): () => void;
723
+ /** The topics currently held, in the order they were first acquired. */
724
+ active(): string[];
725
+ /** Stop managing subscriptions. Only needed for managers created dynamically. */
726
+ dispose(): void;
410
727
  }
411
728
  /**
412
729
  * Manage topic subscriptions that survive reconnects.
@@ -430,41 +747,44 @@ interface WebSocketTopics {
430
747
  * useWebSocketTopic(topics, `prices:${symbol}`);
431
748
  * ```
432
749
  */
433
- declare function createWebSocketTopics<const Out>(client: WebSocketClient<any, Out>, options: WebSocketTopicsOptions<NoInfer<Out>>): WebSocketTopics;
434
-
750
+ export declare function createWebSocketTopics<const Out>(client: WebSocketClient<any, Out>, options: WebSocketTopicsOptions<NoInfer<Out>>): WebSocketTopics;
751
+ //#endregion
752
+ //#region src/react.d.ts
435
753
  /**
436
754
  * Per-component event handlers. They always see the component's latest props and
437
755
  * state, and changing them never reconnects.
438
756
  */
439
757
  interface WebSocketHandlers<In> {
440
- /** The socket opened (initially or after a reconnect). */
441
- onOpen?: (event: Event) => void;
442
- /** A message arrived and passed `parse`/`json` and `schema`. */
443
- onMessage?: (message: In, event: MessageEvent) => void;
444
- /** A socket closed. Called whether or not it will be retried. */
445
- onClose?: (close: CloseInfo) => void;
446
- /** A socket error `Event`, a `MessageError`, or an `Error` from the constructor or `url` function. */
447
- onError?: (error: Event | Error) => void;
448
- /**
449
- * `false` releases this component's hold on the connection and stops its handlers.
450
- * The connection closes once nothing else holds it.
451
- * @default true
452
- */
453
- enabled?: boolean;
758
+ /** The socket opened (initially or after a reconnect). */
759
+ onOpen?: (event: Event) => void;
760
+ /** A message arrived and passed `parse`/`json` and `schema`. */
761
+ onMessage?: (message: In, event: MessageEvent) => void;
762
+ /** A socket closed. Called whether or not it will be retried. */
763
+ onClose?: (close: CloseInfo) => void;
764
+ /** A socket error `Event`, a `MessageError`, or an `Error` from the constructor or `url` function. */
765
+ onError?: (error: Event | Error) => void;
766
+ /**
767
+ * `false` releases this component's hold on the connection and stops its handlers.
768
+ * The connection closes once nothing else holds it.
769
+ * @default true
770
+ */
771
+ enabled?: boolean;
454
772
  }
455
773
  /** Options for `useWebSocket(url, options)`: connection options plus handlers. */
456
- interface UseWebSocketOptions<In, Out> extends WebSocketOptions<In, Out>, WebSocketHandlers<In> {
457
- }
774
+ interface UseWebSocketOptions<In, Out> extends WebSocketOptions<In, Out>, WebSocketHandlers<In> {}
458
775
  /** What `useWebSocket` returns: the current {@link Snapshot} plus stable actions. */
459
776
  interface UseWebSocketResult<In, Out> extends Snapshot<In> {
460
- /** Send now, or queue until open. Returns `true` if sent immediately. Stable identity. */
461
- send: (message: Out) => boolean;
462
- /** Close and stop reconnecting (for every component sharing the connection). Stable identity. */
463
- close: (code?: number, reason?: string) => void;
464
- /** Drop the socket and connect again right away. Stable identity. */
465
- reconnect: () => void;
466
- /** The underlying client, or `null` when the URL is `null`/`undefined`. */
467
- client: WebSocketClient<In, Out> | null;
777
+ /**
778
+ * Send now, or queue until open (see {@link SendOptions} for volatile and keyed sends).
779
+ * Returns `true` if sent immediately. Stable identity.
780
+ */
781
+ send: (message: Out, options?: SendOptions) => boolean;
782
+ /** Close and stop reconnecting (for every component sharing the connection). Stable identity. */
783
+ close: (code?: number, reason?: string) => void;
784
+ /** Drop the socket and connect again right away. Stable identity. */
785
+ reconnect: () => void;
786
+ /** The underlying client, or `null` when the URL is `null`/`undefined`. */
787
+ client: WebSocketClient<In, Out> | null;
468
788
  }
469
789
  /**
470
790
  * Connect to a WebSocket and re-render with its status and latest message.
@@ -489,8 +809,8 @@ interface UseWebSocketResult<In, Out> extends Snapshot<In> {
489
809
  * });
490
810
  * ```
491
811
  */
492
- declare function useWebSocket<In = unknown, Out = unknown>(url: string | null | undefined, options?: UseWebSocketOptions<In, Out>): UseWebSocketResult<In, Out>;
493
- declare function useWebSocket<In, Out>(client: WebSocketClient<In, Out> | null | undefined, options?: WebSocketHandlers<In>): UseWebSocketResult<In, Out>;
812
+ export declare function useWebSocket<In = unknown, Out = unknown>(url: string | null | undefined, options?: UseWebSocketOptions<In, Out>): UseWebSocketResult<In, Out>;
813
+ export declare function useWebSocket<In, Out>(client: WebSocketClient<In, Out> | null | undefined, options?: WebSocketHandlers<In>): UseWebSocketResult<In, Out>;
494
814
  /**
495
815
  * Listen to a client's events without re-rendering the component. The listener always
496
816
  * sees the latest props and state. Keeps the connection open while mounted.
@@ -500,7 +820,7 @@ declare function useWebSocket<In, Out>(client: WebSocketClient<In, Out> | null |
500
820
  * useWebSocketEvent(chat, 'message', message => setMessages(list => [...list, message]));
501
821
  * ```
502
822
  */
503
- declare function useWebSocketEvent<In, K extends keyof EventMap<In>>(client: WebSocketClient<In, any> | null | undefined, type: K, listener: EventMap<In>[K]): void;
823
+ export declare function useWebSocketEvent<In, K extends keyof EventMap<In>>(client: WebSocketClient<In, any> | null | undefined, type: K, listener: EventMap<In>[K]): void;
504
824
  /**
505
825
  * The connection status of a client. Re-renders only when the status changes, not on
506
826
  * messages. Keeps the connection open while mounted.
@@ -510,7 +830,7 @@ declare function useWebSocketEvent<In, K extends keyof EventMap<In>>(client: Web
510
830
  * const status = useWebSocketStatus(chat); // 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed'
511
831
  * ```
512
832
  */
513
- declare function useWebSocketStatus(client: WebSocketClient<any, any> | null | undefined): Status;
833
+ export declare function useWebSocketStatus(client: WebSocketClient<any, any> | null | undefined): Status;
514
834
  /**
515
835
  * Read state built from messages by `createWebSocketState`. Re-renders only when the
516
836
  * selected value changes (by `isEqual`, default `Object.is`), however often messages
@@ -523,8 +843,8 @@ declare function useWebSocketStatus(client: WebSocketClient<any, any> | null | u
523
843
  * const acme = useWebSocketState(priceState, state => state.ACME);
524
844
  * ```
525
845
  */
526
- declare function useWebSocketState<S>(store: WebSocketState<S>): S;
527
- declare function useWebSocketState<S, T>(store: WebSocketState<S>, selector: (state: S) => T, isEqual?: (a: T, b: T) => boolean): T;
846
+ export declare function useWebSocketState<S>(store: WebSocketState<S>): S;
847
+ export declare function useWebSocketState<S, T>(store: WebSocketState<S>, selector: (state: S) => T, isEqual?: (a: T, b: T) => boolean): T;
528
848
  /**
529
849
  * Subscribe to one topic (or several) while mounted, through a `createWebSocketTopics`
530
850
  * manager. Components holding the same topic share one subscription, and it is sent again
@@ -536,6 +856,42 @@ declare function useWebSocketState<S, T>(store: WebSocketState<S>, selector: (st
536
856
  * useWebSocketTopic(topics, watchlist.map(symbol => `prices:${symbol}`));
537
857
  * ```
538
858
  */
539
- declare function useWebSocketTopic(topics: WebSocketTopics | null | undefined, topic: string | readonly string[] | null | undefined): void;
540
-
541
- export { type CloseInfo, type EventMap, type HeartbeatOptions, MessageError, type QueueOptions, type ReconnectOptions, type SendData, type Snapshot, type StandardSchemaV1, type Status, type UrlSource, type UseWebSocketOptions, type UseWebSocketResult, type WebSocketClient, type WebSocketHandlers, type WebSocketOptions, type WebSocketState, type WebSocketStateOptions, type WebSocketTopics, type WebSocketTopicsOptions, createWebSocket, createWebSocketState, createWebSocketTopics, useWebSocket, useWebSocketEvent, useWebSocketState, useWebSocketStatus, useWebSocketTopic };
859
+ export declare function useWebSocketTopic(topics: WebSocketTopics | null | undefined, topic: string | readonly string[] | null | undefined): void;
860
+ /**
861
+ * Read round-trip time and server clock offset from a `createWebSocketLatency` instance.
862
+ * Re-renders when a measurement changes, about once per ping interval. Keeps the connection
863
+ * open while mounted. On the server, and during hydration, both values are `undefined`.
864
+ *
865
+ * @example
866
+ * ```tsx
867
+ * const { rtt } = useWebSocketLatency(latency);
868
+ * return <span>{rtt === undefined ? '–' : `${Math.round(rtt)} ms`}</span>;
869
+ * ```
870
+ */
871
+ export declare function useWebSocketLatency(latency: WebSocketLatency): Latency;
872
+ /**
873
+ * Requests for `method` that a person answers, e.g. an agent asking to run a tool. While mounted,
874
+ * it registers `method` on the responder without a handler, so new requests wait here instead of
875
+ * getting a `NotFoundError` reply. Call `respond` or `reject` on one to answer it. Re-renders
876
+ * when the list changes. Keeps the connection open while mounted. `null` holds nothing.
877
+ *
878
+ * Requests stay listed after unmount until they are answered, time out, are cancelled or lose
879
+ * their connection, so a remounted dialog shows them again. On the server the list is empty.
880
+ *
881
+ * @example
882
+ * ```tsx
883
+ * const [request] = useAgentApproval(tools, 'approve');
884
+ * if (!request) return null;
885
+ * return (
886
+ * <dialog open>
887
+ * {request.params.summary}
888
+ * <button onClick={() => request.respond({ approved: true })}>Approve</button>
889
+ * <button onClick={() => request.respond({ approved: false })}>Deny</button>
890
+ * </dialog>
891
+ * );
892
+ * ```
893
+ */
894
+ export declare function useAgentApproval<P, R>(responder: WebSocketResponder<P, R> | null | undefined, method: string | null | undefined): readonly IncomingRequest<P, R>[];
895
+ //#endregion
896
+ export type { CloseInfo, EventMap, HeartbeatOptions, IncomingRequest, Latency, QueueOptions, ReconnectOptions, RequestHandler, RequestOptions, SendData, SendOptions, Snapshot, StandardSchemaV1, Status, UrlSource, UseWebSocketOptions, UseWebSocketResult, WebSocketClient, WebSocketHandlers, WebSocketLatency, WebSocketLatencyOptions, WebSocketOptions, WebSocketRequests, WebSocketRequestsOptions, WebSocketResponder, WebSocketResponderOptions, WebSocketState, WebSocketStateOptions, WebSocketTopics, WebSocketTopicsOptions };
897
+ //# sourceMappingURL=index.d.cts.map