react-websocket 2.1.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js ADDED
@@ -0,0 +1,469 @@
1
+ // src/types.ts
2
+ var MessageError = class extends Error {
3
+ /** The raw `event.data` that failed. */
4
+ data;
5
+ /** Schema validation issues, when the message failed `schema`. */
6
+ issues;
7
+ constructor(message, data, options) {
8
+ super(message, options?.cause === void 0 ? void 0 : { cause: options.cause });
9
+ this.name = "MessageError";
10
+ this.data = data;
11
+ this.issues = options?.issues;
12
+ }
13
+ };
14
+
15
+ // src/client.ts
16
+ var OPEN = 1;
17
+ var RECONNECT_DEFAULTS = {
18
+ maxAttempts: Infinity,
19
+ minDelay: 1e3,
20
+ maxDelay: 3e4,
21
+ factor: 2,
22
+ jitter: 0.5
23
+ };
24
+ function createDeferred() {
25
+ let resolve;
26
+ let reject;
27
+ const promise = new Promise((res, rej) => {
28
+ resolve = res;
29
+ reject = rej;
30
+ });
31
+ promise.status = "pending";
32
+ promise.catch(() => {
33
+ });
34
+ const deferred = {
35
+ promise,
36
+ settled: false,
37
+ resolve() {
38
+ if (deferred.settled) return;
39
+ deferred.settled = true;
40
+ promise.status = "fulfilled";
41
+ promise.value = void 0;
42
+ resolve();
43
+ },
44
+ reject(reason) {
45
+ if (deferred.settled) return;
46
+ deferred.settled = true;
47
+ promise.status = "rejected";
48
+ promise.reason = reason;
49
+ reject(reason);
50
+ }
51
+ };
52
+ return deferred;
53
+ }
54
+ function rethrowAsync(error) {
55
+ queueMicrotask(() => {
56
+ throw error;
57
+ });
58
+ }
59
+ function isThenable(value) {
60
+ return typeof value?.then === "function";
61
+ }
62
+ var ON_TEARDOWN = /* @__PURE__ */ Symbol.for("react-websocket.onTeardown");
63
+ function createClient(url, options = {}) {
64
+ const onTeardown = options[ON_TEARDOWN];
65
+ const log = options.logger ?? (() => {
66
+ });
67
+ const retry = options.reconnect === false ? null : {
68
+ ...RECONNECT_DEFAULTS,
69
+ ...typeof options.reconnect === "object" ? options.reconnect : {}
70
+ };
71
+ const queueLimit = options.queue === false ? 0 : typeof options.queue === "object" ? Math.max(0, options.queue.limit ?? Infinity) : Infinity;
72
+ let snapshot = { status: "idle", lastMessage: void 0, attempt: 0 };
73
+ const storeListeners = /* @__PURE__ */ new Set();
74
+ const listeners = {
75
+ open: /* @__PURE__ */ new Set(),
76
+ message: /* @__PURE__ */ new Set(),
77
+ close: /* @__PURE__ */ new Set(),
78
+ error: /* @__PURE__ */ new Set()
79
+ };
80
+ let ws = null;
81
+ let wanted = false;
82
+ let refs = 0;
83
+ let pinned = false;
84
+ let pending = [];
85
+ let ready = null;
86
+ let opened = false;
87
+ let unavailable = null;
88
+ let startScheduled = false;
89
+ let inbox = null;
90
+ let generation = 0;
91
+ let windowBound = false;
92
+ let retryTimer;
93
+ let teardownTimer;
94
+ let heartbeatTimer;
95
+ let pongTimer;
96
+ function set(patch) {
97
+ snapshot = { ...snapshot, ...patch };
98
+ for (const listener of [...storeListeners]) listener();
99
+ }
100
+ function emit(type, ...args) {
101
+ for (const listener of [...listeners[type]]) {
102
+ try {
103
+ listener(...args);
104
+ } catch (error) {
105
+ rethrowAsync(error);
106
+ }
107
+ }
108
+ }
109
+ function getImpl() {
110
+ if (options.WebSocket) return options.WebSocket;
111
+ return typeof window === "undefined" ? void 0 : globalThis.WebSocket;
112
+ }
113
+ function rejectReady(reason) {
114
+ if (!ready || ready.settled) ready = createDeferred();
115
+ ready.reject(reason);
116
+ }
117
+ function retryNow() {
118
+ if (retryTimer !== void 0) {
119
+ log("network or visibility change, retrying now");
120
+ open();
121
+ }
122
+ }
123
+ function onVisibilityChange() {
124
+ if (document.visibilityState === "visible") retryNow();
125
+ }
126
+ function bindWindow() {
127
+ if (windowBound || typeof window === "undefined") return;
128
+ windowBound = true;
129
+ window.addEventListener("online", retryNow);
130
+ document.addEventListener("visibilitychange", onVisibilityChange);
131
+ }
132
+ function unbindWindow() {
133
+ if (!windowBound) return;
134
+ windowBound = false;
135
+ window.removeEventListener("online", retryNow);
136
+ document.removeEventListener("visibilitychange", onVisibilityChange);
137
+ }
138
+ function startHeartbeat(socket) {
139
+ const heartbeat = options.heartbeat;
140
+ if (!heartbeat) return;
141
+ heartbeatTimer = setInterval(() => {
142
+ socket.send(heartbeat.message ?? "ping");
143
+ if (heartbeat.timeout && pongTimer === void 0) {
144
+ pongTimer = setTimeout(() => {
145
+ log("heartbeat timeout");
146
+ detach(socket, false);
147
+ socket.close(4e3, "heartbeat timeout");
148
+ handleClose({ code: 4e3, reason: "heartbeat timeout", wasClean: false });
149
+ }, heartbeat.timeout);
150
+ }
151
+ }, heartbeat.interval);
152
+ }
153
+ function stopHeartbeat() {
154
+ clearInterval(heartbeatTimer);
155
+ clearTimeout(pongTimer);
156
+ heartbeatTimer = pongTimer = void 0;
157
+ }
158
+ function detach(socket, reportClose) {
159
+ if (ws === socket) ws = null;
160
+ socket.onopen = socket.onmessage = socket.onerror = null;
161
+ socket.onclose = reportClose ? (event) => emit("close", { code: event.code, reason: event.reason, wasClean: event.wasClean }) : null;
162
+ }
163
+ function backoff(attempt) {
164
+ const { minDelay, maxDelay, factor, jitter } = retry;
165
+ const base = Math.min(maxDelay, minDelay * factor ** (attempt - 1));
166
+ return Math.round(base * (1 - jitter * Math.random()));
167
+ }
168
+ function open() {
169
+ clearTimeout(retryTimer);
170
+ retryTimer = void 0;
171
+ const Impl = getImpl();
172
+ if (!Impl) return;
173
+ const id = ++generation;
174
+ set({ status: snapshot.attempt === 0 ? "connecting" : "reconnecting" });
175
+ let target;
176
+ try {
177
+ target = typeof url === "string" ? url : url();
178
+ } catch (error) {
179
+ urlFailed(error);
180
+ return;
181
+ }
182
+ if (typeof target === "string") {
183
+ start(Impl, target);
184
+ return;
185
+ }
186
+ Promise.resolve(target).then(
187
+ (resolved) => {
188
+ if (id === generation && wanted) start(Impl, resolved);
189
+ },
190
+ (error) => {
191
+ if (id === generation && wanted) urlFailed(error);
192
+ }
193
+ );
194
+ }
195
+ function urlFailed(error) {
196
+ const reason = error instanceof Error ? error : new Error(String(error));
197
+ log("url() failed", reason);
198
+ emit("error", reason);
199
+ retryOrFail({ code: 1006, reason: "url() failed", wasClean: false }, reason);
200
+ }
201
+ function start(Impl, target) {
202
+ let socket;
203
+ try {
204
+ socket = new Impl(target, options.protocols);
205
+ } catch (error) {
206
+ emit("error", error);
207
+ fail(error);
208
+ return;
209
+ }
210
+ if (options.binaryType) socket.binaryType = options.binaryType;
211
+ ws = socket;
212
+ log("connecting", target);
213
+ socket.onopen = (event) => {
214
+ log("open");
215
+ opened = true;
216
+ set({ status: "open", attempt: 0 });
217
+ startHeartbeat(socket);
218
+ ready?.resolve();
219
+ emit("open", event);
220
+ if (ws !== socket) return;
221
+ const queued = pending;
222
+ pending = [];
223
+ for (const data of queued) socket.send(data);
224
+ };
225
+ socket.onmessage = (event) => receive(event, socket);
226
+ socket.onerror = (event) => emit("error", event);
227
+ socket.onclose = (event) => {
228
+ detach(socket, false);
229
+ handleClose({ code: event.code, reason: event.reason, wasClean: event.wasClean });
230
+ };
231
+ }
232
+ function handleClose(info) {
233
+ stopHeartbeat();
234
+ log("closed", info);
235
+ retryOrFail(info);
236
+ emit("close", info);
237
+ }
238
+ function retryOrFail(info, error) {
239
+ if (wanted && retry && snapshot.attempt < retry.maxAttempts && (retry.shouldReconnect?.(info) ?? true)) {
240
+ const attempt = snapshot.attempt + 1;
241
+ const delay = backoff(attempt);
242
+ set({ status: "reconnecting", attempt });
243
+ log(`reconnecting in ${delay}ms (attempt ${attempt})`);
244
+ retryTimer = setTimeout(open, delay);
245
+ } else {
246
+ fail(
247
+ error ?? new Error(`WebSocket closed (code ${info.code}${info.reason ? `: ${info.reason}` : ""})`)
248
+ );
249
+ }
250
+ }
251
+ function fail(reason) {
252
+ wanted = false;
253
+ opened = false;
254
+ unbindWindow();
255
+ pending = [];
256
+ set({ status: "closed" });
257
+ rejectReady(reason);
258
+ }
259
+ function receive(event, socket) {
260
+ clearTimeout(pongTimer);
261
+ pongTimer = void 0;
262
+ if (options.heartbeat?.pong !== void 0 && event.data === options.heartbeat.pong) return;
263
+ const run = () => decode(event, socket);
264
+ if (inbox) {
265
+ const next = inbox.then(run).then(() => {
266
+ if (inbox === next) inbox = null;
267
+ });
268
+ inbox = next;
269
+ return;
270
+ }
271
+ const result = run();
272
+ if (result) {
273
+ const next = result.then(() => {
274
+ if (inbox === next) inbox = null;
275
+ });
276
+ inbox = next;
277
+ }
278
+ }
279
+ function decode(event, socket) {
280
+ let value;
281
+ try {
282
+ value = options.parse ? options.parse(event.data) : options.json ? JSON.parse(event.data) : event.data;
283
+ } catch (cause) {
284
+ emit("error", new MessageError("Failed to parse message", event.data, { cause }));
285
+ return;
286
+ }
287
+ const schema = options.schema;
288
+ if (!schema) return deliver(value, event, socket);
289
+ let result;
290
+ try {
291
+ result = schema["~standard"].validate(value);
292
+ } catch (cause) {
293
+ emit("error", new MessageError("Schema validation threw", event.data, { cause }));
294
+ return;
295
+ }
296
+ if (isThenable(result)) {
297
+ return Promise.resolve(result).then(
298
+ (r) => validated(r, event, socket),
299
+ (cause) => emit("error", new MessageError("Schema validation threw", event.data, { cause }))
300
+ );
301
+ }
302
+ validated(result, event, socket);
303
+ }
304
+ function validated(result, event, socket) {
305
+ if (result.issues) {
306
+ emit(
307
+ "error",
308
+ new MessageError("Message failed schema validation", event.data, { issues: result.issues })
309
+ );
310
+ } else {
311
+ deliver(result.value, event, socket);
312
+ }
313
+ }
314
+ function deliver(message, event, socket) {
315
+ if (ws !== socket) return;
316
+ set({ lastMessage: message });
317
+ emit("message", message, event);
318
+ }
319
+ function send(message) {
320
+ const data = options.serialize ? options.serialize(message) : options.json ? JSON.stringify(message) : message;
321
+ if (ws && ws.readyState === OPEN) {
322
+ ws.send(data);
323
+ return true;
324
+ }
325
+ if (queueLimit === 0) {
326
+ log("dropped message: socket is not open");
327
+ return false;
328
+ }
329
+ if (!getImpl()) {
330
+ log("dropped message: no WebSocket implementation available");
331
+ return false;
332
+ }
333
+ pending.push(data);
334
+ if (pending.length > queueLimit) {
335
+ pending.shift();
336
+ log(`dropped oldest queued message: queue limit (${queueLimit}) reached`);
337
+ }
338
+ return false;
339
+ }
340
+ function begin() {
341
+ wanted = true;
342
+ if (snapshot.status === "idle" || snapshot.status === "closed") {
343
+ opened = false;
344
+ if (ready?.settled) ready = null;
345
+ }
346
+ snapshot = { ...snapshot, attempt: 0 };
347
+ bindWindow();
348
+ open();
349
+ }
350
+ function ensureConnecting() {
351
+ if (wanted || !getImpl()) return;
352
+ begin();
353
+ }
354
+ function connect() {
355
+ pinned = true;
356
+ ensureConnecting();
357
+ }
358
+ function stop(code, reason) {
359
+ wanted = false;
360
+ generation++;
361
+ clearTimeout(retryTimer);
362
+ retryTimer = void 0;
363
+ stopHeartbeat();
364
+ unbindWindow();
365
+ pending = [];
366
+ if (ws) {
367
+ const socket = ws;
368
+ detach(socket, true);
369
+ socket.close(code, reason);
370
+ }
371
+ }
372
+ function close(code = 1e3, reason) {
373
+ pinned = false;
374
+ opened = false;
375
+ stop(code, reason);
376
+ set({ status: "closed", attempt: 0 });
377
+ rejectReady(new Error("WebSocket was closed"));
378
+ }
379
+ function reconnect() {
380
+ if (!getImpl()) return;
381
+ clearTimeout(retryTimer);
382
+ retryTimer = void 0;
383
+ stopHeartbeat();
384
+ if (ws) {
385
+ const socket = ws;
386
+ detach(socket, true);
387
+ socket.close(1e3, "reconnect");
388
+ }
389
+ begin();
390
+ }
391
+ function teardown() {
392
+ if (refs > 0 || pinned) return;
393
+ if (ready && !ready.settled) return;
394
+ stop();
395
+ ready = null;
396
+ opened = false;
397
+ set({ status: "idle", attempt: 0 });
398
+ onTeardown?.();
399
+ }
400
+ function acquire() {
401
+ refs++;
402
+ clearTimeout(teardownTimer);
403
+ if (snapshot.status === "idle") ensureConnecting();
404
+ let released = false;
405
+ return () => {
406
+ if (released) return;
407
+ released = true;
408
+ if (--refs > 0) return;
409
+ clearTimeout(teardownTimer);
410
+ teardownTimer = setTimeout(teardown, 0);
411
+ };
412
+ }
413
+ return {
414
+ url,
415
+ get ready() {
416
+ if (!getImpl()) {
417
+ if (!unavailable) {
418
+ unavailable = createDeferred();
419
+ unavailable.reject(
420
+ new Error("react-websocket: no WebSocket available here (server render?)")
421
+ );
422
+ }
423
+ return unavailable.promise;
424
+ }
425
+ if (snapshot.status === "idle" && !startScheduled) {
426
+ startScheduled = true;
427
+ queueMicrotask(() => {
428
+ startScheduled = false;
429
+ if (snapshot.status === "idle") ensureConnecting();
430
+ });
431
+ }
432
+ if (!ready) {
433
+ ready = createDeferred();
434
+ if (opened) ready.resolve();
435
+ }
436
+ return ready.promise;
437
+ },
438
+ get socket() {
439
+ return ws;
440
+ },
441
+ subscribe(listener) {
442
+ storeListeners.add(listener);
443
+ return () => {
444
+ storeListeners.delete(listener);
445
+ };
446
+ },
447
+ getSnapshot: () => snapshot,
448
+ on(type, listener) {
449
+ const entry = ((...args) => listener(...args));
450
+ listeners[type].add(entry);
451
+ return () => {
452
+ listeners[type].delete(entry);
453
+ };
454
+ },
455
+ send,
456
+ connect,
457
+ close,
458
+ reconnect,
459
+ acquire
460
+ };
461
+ }
462
+ function createWebSocket(url, options) {
463
+ return createClient(url, options);
464
+ }
465
+ export {
466
+ MessageError,
467
+ createWebSocket
468
+ };
469
+ //# sourceMappingURL=core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/client.ts"],"sourcesContent":["/**\n * Where to connect: a URL, or a function that returns one (sync or async).\n *\n * A function is called before **every** connection attempt, including reconnects,\n * so it can put a fresh auth token in the URL. If it throws or rejects, that counts\n * as a failed attempt and is retried with backoff.\n *\n * @example\n * ```ts\n * createWebSocket(async () => `wss://api.example.com/live?token=${await getToken()}`);\n * ```\n */\nexport type UrlSource = string | (() => string | Promise<string>);\n\n/**\n * Connection state.\n *\n * - `idle`: not connected and not trying to be. Nobody is using the client yet, or everyone stopped.\n * - `connecting`: the first attempt is in progress.\n * - `open`: connected. `send()` goes out immediately.\n * - `reconnecting`: the connection dropped (or an attempt failed) and a retry is scheduled or in progress.\n * - `closed`: stopped for good, by `close()` or after giving up on reconnecting.\n * It stays closed until `connect()` or `reconnect()` is called, or every hook unmounts.\n */\nexport type Status = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed';\n\n/** The client's state as seen by React. A new object is created on every change. */\nexport interface Snapshot<In> {\n /** Connection state. */\n readonly status: Status;\n /** Most recent message (after `parse`/`json` and `schema`), kept across reconnects. */\n readonly lastMessage: In | undefined;\n /** Consecutive failed attempts since the last successful open. `0` while open. */\n readonly attempt: number;\n}\n\n/** Details of a closed connection, from the browser's `CloseEvent`. */\nexport interface CloseInfo {\n /** Close code: `1000` is a normal close, `1006` an abnormal one (e.g. network loss), `4000`–`4999` are yours. */\n readonly code: number;\n /** Close reason sent by the side that closed the connection. Often empty. */\n readonly reason: string;\n /** Whether the closing handshake completed. */\n readonly wasClean: boolean;\n}\n\n/** Anything `WebSocket.prototype.send` accepts: a string, `Blob`, `ArrayBuffer` or typed array. */\nexport type SendData = Parameters<WebSocket['send']>[0];\n\n/** Reconnect timing. Delay before attempt `n` = `min(maxDelay, minDelay * factor ** (n - 1))`, minus jitter. */\nexport interface ReconnectOptions {\n /**\n * Maximum consecutive reconnect attempts. When the last one fails too, the client\n * gives up: the status becomes `closed` and `ready` rejects. `0` never retries.\n * @default Infinity\n */\n maxAttempts?: number;\n /**\n * Delay before the first retry, in ms.\n * @default 1000\n */\n minDelay?: number;\n /**\n * Upper bound for the delay, in ms.\n * @default 30000\n */\n maxDelay?: number;\n /**\n * Backoff multiplier applied per attempt.\n * @default 2\n */\n factor?: number;\n /**\n * Randomly shave up to this fraction (0–1) off each delay, so that many clients\n * dropped at once don't all reconnect at the same moment.\n * @default 0.5\n */\n jitter?: number;\n /**\n * Called on every unexpected close. Return `false` to stop reconnecting.\n *\n * @example\n * ```ts\n * // Don't retry when the server rejects our credentials.\n * shouldReconnect: close => close.code !== 4001\n * ```\n * @default () => true\n */\n shouldReconnect?: (close: CloseInfo) => boolean;\n}\n\n/** Application-level keep-alive. Useful behind proxies that drop idle connections. */\nexport interface HeartbeatOptions {\n /** Send `message` every `interval` ms while open. */\n interval: number;\n /**\n * Sent as-is (it is not passed through `serialize` or `json`).\n * @default 'ping'\n */\n message?: string;\n /** Incoming data equal to this string is swallowed instead of being delivered as a message. */\n pong?: string;\n /**\n * If nothing at all arrives within this many ms after a ping, the connection is\n * treated as dead: it closes with code `4000` and reconnects.\n */\n timeout?: number;\n}\n\n/** Bounds for the send queue. */\nexport interface QueueOptions {\n /**\n * Maximum number of messages held while not connected. When full, the oldest\n * message is dropped.\n * @default Infinity\n */\n limit?: number;\n}\n\n/**\n * The minimal [Standard Schema v1](https://standardschema.dev) interface, implemented\n * by zod (3.24+), valibot (1.0+), arktype (2.0+) and others. You don't need to\n * import this; pass your schema object directly.\n */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': {\n readonly version: 1;\n readonly vendor: string;\n readonly validate: (\n value: unknown\n ) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;\n readonly types?: { readonly input: Input; readonly output: Output } | undefined;\n };\n}\n\n/** The result of a Standard Schema `validate` call. */\nexport type StandardSchemaResult<Output> =\n | { readonly value: Output; readonly issues?: undefined }\n | { readonly issues: ReadonlyArray<{ readonly message: string }> };\n\n/**\n * Connection options, shared by `createWebSocket(url, options)` and `useWebSocket(url, options)`.\n *\n * @typeParam In - Type of incoming messages (after `parse`/`json`/`schema`).\n * @typeParam Out - Type accepted by `send()`.\n */\nexport interface WebSocketOptions<In = unknown, Out = unknown> {\n /** Sub-protocol(s) passed to the `WebSocket` constructor. */\n protocols?: string | string[];\n /**\n * How binary messages are exposed.\n * @default 'blob'\n */\n binaryType?: BinaryType;\n /**\n * `JSON.parse` incoming and `JSON.stringify` outgoing messages. Messages that fail\n * to parse are reported to `onError` as a {@link MessageError} and not delivered.\n * @default false\n */\n json?: boolean;\n /**\n * Custom decoder for incoming `event.data`. Takes precedence over `json`.\n * Throwing reports a {@link MessageError} and drops the message.\n */\n parse?: (data: unknown) => unknown;\n /** Custom encoder for outgoing messages. Takes precedence over `json`. */\n serialize?: (message: Out) => SendData;\n /**\n * Validate incoming messages (after parsing) with any Standard Schema library.\n * Invalid messages are reported to `onError` as a {@link MessageError} and not delivered.\n * The message type `In` is inferred from it.\n *\n * @example\n * ```ts\n * createWebSocket(url, { json: true, schema: z.object({ price: z.number() }) });\n * ```\n */\n schema?: StandardSchemaV1<unknown, In>;\n /**\n * Reconnect with exponential backoff after an unexpected close. `false` disables it.\n * @default true\n */\n reconnect?: boolean | ReconnectOptions;\n /** Send a ping on an interval and, optionally, reconnect when the server goes quiet. */\n heartbeat?: HeartbeatOptions;\n /**\n * Buffer `send()` calls made while not connected and send them, in order, on open\n * (right after `open` listeners run).\n * `false` drops them instead. `{ limit }` caps the buffer, dropping the oldest.\n * The queue is cleared by `close()` or when the client gives up.\n * @default true\n */\n queue?: boolean | QueueOptions;\n /**\n * Receives debug messages about connection attempts, retries and dropped messages.\n * @example\n * ```ts\n * logger: console.debug\n * ```\n */\n logger?: (message: string, ...details: unknown[]) => void;\n /**\n * `WebSocket` implementation to use, e.g. a mock in tests or the `ws` package in Node.\n * When omitted, the global `WebSocket` is used in browsers. During a server render\n * (no `window`), nothing connects unless an implementation is passed.\n */\n WebSocket?: typeof WebSocket;\n}\n\n/**\n * Reported via the `error` event (and `onError`) when an incoming message can't be\n * decoded by `parse`/`json` or fails `schema` validation. The message is not delivered.\n *\n * @example\n * ```ts\n * onError(error) {\n * if (error instanceof MessageError) report(error.data, error.issues);\n * }\n * ```\n */\nexport class MessageError extends Error {\n /** The raw `event.data` that failed. */\n readonly data: unknown;\n /** Schema validation issues, when the message failed `schema`. */\n readonly issues: ReadonlyArray<{ readonly message: string }> | undefined;\n\n constructor(\n message: string,\n data: unknown,\n options?: { cause?: unknown; issues?: ReadonlyArray<{ readonly message: string }> }\n ) {\n super(message, options?.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'MessageError';\n this.data = data;\n this.issues = options?.issues;\n }\n}\n\n/** Events emitted by a client. Subscribe with `client.on(type, listener)` or `useWebSocketEvent`. */\nexport interface EventMap<In> {\n /**\n * The socket opened (initially or after a reconnect). Listeners run before queued\n * messages are sent, so a handshake sent from here goes out first.\n */\n open: (event: Event) => void;\n /** A message arrived and passed `parse` and `schema`. */\n message: (message: In, event: MessageEvent) => void;\n /** A socket closed, whether it will be retried or not. */\n close: (close: CloseInfo) => void;\n /**\n * A socket error `Event`, a {@link MessageError} for an undecodable or invalid message,\n * or the `Error` thrown by the `WebSocket` constructor or a `url` function.\n */\n error: (error: Event | MessageError | Error) => void;\n}\n\n/**\n * A WebSocket connection that reconnects, queues, decodes and can be shared.\n * Create one with `createWebSocket()`.\n *\n * The connection is reference-counted: it opens when the first hook mounts (or\n * `ready` is read) and closes one tick after the last hook unmounts. Calling\n * `connect()` keeps it open regardless, until `close()`.\n *\n * @typeParam In - Type of incoming messages.\n * @typeParam Out - Type accepted by `send()`.\n */\nexport interface WebSocketClient<In = unknown, Out = unknown> {\n /** The URL (or URL function) the client was created with. */\n readonly url: UrlSource;\n /**\n * A promise that resolves once the socket has opened. Reading it starts an idle client.\n *\n * It stays resolved through automatic reconnects, so `use(client.ready)` shows a\n * Suspense fallback only for the first connection, never on a network blip; use\n * `status` to show reconnects. It rejects when the client gives up reconnecting, when\n * `close()` is called, and during a server render. After that, `connect()` or\n * `reconnect()` make it a new pending promise.\n *\n * It is safe to pass to React 19's `use()`: the same promise is returned until its state\n * changes, and it carries `status`/`value`/`reason` so `use()` doesn't suspend when it is\n * already settled.\n */\n readonly ready: Promise<void>;\n /** The current underlying `WebSocket`, if any. An escape hatch; prefer the client's methods. */\n readonly socket: WebSocket | null;\n /** Subscribe to snapshot changes. Compatible with `useSyncExternalStore`. Returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** The current {@link Snapshot}. Returns the same object until something changes. */\n getSnapshot(): Snapshot<In>;\n /**\n * Listen to an event. Returns an unsubscribe function. Listener errors are re-thrown\n * asynchronously, so one failing listener doesn't break the others.\n */\n on<K extends keyof EventMap<In>>(type: K, listener: EventMap<In>[K]): () => void;\n /**\n * Send a message (encoded with `serialize`/`json` if configured). If the socket isn't\n * open, the message is queued and sent on open (see the `queue` option).\n * @returns `true` if it was sent immediately, `false` if it was queued or dropped.\n */\n send(message: Out): boolean;\n /**\n * Start connecting, and keep the connection open even when no hook is using the\n * client, until `close()` is called. Does nothing if already connecting or open.\n */\n connect(): void;\n /**\n * Close the connection and stop reconnecting. The status becomes `closed` and the\n * send queue is cleared. Mounted hooks stay mounted; call `connect()` or `reconnect()`\n * to start again.\n * @param code - Close code. @default 1000\n */\n close(code?: number, reason?: string): void;\n /**\n * Drop the current socket (if any) and connect again immediately, resetting the\n * backoff. Also restarts a `closed` client.\n */\n reconnect(): void;\n /**\n * Hold the connection open until the returned function is called. This is what the\n * hooks use; call it yourself to integrate with non-React code.\n * @returns A release function (safe to call more than once).\n */\n acquire(): () => void;\n}\n","import {\n MessageError,\n type CloseInfo,\n type EventMap,\n type ReconnectOptions,\n type SendData,\n type Snapshot,\n type StandardSchemaResult,\n type UrlSource,\n type WebSocketClient,\n type WebSocketOptions\n} from './types';\n\nconst OPEN = 1;\n\nconst RECONNECT_DEFAULTS = {\n maxAttempts: Infinity,\n minDelay: 1000,\n maxDelay: 30_000,\n factor: 2,\n jitter: 0.5\n} satisfies ReconnectOptions;\n\ntype Timer = ReturnType<typeof setTimeout> | undefined;\n\n// React's `use()` reads `status`/`value`/`reason` off a thenable to skip suspending\n// when it is already settled.\ntype TrackedPromise = Promise<void> & {\n status: 'pending' | 'fulfilled' | 'rejected';\n value?: void;\n reason?: unknown;\n};\n\ninterface Deferred {\n readonly promise: TrackedPromise;\n settled: boolean;\n resolve(): void;\n reject(reason: unknown): void;\n}\n\nfunction createDeferred(): Deferred {\n let resolve!: () => void;\n let reject!: (reason: unknown) => void;\n const promise = new Promise<void>((res, rej) => {\n resolve = res;\n reject = rej;\n }) as TrackedPromise;\n promise.status = 'pending';\n // Nobody may be awaiting `ready`; don't surface that as an unhandled rejection.\n promise.catch(() => {});\n const deferred: Deferred = {\n promise,\n settled: false,\n resolve() {\n if (deferred.settled) return;\n deferred.settled = true;\n promise.status = 'fulfilled';\n promise.value = undefined;\n resolve();\n },\n reject(reason) {\n if (deferred.settled) return;\n deferred.settled = true;\n promise.status = 'rejected';\n promise.reason = reason;\n reject(reason);\n }\n };\n return deferred;\n}\n\nfunction rethrowAsync(error: unknown) {\n queueMicrotask(() => {\n throw error;\n });\n}\n\nfunction isThenable<T>(value: unknown): value is PromiseLike<T> {\n return typeof (value as PromiseLike<T> | null)?.then === 'function';\n}\n\n/**\n * @internal Option key for a callback run when the client tears down, which lets the hooks'\n * URL registry forget clients nobody holds anymore. A registered symbol rather than an export,\n * because the hooks entry imports the client from the `core` entry at runtime.\n */\nconst ON_TEARDOWN = Symbol.for('react-websocket.onTeardown');\n\nfunction createClient<In = unknown, Out = unknown>(\n url: UrlSource,\n options: WebSocketOptions<In, Out> & { [ON_TEARDOWN]?: () => void } = {}\n): WebSocketClient<In, Out> {\n const onTeardown = options[ON_TEARDOWN];\n const log = options.logger ?? (() => {});\n const retry =\n options.reconnect === false\n ? null\n : {\n ...RECONNECT_DEFAULTS,\n ...(typeof options.reconnect === 'object' ? options.reconnect : {})\n };\n const queueLimit =\n options.queue === false\n ? 0\n : typeof options.queue === 'object'\n ? Math.max(0, options.queue.limit ?? Infinity)\n : Infinity;\n\n let snapshot: Snapshot<In> = { status: 'idle', lastMessage: undefined, attempt: 0 };\n const storeListeners = new Set<() => void>();\n const listeners: { [K in keyof EventMap<In>]: Set<EventMap<In>[K]> } = {\n open: new Set(),\n message: new Set(),\n close: new Set(),\n error: new Set()\n };\n\n let ws: WebSocket | null = null;\n let wanted = false;\n let refs = 0;\n // Set by a public `connect()`: stay connected after the last hook releases, until `close()`.\n let pinned = false;\n let pending: SendData[] = [];\n let ready: Deferred | null = null;\n // Opened at least once since the client was last started. `ready` stays resolved through\n // automatic reconnects so `use(client.ready)` doesn't swap content for a fallback on every blip.\n let opened = false;\n let unavailable: Deferred | null = null;\n let startScheduled = false;\n let inbox: Promise<void> | null = null;\n // Bumped per connection attempt so a slow `url()` can't resurrect a cancelled one.\n let generation = 0;\n let windowBound = false;\n let retryTimer: Timer;\n let teardownTimer: Timer;\n let heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n let pongTimer: Timer;\n\n function set(patch: Partial<Snapshot<In>>) {\n snapshot = { ...snapshot, ...patch };\n for (const listener of [...storeListeners]) listener();\n }\n\n function emit<K extends keyof EventMap<In>>(type: K, ...args: Parameters<EventMap<In>[K]>) {\n for (const listener of [...listeners[type]]) {\n try {\n (listener as (...a: Parameters<EventMap<In>[K]>) => void)(...args);\n } catch (error) {\n rethrowAsync(error);\n }\n }\n }\n\n function getImpl(): typeof WebSocket | undefined {\n if (options.WebSocket) return options.WebSocket;\n // Node has a global WebSocket too; don't connect from a server render.\n return typeof window === 'undefined' ? undefined : globalThis.WebSocket;\n }\n\n function rejectReady(reason: unknown) {\n if (!ready || ready.settled) ready = createDeferred();\n ready.reject(reason);\n }\n\n function retryNow() {\n if (retryTimer !== undefined) {\n log('network or visibility change, retrying now');\n open();\n }\n }\n\n function onVisibilityChange() {\n if (document.visibilityState === 'visible') retryNow();\n }\n\n function bindWindow() {\n if (windowBound || typeof window === 'undefined') return;\n windowBound = true;\n window.addEventListener('online', retryNow);\n document.addEventListener('visibilitychange', onVisibilityChange);\n }\n\n function unbindWindow() {\n if (!windowBound) return;\n windowBound = false;\n window.removeEventListener('online', retryNow);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n }\n\n function startHeartbeat(socket: WebSocket) {\n const heartbeat = options.heartbeat;\n if (!heartbeat) return;\n heartbeatTimer = setInterval(() => {\n socket.send(heartbeat.message ?? 'ping');\n if (heartbeat.timeout && pongTimer === undefined) {\n pongTimer = setTimeout(() => {\n log('heartbeat timeout');\n // The close handshake may never finish on a dead link, so don't wait for it.\n detach(socket, false);\n socket.close(4000, 'heartbeat timeout');\n handleClose({ code: 4000, reason: 'heartbeat timeout', wasClean: false });\n }, heartbeat.timeout);\n }\n }, heartbeat.interval);\n }\n\n function stopHeartbeat() {\n clearInterval(heartbeatTimer);\n clearTimeout(pongTimer);\n heartbeatTimer = pongTimer = undefined;\n }\n\n /** Stop tracking `socket`. Its eventual close event is still reported unless `reportClose` is false. */\n function detach(socket: WebSocket, reportClose: boolean) {\n if (ws === socket) ws = null;\n socket.onopen = socket.onmessage = socket.onerror = null;\n socket.onclose = reportClose\n ? event => emit('close', { code: event.code, reason: event.reason, wasClean: event.wasClean })\n : null;\n }\n\n function backoff(attempt: number) {\n const { minDelay, maxDelay, factor, jitter } = retry!;\n const base = Math.min(maxDelay, minDelay * factor ** (attempt - 1));\n return Math.round(base * (1 - jitter * Math.random()));\n }\n\n function open() {\n clearTimeout(retryTimer);\n retryTimer = undefined;\n const Impl = getImpl();\n if (!Impl) return;\n const id = ++generation;\n set({ status: snapshot.attempt === 0 ? 'connecting' : 'reconnecting' });\n\n let target: string | Promise<string>;\n try {\n target = typeof url === 'string' ? url : url();\n } catch (error) {\n urlFailed(error);\n return;\n }\n if (typeof target === 'string') {\n start(Impl, target);\n return;\n }\n Promise.resolve(target).then(\n resolved => {\n if (id === generation && wanted) start(Impl, resolved);\n },\n error => {\n if (id === generation && wanted) urlFailed(error);\n }\n );\n }\n\n /** `url()` threw or rejected (e.g. a token refresh failed): count it as a failed attempt. */\n function urlFailed(error: unknown) {\n const reason = error instanceof Error ? error : new Error(String(error));\n log('url() failed', reason);\n emit('error', reason);\n retryOrFail({ code: 1006, reason: 'url() failed', wasClean: false }, reason);\n }\n\n function start(Impl: typeof WebSocket, target: string) {\n let socket: WebSocket;\n try {\n socket = new Impl(target, options.protocols);\n } catch (error) {\n // e.g. an invalid URL; retrying won't help.\n emit('error', error as Error);\n fail(error);\n return;\n }\n if (options.binaryType) socket.binaryType = options.binaryType;\n ws = socket;\n log('connecting', target);\n\n socket.onopen = event => {\n log('open');\n opened = true;\n set({ status: 'open', attempt: 0 });\n startHeartbeat(socket);\n ready?.resolve();\n // `open` listeners go first, so a handshake sent from `onOpen` (e.g. auth) precedes\n // whatever was queued while disconnected.\n emit('open', event);\n if (ws !== socket) return; // a listener closed or replaced it\n const queued = pending;\n pending = [];\n for (const data of queued) socket.send(data);\n };\n socket.onmessage = event => receive(event, socket);\n socket.onerror = event => emit('error', event);\n socket.onclose = event => {\n detach(socket, false);\n handleClose({ code: event.code, reason: event.reason, wasClean: event.wasClean });\n };\n }\n\n function handleClose(info: CloseInfo) {\n stopHeartbeat();\n log('closed', info);\n retryOrFail(info);\n emit('close', info);\n }\n\n function retryOrFail(info: CloseInfo, error?: Error) {\n if (\n wanted &&\n retry &&\n snapshot.attempt < retry.maxAttempts &&\n (retry.shouldReconnect?.(info) ?? true)\n ) {\n const attempt = snapshot.attempt + 1;\n const delay = backoff(attempt);\n set({ status: 'reconnecting', attempt });\n log(`reconnecting in ${delay}ms (attempt ${attempt})`);\n retryTimer = setTimeout(open, delay);\n } else {\n fail(\n error ??\n new Error(`WebSocket closed (code ${info.code}${info.reason ? `: ${info.reason}` : ''})`)\n );\n }\n }\n\n function fail(reason: unknown) {\n wanted = false;\n opened = false;\n unbindWindow();\n pending = [];\n set({ status: 'closed' });\n rejectReady(reason);\n }\n\n function receive(event: MessageEvent, socket: WebSocket) {\n clearTimeout(pongTimer);\n pongTimer = undefined;\n if (options.heartbeat?.pong !== undefined && event.data === options.heartbeat.pong) return;\n\n // Async schema validation must not reorder messages.\n const run = () => decode(event, socket);\n if (inbox) {\n const next: Promise<void> = inbox.then(run).then(() => {\n if (inbox === next) inbox = null;\n });\n inbox = next;\n return;\n }\n const result = run();\n if (result) {\n const next: Promise<void> = result.then(() => {\n if (inbox === next) inbox = null;\n });\n inbox = next;\n }\n }\n\n function decode(event: MessageEvent, socket: WebSocket): void | Promise<void> {\n let value: unknown;\n try {\n value = options.parse\n ? options.parse(event.data)\n : options.json\n ? JSON.parse(event.data as string)\n : event.data;\n } catch (cause) {\n emit('error', new MessageError('Failed to parse message', event.data, { cause }));\n return;\n }\n\n const schema = options.schema;\n if (!schema) return deliver(value as In, event, socket);\n\n let result: ReturnType<(typeof schema)['~standard']['validate']>;\n try {\n result = schema['~standard'].validate(value);\n } catch (cause) {\n emit('error', new MessageError('Schema validation threw', event.data, { cause }));\n return;\n }\n if (isThenable<StandardSchemaResult<In>>(result)) {\n return Promise.resolve(result).then(\n r => validated(r, event, socket),\n cause => emit('error', new MessageError('Schema validation threw', event.data, { cause }))\n );\n }\n validated(result, event, socket);\n }\n\n function validated(result: StandardSchemaResult<In>, event: MessageEvent, socket: WebSocket) {\n if (result.issues) {\n emit(\n 'error',\n new MessageError('Message failed schema validation', event.data, { issues: result.issues })\n );\n } else {\n deliver(result.value, event, socket);\n }\n }\n\n function deliver(message: In, event: MessageEvent, socket: WebSocket) {\n if (ws !== socket) return; // closed or replaced while validating\n set({ lastMessage: message });\n emit('message', message, event);\n }\n\n function send(message: Out): boolean {\n const data = options.serialize\n ? options.serialize(message)\n : options.json\n ? JSON.stringify(message)\n : (message as SendData);\n if (ws && ws.readyState === OPEN) {\n ws.send(data);\n return true;\n }\n if (queueLimit === 0) {\n log('dropped message: socket is not open');\n return false;\n }\n if (!getImpl()) {\n // e.g. during a server render: this client can never connect, so don't hold on to it.\n log('dropped message: no WebSocket implementation available');\n return false;\n }\n pending.push(data);\n if (pending.length > queueLimit) {\n pending.shift();\n log(`dropped oldest queued message: queue limit (${queueLimit}) reached`);\n }\n return false;\n }\n\n function begin() {\n wanted = true;\n // Starting over after `close()` or giving up: wait for a new connection.\n if (snapshot.status === 'idle' || snapshot.status === 'closed') {\n opened = false;\n if (ready?.settled) ready = null;\n }\n snapshot = { ...snapshot, attempt: 0 }; // open() notifies\n bindWindow();\n open();\n }\n\n /** Start connecting unless already wanted. Used by holders (`acquire`, `ready`). */\n function ensureConnecting() {\n if (wanted || !getImpl()) return;\n begin();\n }\n\n function connect() {\n pinned = true;\n ensureConnecting();\n }\n\n function stop(code?: number, reason?: string) {\n wanted = false;\n generation++;\n clearTimeout(retryTimer);\n retryTimer = undefined;\n stopHeartbeat();\n unbindWindow();\n pending = [];\n if (ws) {\n const socket = ws;\n detach(socket, true);\n socket.close(code, reason);\n }\n }\n\n function close(code = 1000, reason?: string) {\n pinned = false;\n opened = false;\n stop(code, reason);\n set({ status: 'closed', attempt: 0 });\n rejectReady(new Error('WebSocket was closed'));\n }\n\n function reconnect() {\n if (!getImpl()) return;\n clearTimeout(retryTimer);\n retryTimer = undefined;\n stopHeartbeat();\n if (ws) {\n const socket = ws;\n detach(socket, true);\n socket.close(1000, 'reconnect');\n }\n begin();\n }\n\n function teardown() {\n if (refs > 0 || pinned) return;\n // Someone may be suspended on `ready`; let the attempt finish.\n if (ready && !ready.settled) return;\n stop();\n ready = null;\n opened = false;\n set({ status: 'idle', attempt: 0 });\n onTeardown?.();\n }\n\n function acquire() {\n refs++;\n clearTimeout(teardownTimer);\n if (snapshot.status === 'idle') ensureConnecting();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n if (--refs > 0) return;\n // Deferred so StrictMode's unmount/remount and route transitions don't churn the socket.\n clearTimeout(teardownTimer);\n teardownTimer = setTimeout(teardown, 0);\n };\n }\n\n return {\n url,\n get ready() {\n if (!getImpl()) {\n if (!unavailable) {\n unavailable = createDeferred();\n unavailable.reject(\n new Error('react-websocket: no WebSocket available here (server render?)')\n );\n }\n return unavailable.promise;\n }\n if (snapshot.status === 'idle' && !startScheduled) {\n // `ready` is read during render; start outside of it.\n startScheduled = true;\n queueMicrotask(() => {\n startScheduled = false;\n if (snapshot.status === 'idle') ensureConnecting();\n });\n }\n if (!ready) {\n ready = createDeferred();\n if (opened) ready.resolve();\n }\n return ready.promise;\n },\n get socket() {\n return ws;\n },\n subscribe(listener) {\n storeListeners.add(listener);\n return () => {\n storeListeners.delete(listener);\n };\n },\n getSnapshot: () => snapshot,\n on(type, listener) {\n // Wrap so the same function can be subscribed twice and unsubscribed independently.\n const entry = ((...args: unknown[]) =>\n (listener as (...a: unknown[]) => void)(...args)) as typeof listener;\n listeners[type].add(entry);\n return () => {\n listeners[type].delete(entry);\n };\n },\n send,\n connect,\n close,\n reconnect,\n acquire\n };\n}\n\n/**\n * Create a WebSocket client, usually at module level, to share across components.\n *\n * Nothing connects until a hook uses it, `ready` is read, or `connect()` is called.\n * It closes one tick after the last hook unmounts, unless `connect()` was called.\n *\n * @param url - A URL, or a function (sync or async) called before every connection\n * attempt, e.g. to put a fresh auth token in the URL on each reconnect.\n * @typeParam In - Type of incoming messages. Inferred from `options.schema` if given.\n * @typeParam Out - Type accepted by `send()`.\n *\n * @example\n * ```ts\n * type ChatIn = { user: string; text: string };\n * type ChatOut = { text: string };\n *\n * export const chat = createWebSocket<ChatIn, ChatOut>('wss://api.example.com/chat', { json: true });\n * ```\n */\nexport function createWebSocket<In = unknown, Out = unknown>(\n url: UrlSource,\n options?: WebSocketOptions<In, Out>\n): WebSocketClient<In, Out> {\n return createClient(url, options);\n}\n"],"mappings":";AA4NO,IAAM,eAAN,cAA2B,MAAM;AAAA;AAAA,EAE7B;AAAA;AAAA,EAEA;AAAA,EAET,YACE,SACA,MACA,SACA;AACA,UAAM,SAAS,SAAS,UAAU,SAAY,SAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;AAClF,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,SAAS,SAAS;AAAA,EACzB;AACF;;;AC/NA,IAAM,OAAO;AAEb,IAAM,qBAAqB;AAAA,EACzB,aAAa;AAAA,EACb,UAAU;AAAA,EACV,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,QAAQ;AACV;AAmBA,SAAS,iBAA2B;AAClC,MAAI;AACJ,MAAI;AACJ,QAAM,UAAU,IAAI,QAAc,CAAC,KAAK,QAAQ;AAC9C,cAAU;AACV,aAAS;AAAA,EACX,CAAC;AACD,UAA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O,MAAM;AAAA,IACf;AAAA,IACA,IAAI,SAAS;AACX,aAAO;AAAA,IACT;AAAA,IACA,UAAU,UAAU;AAClB,qBAAe,IAAI,QAAQ;AAC3B,aAAO,MAAM;AACX,uBAAe,OAAO,QAAQ;AAAA,MAChC;AAAA,IACF;AAAA,IACA,aAAa,MAAM;AAAA,IACnB,GAAG,MAAM,UAAU;AAEjB,YAAM,SAAS,IAAI,SAChB,SAAuC,GAAG,IAAI;AACjD,gBAAU,IAAI,EAAE,IAAI,KAAK;AACzB,aAAO,MAAM;AACX,kBAAU,IAAI,EAAE,OAAO,KAAK;AAAA,MAC9B;AAAA,IACF;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAqBO,SAAS,gBACd,KACA,SAC0B;AAC1B,SAAO,aAAa,KAAK,OAAO;AAClC;","names":[]}
package/dist/index.cjs ADDED
@@ -0,0 +1,129 @@
1
+ 'use client';
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
20
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
21
+
22
+ // src/index.ts
23
+ var src_exports = {};
24
+ __export(src_exports, {
25
+ useWebSocket: () => useWebSocket,
26
+ useWebSocketEvent: () => useWebSocketEvent,
27
+ useWebSocketStatus: () => useWebSocketStatus
28
+ });
29
+ module.exports = __toCommonJS(src_exports);
30
+ __reExport(src_exports, require("./core.cjs"), module.exports);
31
+
32
+ // src/react.ts
33
+ var import_react = require("react");
34
+ var import_core = require("./core.cjs");
35
+ var IDLE = Object.freeze({ status: "idle", lastMessage: void 0, attempt: 0 });
36
+ var idleSnapshot = () => IDLE;
37
+ var idleStatus = () => "idle";
38
+ var noopSubscribe = () => () => {
39
+ };
40
+ var noopSend = () => false;
41
+ var noop = () => {
42
+ };
43
+ var ON_TEARDOWN = /* @__PURE__ */ Symbol.for("react-websocket.onTeardown");
44
+ var registry = /* @__PURE__ */ new Map();
45
+ function sharedClient(url, options) {
46
+ if (typeof window === "undefined") return (0, import_core.createWebSocket)(url, options);
47
+ const key = `${url}\0${JSON.stringify(options.protocols ?? null)}`;
48
+ let client = registry.get(key);
49
+ if (!client) {
50
+ const created = (0, import_core.createWebSocket)(url, {
51
+ ...options,
52
+ [ON_TEARDOWN]: () => {
53
+ if (registry.get(key) === created) registry.delete(key);
54
+ }
55
+ });
56
+ registry.set(key, created);
57
+ client = created;
58
+ }
59
+ return client;
60
+ }
61
+ function useLatest(value) {
62
+ const ref = (0, import_react.useRef)(value);
63
+ (0, import_react.useInsertionEffect)(() => {
64
+ ref.current = value;
65
+ });
66
+ return ref;
67
+ }
68
+ function useHold(client, enabled) {
69
+ (0, import_react.useEffect)(() => {
70
+ if (client && enabled) return client.acquire();
71
+ }, [client, enabled]);
72
+ }
73
+ function useWebSocket(target, options = {}) {
74
+ const client = target == null ? null : typeof target === "string" ? sharedClient(target, options) : target;
75
+ const enabled = options.enabled ?? true;
76
+ const snapshot = (0, import_react.useSyncExternalStore)(
77
+ client ? client.subscribe : noopSubscribe,
78
+ client ? client.getSnapshot : idleSnapshot,
79
+ idleSnapshot
80
+ );
81
+ const handlers = useLatest(options);
82
+ (0, import_react.useEffect)(() => {
83
+ if (!client || !enabled) return;
84
+ const offs = [
85
+ client.on("open", (event) => handlers.current.onOpen?.(event)),
86
+ client.on("message", (message, event) => handlers.current.onMessage?.(message, event)),
87
+ client.on("close", (info) => handlers.current.onClose?.(info)),
88
+ client.on("error", (error) => handlers.current.onError?.(error))
89
+ ];
90
+ return () => offs.forEach((off) => off());
91
+ }, [client, enabled, handlers]);
92
+ useHold(client, enabled);
93
+ return {
94
+ ...snapshot,
95
+ send: client ? client.send : noopSend,
96
+ close: client ? client.close : noop,
97
+ reconnect: client ? client.reconnect : noop,
98
+ client
99
+ };
100
+ }
101
+ function useWebSocketEvent(client, type, listener) {
102
+ const latest = useLatest(listener);
103
+ (0, import_react.useEffect)(() => {
104
+ if (!client) return;
105
+ const off = client.on(type, ((...args) => latest.current(...args)));
106
+ const release = client.acquire();
107
+ return () => {
108
+ off();
109
+ release();
110
+ };
111
+ }, [client, type, latest]);
112
+ }
113
+ function useWebSocketStatus(client) {
114
+ const status = (0, import_react.useSyncExternalStore)(
115
+ client ? client.subscribe : noopSubscribe,
116
+ client ? () => client.getSnapshot().status : idleStatus,
117
+ idleStatus
118
+ );
119
+ useHold(client ?? null, true);
120
+ return status;
121
+ }
122
+ // Annotate the CommonJS export names for ESM import in node:
123
+ 0 && (module.exports = {
124
+ useWebSocket,
125
+ useWebSocketEvent,
126
+ useWebSocketStatus,
127
+ ...require("./core.cjs")
128
+ });
129
+ //# sourceMappingURL=index.cjs.map