@bymax-one/nest-realtime 1.2.15 → 1.2.17

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.
@@ -44,7 +44,7 @@ var NAMED_SSE_EVENTS = [
44
44
  PRESENCE_EVENT_NAMES.OFFLINE
45
45
  ];
46
46
  var BROWSER_SSE_EVENT_NAMES = ["message", "open", RESERVED_EVENT_NAMES.ERROR];
47
- function useRealtimeSse(opts) {
47
+ function useSseStreamState(opts) {
48
48
  const [connected, setConnected] = react.useState(false);
49
49
  const [events, setEvents] = react.useState([]);
50
50
  const [lastEvent, setLastEvent] = react.useState(void 0);
@@ -55,68 +55,120 @@ function useRealtimeSse(opts) {
55
55
  const attemptsRef = react.useRef(0);
56
56
  const timerRef = react.useRef(null);
57
57
  const lastIdRef = react.useRef(void 0);
58
- const extraEventNames = (opts.eventNames ?? []).filter((name) => name !== "" && !BROWSER_SSE_EVENT_NAMES.includes(name)).join("\n");
59
58
  const clearReconnectTimer = react.useCallback(() => {
60
59
  if (timerRef.current !== null) {
61
60
  clearTimeout(timerRef.current);
62
61
  timerRef.current = null;
63
62
  }
64
63
  }, []);
65
- const connect = react.useCallback(() => {
66
- if (opts.enabled === false) return;
67
- sourceRef.current?.close();
68
- clearReconnectTimer();
69
- if (lastIdRef.current?.url !== opts.url) lastIdRef.current = void 0;
70
- const source = new EventSource(withLastEventId(opts.url, lastIdRef.current?.id), {
71
- withCredentials: opts.withCredentials ?? false
72
- });
73
- sourceRef.current = source;
74
- source.onopen = () => {
75
- setConnected(true);
76
- setError(void 0);
77
- clearReconnectTimer();
78
- reconnectMsRef.current = validDelay(opts.reconnectInitialMs, 1e3);
79
- attemptsRef.current = 0;
80
- setReconnectAttempts(0);
81
- };
82
- source.onerror = () => {
83
- setConnected(false);
84
- setError(new Error("SSE connection error"));
85
- attemptsRef.current += 1;
86
- setReconnectAttempts(attemptsRef.current);
87
- if (opts.maxAttempts !== void 0 && attemptsRef.current >= opts.maxAttempts) {
88
- source.close();
89
- return;
90
- }
91
- clearReconnectTimer();
92
- const delay = nextBackoff(reconnectMsRef.current, validDelay(opts.reconnectMaxMs, 3e4));
93
- reconnectMsRef.current = delay;
94
- timerRef.current = setTimeout(connect, delay);
95
- };
96
- const handleEvent = (e) => {
97
- if (e.lastEventId !== "") lastIdRef.current = { url: opts.url, id: e.lastEventId };
98
- let data;
99
- try {
100
- data = JSON.parse(e.data);
101
- } catch {
102
- setError(new Error(`Malformed SSE payload on "${e.type}"`));
103
- return;
104
- }
105
- const entry = {
106
- type: e.type,
107
- data,
108
- id: e.lastEventId
109
- };
110
- setEvents((prev) => [...prev, entry].slice(-100));
111
- setLastEvent(entry);
112
- };
113
- source.onmessage = handleEvent;
114
- for (const name of NAMED_SSE_EVENTS) {
115
- source.addEventListener(name, handleEvent);
64
+ const context = react.useMemo(
65
+ () => ({
66
+ setConnected,
67
+ setError,
68
+ setReconnectAttempts,
69
+ setEvents,
70
+ setLastEvent,
71
+ sourceRef,
72
+ reconnectMsRef,
73
+ attemptsRef,
74
+ timerRef,
75
+ lastIdRef,
76
+ clearReconnectTimer
77
+ }),
78
+ [clearReconnectTimer]
79
+ );
80
+ return { view: { connected, events, lastEvent, error, reconnectAttempts }, context };
81
+ }
82
+ function joinEventNames(names) {
83
+ return (names ?? []).filter((name) => name !== "" && !BROWSER_SSE_EVENT_NAMES.includes(name)).join("\n");
84
+ }
85
+ function resetBackoff(context, reconnectInitialMs) {
86
+ context.reconnectMsRef.current = validDelay(reconnectInitialMs, 1e3);
87
+ context.attemptsRef.current = 0;
88
+ context.setReconnectAttempts(0);
89
+ }
90
+ function onOpenHandler(context, opts) {
91
+ return () => {
92
+ context.setConnected(true);
93
+ context.setError(void 0);
94
+ context.clearReconnectTimer();
95
+ resetBackoff(context, opts.reconnectInitialMs);
96
+ };
97
+ }
98
+ function onErrorHandler(context, opts, source, retry) {
99
+ return () => {
100
+ context.setConnected(false);
101
+ context.setError(new Error("SSE connection error"));
102
+ context.attemptsRef.current += 1;
103
+ context.setReconnectAttempts(context.attemptsRef.current);
104
+ if (opts.maxAttempts !== void 0 && context.attemptsRef.current >= opts.maxAttempts) {
105
+ source.close();
106
+ return;
116
107
  }
117
- for (const name of extraEventNames === "" ? [] : extraEventNames.split("\n")) {
118
- source.addEventListener(name, handleEvent);
108
+ context.clearReconnectTimer();
109
+ const delay = nextBackoff(
110
+ context.reconnectMsRef.current,
111
+ validDelay(opts.reconnectMaxMs, 3e4)
112
+ );
113
+ context.reconnectMsRef.current = delay;
114
+ context.timerRef.current = setTimeout(retry, delay);
115
+ };
116
+ }
117
+ function eventHandler(context, url) {
118
+ return (e) => {
119
+ if (e.lastEventId !== "") context.lastIdRef.current = { url, id: e.lastEventId };
120
+ let data;
121
+ try {
122
+ data = JSON.parse(e.data);
123
+ } catch {
124
+ context.setError(new Error(`Malformed SSE payload on "${e.type}"`));
125
+ return;
119
126
  }
127
+ const entry = {
128
+ type: e.type,
129
+ data,
130
+ id: e.lastEventId
131
+ };
132
+ context.setEvents((prev) => [...prev, entry].slice(-100));
133
+ context.setLastEvent(entry);
134
+ };
135
+ }
136
+ function openStream(context, opts, extraEventNames, retry) {
137
+ context.sourceRef.current?.close();
138
+ context.clearReconnectTimer();
139
+ if (context.lastIdRef.current?.url !== opts.url) context.lastIdRef.current = void 0;
140
+ const source = new EventSource(withLastEventId(opts.url, context.lastIdRef.current?.id), {
141
+ withCredentials: opts.withCredentials ?? false
142
+ });
143
+ context.sourceRef.current = source;
144
+ source.onopen = onOpenHandler(context, opts);
145
+ source.onerror = onErrorHandler(context, opts, source, retry);
146
+ const handleEvent = eventHandler(context, opts.url);
147
+ source.onmessage = handleEvent;
148
+ for (const name of NAMED_SSE_EVENTS) {
149
+ source.addEventListener(name, handleEvent);
150
+ }
151
+ for (const name of extraEventNames === "" ? [] : extraEventNames.split("\n")) {
152
+ source.addEventListener(name, handleEvent);
153
+ }
154
+ }
155
+ function useRealtimeSse(opts) {
156
+ const { view, context } = useSseStreamState(opts);
157
+ const extraEventNames = joinEventNames(opts.eventNames);
158
+ const connect = react.useCallback(() => {
159
+ if (opts.enabled === false) return;
160
+ openStream(
161
+ context,
162
+ {
163
+ url: opts.url,
164
+ withCredentials: opts.withCredentials,
165
+ reconnectInitialMs: opts.reconnectInitialMs,
166
+ reconnectMaxMs: opts.reconnectMaxMs,
167
+ maxAttempts: opts.maxAttempts
168
+ },
169
+ extraEventNames,
170
+ connect
171
+ );
120
172
  }, [
121
173
  opts.enabled,
122
174
  opts.url,
@@ -125,31 +177,55 @@ function useRealtimeSse(opts) {
125
177
  opts.reconnectMaxMs,
126
178
  opts.maxAttempts,
127
179
  extraEventNames,
128
- clearReconnectTimer
180
+ context
129
181
  ]);
130
182
  react.useEffect(() => {
131
183
  if (opts.enabled === false) return;
132
184
  connect();
133
185
  return () => {
134
- clearReconnectTimer();
135
- sourceRef.current?.close();
136
- sourceRef.current = null;
186
+ context.clearReconnectTimer();
187
+ context.sourceRef.current?.close();
188
+ context.sourceRef.current = null;
137
189
  };
138
- }, [connect, opts.enabled, clearReconnectTimer]);
190
+ }, [connect, opts.enabled, context]);
139
191
  const reconnect = react.useCallback(() => {
140
- reconnectMsRef.current = validDelay(opts.reconnectInitialMs, 1e3);
141
- attemptsRef.current = 0;
142
- setReconnectAttempts(0);
192
+ resetBackoff(context, opts.reconnectInitialMs);
143
193
  connect();
144
- }, [connect, opts.reconnectInitialMs]);
145
- return { connected, events, lastEvent, error, reconnectAttempts, reconnect };
194
+ }, [connect, opts.reconnectInitialMs, context]);
195
+ return { ...view, reconnect };
146
196
  }
147
- var MAX_EVENTS2 = 100;
148
- function useRealtimeWs(opts) {
149
- const [connected, setConnected] = react.useState(false);
150
- const [events, setEvents] = react.useState([]);
151
- const [lastEvent, setLastEvent] = react.useState(void 0);
152
- const [error, setError] = react.useState(void 0);
197
+ function asError(e) {
198
+ return e instanceof Error ? e : new Error(String(e));
199
+ }
200
+ function bindSocket(socket, sinks) {
201
+ socket.on("connect", () => {
202
+ sinks.setConnected(true);
203
+ sinks.setError(void 0);
204
+ });
205
+ socket.on("disconnect", () => sinks.setConnected(false));
206
+ socket.on("error", (e) => sinks.setError(asError(e)));
207
+ socket.onAny((eventName, payload) => {
208
+ const entry = {
209
+ type: eventName,
210
+ data: payload
211
+ };
212
+ sinks.setEvents((prev) => [...prev, entry].slice(-100));
213
+ sinks.setLastEvent(entry);
214
+ });
215
+ }
216
+ async function openSocket(url, path, ticket, token) {
217
+ const { io } = await import('socket.io-client');
218
+ const auth = {
219
+ ...ticket !== void 0 ? { ticket } : {},
220
+ ...token !== void 0 ? { token } : {}
221
+ };
222
+ return io(url, {
223
+ path: path ?? "/socket.io",
224
+ ...ticket !== void 0 || token !== void 0 ? { auth } : {},
225
+ withCredentials: true
226
+ });
227
+ }
228
+ function useSocketHandle() {
153
229
  const socketRef = react.useRef(null);
154
230
  const disposeSocket = react.useCallback(() => {
155
231
  const sock = socketRef.current;
@@ -159,6 +235,18 @@ function useRealtimeWs(opts) {
159
235
  }
160
236
  socketRef.current = null;
161
237
  }, []);
238
+ const emit = react.useCallback((event, data) => {
239
+ const sock = socketRef.current;
240
+ sock?.emit(event, data);
241
+ }, []);
242
+ return { socketRef, disposeSocket, emit };
243
+ }
244
+ function useRealtimeWs(opts) {
245
+ const [connected, setConnected] = react.useState(false);
246
+ const [events, setEvents] = react.useState([]);
247
+ const [lastEvent, setLastEvent] = react.useState(void 0);
248
+ const [error, setError] = react.useState(void 0);
249
+ const { socketRef, disposeSocket, emit } = useSocketHandle();
162
250
  const authTicket = opts.auth?.ticket;
163
251
  const authToken = opts.auth?.token;
164
252
  const connect = react.useCallback(async () => {
@@ -166,44 +254,18 @@ function useRealtimeWs(opts) {
166
254
  disposeSocket();
167
255
  setConnected(false);
168
256
  try {
169
- const { io } = await import('socket.io-client');
170
- const auth = {
171
- ...authTicket !== void 0 ? { ticket: authTicket } : {},
172
- ...authToken !== void 0 ? { token: authToken } : {}
173
- };
174
- const socket = io(opts.url, {
175
- path: opts.path ?? "/socket.io",
176
- ...authTicket !== void 0 || authToken !== void 0 ? { auth } : {},
177
- withCredentials: true
178
- });
257
+ const socket = await openSocket(opts.url, opts.path, authTicket, authToken);
179
258
  socketRef.current = socket;
180
- socket.on("connect", () => {
181
- setConnected(true);
182
- setError(void 0);
183
- });
184
- socket.on("disconnect", () => setConnected(false));
185
- socket.on("error", (e) => setError(e instanceof Error ? e : new Error(String(e))));
186
- socket.onAny((eventName, payload) => {
187
- const entry = {
188
- type: eventName,
189
- data: payload
190
- };
191
- setEvents((prev) => [...prev, entry].slice(-MAX_EVENTS2));
192
- setLastEvent(entry);
193
- });
259
+ bindSocket(socket, { setConnected, setError, setEvents, setLastEvent });
194
260
  } catch (e) {
195
- setError(e instanceof Error ? e : new Error(String(e)));
261
+ setError(asError(e));
196
262
  }
197
- }, [opts.enabled, opts.url, authTicket, authToken, opts.path, disposeSocket]);
263
+ }, [opts.enabled, opts.url, authTicket, authToken, opts.path, disposeSocket, socketRef]);
198
264
  react.useEffect(() => {
199
265
  if (opts.enabled === false) return;
200
266
  void connect();
201
267
  return () => disposeSocket();
202
268
  }, [connect, opts.enabled, disposeSocket]);
203
- const emit = react.useCallback((event, data) => {
204
- const sock = socketRef.current;
205
- sock?.emit(event, data);
206
- }, []);
207
269
  const reconnect = react.useCallback(() => {
208
270
  void connect();
209
271
  }, [connect]);
@@ -1,4 +1,4 @@
1
- import { createContext, useContext, useState, useEffect, useRef, useCallback } from 'react';
1
+ import { createContext, useContext, useState, useEffect, useCallback, useRef, useMemo } from 'react';
2
2
  import { jsx } from 'react/jsx-runtime';
3
3
 
4
4
  // src/shared/constants/reserved-events.constants.ts
@@ -42,7 +42,7 @@ var NAMED_SSE_EVENTS = [
42
42
  PRESENCE_EVENT_NAMES.OFFLINE
43
43
  ];
44
44
  var BROWSER_SSE_EVENT_NAMES = ["message", "open", RESERVED_EVENT_NAMES.ERROR];
45
- function useRealtimeSse(opts) {
45
+ function useSseStreamState(opts) {
46
46
  const [connected, setConnected] = useState(false);
47
47
  const [events, setEvents] = useState([]);
48
48
  const [lastEvent, setLastEvent] = useState(void 0);
@@ -53,68 +53,120 @@ function useRealtimeSse(opts) {
53
53
  const attemptsRef = useRef(0);
54
54
  const timerRef = useRef(null);
55
55
  const lastIdRef = useRef(void 0);
56
- const extraEventNames = (opts.eventNames ?? []).filter((name) => name !== "" && !BROWSER_SSE_EVENT_NAMES.includes(name)).join("\n");
57
56
  const clearReconnectTimer = useCallback(() => {
58
57
  if (timerRef.current !== null) {
59
58
  clearTimeout(timerRef.current);
60
59
  timerRef.current = null;
61
60
  }
62
61
  }, []);
63
- const connect = useCallback(() => {
64
- if (opts.enabled === false) return;
65
- sourceRef.current?.close();
66
- clearReconnectTimer();
67
- if (lastIdRef.current?.url !== opts.url) lastIdRef.current = void 0;
68
- const source = new EventSource(withLastEventId(opts.url, lastIdRef.current?.id), {
69
- withCredentials: opts.withCredentials ?? false
70
- });
71
- sourceRef.current = source;
72
- source.onopen = () => {
73
- setConnected(true);
74
- setError(void 0);
75
- clearReconnectTimer();
76
- reconnectMsRef.current = validDelay(opts.reconnectInitialMs, 1e3);
77
- attemptsRef.current = 0;
78
- setReconnectAttempts(0);
79
- };
80
- source.onerror = () => {
81
- setConnected(false);
82
- setError(new Error("SSE connection error"));
83
- attemptsRef.current += 1;
84
- setReconnectAttempts(attemptsRef.current);
85
- if (opts.maxAttempts !== void 0 && attemptsRef.current >= opts.maxAttempts) {
86
- source.close();
87
- return;
88
- }
89
- clearReconnectTimer();
90
- const delay = nextBackoff(reconnectMsRef.current, validDelay(opts.reconnectMaxMs, 3e4));
91
- reconnectMsRef.current = delay;
92
- timerRef.current = setTimeout(connect, delay);
93
- };
94
- const handleEvent = (e) => {
95
- if (e.lastEventId !== "") lastIdRef.current = { url: opts.url, id: e.lastEventId };
96
- let data;
97
- try {
98
- data = JSON.parse(e.data);
99
- } catch {
100
- setError(new Error(`Malformed SSE payload on "${e.type}"`));
101
- return;
102
- }
103
- const entry = {
104
- type: e.type,
105
- data,
106
- id: e.lastEventId
107
- };
108
- setEvents((prev) => [...prev, entry].slice(-100));
109
- setLastEvent(entry);
110
- };
111
- source.onmessage = handleEvent;
112
- for (const name of NAMED_SSE_EVENTS) {
113
- source.addEventListener(name, handleEvent);
62
+ const context = useMemo(
63
+ () => ({
64
+ setConnected,
65
+ setError,
66
+ setReconnectAttempts,
67
+ setEvents,
68
+ setLastEvent,
69
+ sourceRef,
70
+ reconnectMsRef,
71
+ attemptsRef,
72
+ timerRef,
73
+ lastIdRef,
74
+ clearReconnectTimer
75
+ }),
76
+ [clearReconnectTimer]
77
+ );
78
+ return { view: { connected, events, lastEvent, error, reconnectAttempts }, context };
79
+ }
80
+ function joinEventNames(names) {
81
+ return (names ?? []).filter((name) => name !== "" && !BROWSER_SSE_EVENT_NAMES.includes(name)).join("\n");
82
+ }
83
+ function resetBackoff(context, reconnectInitialMs) {
84
+ context.reconnectMsRef.current = validDelay(reconnectInitialMs, 1e3);
85
+ context.attemptsRef.current = 0;
86
+ context.setReconnectAttempts(0);
87
+ }
88
+ function onOpenHandler(context, opts) {
89
+ return () => {
90
+ context.setConnected(true);
91
+ context.setError(void 0);
92
+ context.clearReconnectTimer();
93
+ resetBackoff(context, opts.reconnectInitialMs);
94
+ };
95
+ }
96
+ function onErrorHandler(context, opts, source, retry) {
97
+ return () => {
98
+ context.setConnected(false);
99
+ context.setError(new Error("SSE connection error"));
100
+ context.attemptsRef.current += 1;
101
+ context.setReconnectAttempts(context.attemptsRef.current);
102
+ if (opts.maxAttempts !== void 0 && context.attemptsRef.current >= opts.maxAttempts) {
103
+ source.close();
104
+ return;
114
105
  }
115
- for (const name of extraEventNames === "" ? [] : extraEventNames.split("\n")) {
116
- source.addEventListener(name, handleEvent);
106
+ context.clearReconnectTimer();
107
+ const delay = nextBackoff(
108
+ context.reconnectMsRef.current,
109
+ validDelay(opts.reconnectMaxMs, 3e4)
110
+ );
111
+ context.reconnectMsRef.current = delay;
112
+ context.timerRef.current = setTimeout(retry, delay);
113
+ };
114
+ }
115
+ function eventHandler(context, url) {
116
+ return (e) => {
117
+ if (e.lastEventId !== "") context.lastIdRef.current = { url, id: e.lastEventId };
118
+ let data;
119
+ try {
120
+ data = JSON.parse(e.data);
121
+ } catch {
122
+ context.setError(new Error(`Malformed SSE payload on "${e.type}"`));
123
+ return;
117
124
  }
125
+ const entry = {
126
+ type: e.type,
127
+ data,
128
+ id: e.lastEventId
129
+ };
130
+ context.setEvents((prev) => [...prev, entry].slice(-100));
131
+ context.setLastEvent(entry);
132
+ };
133
+ }
134
+ function openStream(context, opts, extraEventNames, retry) {
135
+ context.sourceRef.current?.close();
136
+ context.clearReconnectTimer();
137
+ if (context.lastIdRef.current?.url !== opts.url) context.lastIdRef.current = void 0;
138
+ const source = new EventSource(withLastEventId(opts.url, context.lastIdRef.current?.id), {
139
+ withCredentials: opts.withCredentials ?? false
140
+ });
141
+ context.sourceRef.current = source;
142
+ source.onopen = onOpenHandler(context, opts);
143
+ source.onerror = onErrorHandler(context, opts, source, retry);
144
+ const handleEvent = eventHandler(context, opts.url);
145
+ source.onmessage = handleEvent;
146
+ for (const name of NAMED_SSE_EVENTS) {
147
+ source.addEventListener(name, handleEvent);
148
+ }
149
+ for (const name of extraEventNames === "" ? [] : extraEventNames.split("\n")) {
150
+ source.addEventListener(name, handleEvent);
151
+ }
152
+ }
153
+ function useRealtimeSse(opts) {
154
+ const { view, context } = useSseStreamState(opts);
155
+ const extraEventNames = joinEventNames(opts.eventNames);
156
+ const connect = useCallback(() => {
157
+ if (opts.enabled === false) return;
158
+ openStream(
159
+ context,
160
+ {
161
+ url: opts.url,
162
+ withCredentials: opts.withCredentials,
163
+ reconnectInitialMs: opts.reconnectInitialMs,
164
+ reconnectMaxMs: opts.reconnectMaxMs,
165
+ maxAttempts: opts.maxAttempts
166
+ },
167
+ extraEventNames,
168
+ connect
169
+ );
118
170
  }, [
119
171
  opts.enabled,
120
172
  opts.url,
@@ -123,31 +175,55 @@ function useRealtimeSse(opts) {
123
175
  opts.reconnectMaxMs,
124
176
  opts.maxAttempts,
125
177
  extraEventNames,
126
- clearReconnectTimer
178
+ context
127
179
  ]);
128
180
  useEffect(() => {
129
181
  if (opts.enabled === false) return;
130
182
  connect();
131
183
  return () => {
132
- clearReconnectTimer();
133
- sourceRef.current?.close();
134
- sourceRef.current = null;
184
+ context.clearReconnectTimer();
185
+ context.sourceRef.current?.close();
186
+ context.sourceRef.current = null;
135
187
  };
136
- }, [connect, opts.enabled, clearReconnectTimer]);
188
+ }, [connect, opts.enabled, context]);
137
189
  const reconnect = useCallback(() => {
138
- reconnectMsRef.current = validDelay(opts.reconnectInitialMs, 1e3);
139
- attemptsRef.current = 0;
140
- setReconnectAttempts(0);
190
+ resetBackoff(context, opts.reconnectInitialMs);
141
191
  connect();
142
- }, [connect, opts.reconnectInitialMs]);
143
- return { connected, events, lastEvent, error, reconnectAttempts, reconnect };
192
+ }, [connect, opts.reconnectInitialMs, context]);
193
+ return { ...view, reconnect };
144
194
  }
145
- var MAX_EVENTS2 = 100;
146
- function useRealtimeWs(opts) {
147
- const [connected, setConnected] = useState(false);
148
- const [events, setEvents] = useState([]);
149
- const [lastEvent, setLastEvent] = useState(void 0);
150
- const [error, setError] = useState(void 0);
195
+ function asError(e) {
196
+ return e instanceof Error ? e : new Error(String(e));
197
+ }
198
+ function bindSocket(socket, sinks) {
199
+ socket.on("connect", () => {
200
+ sinks.setConnected(true);
201
+ sinks.setError(void 0);
202
+ });
203
+ socket.on("disconnect", () => sinks.setConnected(false));
204
+ socket.on("error", (e) => sinks.setError(asError(e)));
205
+ socket.onAny((eventName, payload) => {
206
+ const entry = {
207
+ type: eventName,
208
+ data: payload
209
+ };
210
+ sinks.setEvents((prev) => [...prev, entry].slice(-100));
211
+ sinks.setLastEvent(entry);
212
+ });
213
+ }
214
+ async function openSocket(url, path, ticket, token) {
215
+ const { io } = await import('socket.io-client');
216
+ const auth = {
217
+ ...ticket !== void 0 ? { ticket } : {},
218
+ ...token !== void 0 ? { token } : {}
219
+ };
220
+ return io(url, {
221
+ path: path ?? "/socket.io",
222
+ ...ticket !== void 0 || token !== void 0 ? { auth } : {},
223
+ withCredentials: true
224
+ });
225
+ }
226
+ function useSocketHandle() {
151
227
  const socketRef = useRef(null);
152
228
  const disposeSocket = useCallback(() => {
153
229
  const sock = socketRef.current;
@@ -157,6 +233,18 @@ function useRealtimeWs(opts) {
157
233
  }
158
234
  socketRef.current = null;
159
235
  }, []);
236
+ const emit = useCallback((event, data) => {
237
+ const sock = socketRef.current;
238
+ sock?.emit(event, data);
239
+ }, []);
240
+ return { socketRef, disposeSocket, emit };
241
+ }
242
+ function useRealtimeWs(opts) {
243
+ const [connected, setConnected] = useState(false);
244
+ const [events, setEvents] = useState([]);
245
+ const [lastEvent, setLastEvent] = useState(void 0);
246
+ const [error, setError] = useState(void 0);
247
+ const { socketRef, disposeSocket, emit } = useSocketHandle();
160
248
  const authTicket = opts.auth?.ticket;
161
249
  const authToken = opts.auth?.token;
162
250
  const connect = useCallback(async () => {
@@ -164,44 +252,18 @@ function useRealtimeWs(opts) {
164
252
  disposeSocket();
165
253
  setConnected(false);
166
254
  try {
167
- const { io } = await import('socket.io-client');
168
- const auth = {
169
- ...authTicket !== void 0 ? { ticket: authTicket } : {},
170
- ...authToken !== void 0 ? { token: authToken } : {}
171
- };
172
- const socket = io(opts.url, {
173
- path: opts.path ?? "/socket.io",
174
- ...authTicket !== void 0 || authToken !== void 0 ? { auth } : {},
175
- withCredentials: true
176
- });
255
+ const socket = await openSocket(opts.url, opts.path, authTicket, authToken);
177
256
  socketRef.current = socket;
178
- socket.on("connect", () => {
179
- setConnected(true);
180
- setError(void 0);
181
- });
182
- socket.on("disconnect", () => setConnected(false));
183
- socket.on("error", (e) => setError(e instanceof Error ? e : new Error(String(e))));
184
- socket.onAny((eventName, payload) => {
185
- const entry = {
186
- type: eventName,
187
- data: payload
188
- };
189
- setEvents((prev) => [...prev, entry].slice(-MAX_EVENTS2));
190
- setLastEvent(entry);
191
- });
257
+ bindSocket(socket, { setConnected, setError, setEvents, setLastEvent });
192
258
  } catch (e) {
193
- setError(e instanceof Error ? e : new Error(String(e)));
259
+ setError(asError(e));
194
260
  }
195
- }, [opts.enabled, opts.url, authTicket, authToken, opts.path, disposeSocket]);
261
+ }, [opts.enabled, opts.url, authTicket, authToken, opts.path, disposeSocket, socketRef]);
196
262
  useEffect(() => {
197
263
  if (opts.enabled === false) return;
198
264
  void connect();
199
265
  return () => disposeSocket();
200
266
  }, [connect, opts.enabled, disposeSocket]);
201
- const emit = useCallback((event, data) => {
202
- const sock = socketRef.current;
203
- sock?.emit(event, data);
204
- }, []);
205
267
  const reconnect = useCallback(() => {
206
268
  void connect();
207
269
  }, [connect]);