ly-utils-lib 2.4.0 → 2.6.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/README.md CHANGED
@@ -87,6 +87,9 @@ import { exportExcel, importExcel } from 'ly-utils-lib/excel'
87
87
 
88
88
  // 只导入 PDF 模块
89
89
  import { captureToPDF, createPDF } from 'ly-utils-lib/pdf'
90
+
91
+ // 只导入 WebSocket 模块
92
+ import { createWebSocket, quickConnect } from 'ly-utils-lib/websocket'
90
93
  ```
91
94
 
92
95
  ## 模块文档
@@ -672,6 +675,117 @@ map.destroy()
672
675
  | `lonLatToXY(lon, lat)` | 经纬度转投影 | `lonLatToXY(116.39, 39.90)` |
673
676
  | `xyToLonLat(x, y)` | 投影转经纬度 | `xyToLonLat(x, y)` |
674
677
 
678
+ ### 🔌 WebSocket Module - WebSocket 工具
679
+
680
+ 提供简化的 WebSocket 连接、消息发送、心跳检测和重连机制。
681
+
682
+ ```typescript
683
+ import {
684
+ createWebSocket,
685
+ quickConnect,
686
+ WebSocketState,
687
+ } from 'ly-utils-lib/websocket'
688
+
689
+ // 方式 1: 使用 createWebSocket
690
+ const ws = createWebSocket({
691
+ url: 'echo.websocket.org',
692
+ autoReconnect: true,
693
+ reconnectAttempts: 3,
694
+ heartbeatInterval: 30000,
695
+ onOpen: (event) => console.log('Connected'),
696
+ onMessage: (data, event) => console.log('Received:', data),
697
+ onClose: (event) => console.log('Disconnected'),
698
+ onError: (event) => console.error('Error:', event),
699
+ onReconnect: (attempt) => console.log(`Reconnecting... (${attempt})`),
700
+ onHeartbeat: () => console.log('Heartbeat'),
701
+ })
702
+
703
+ // 发送消息
704
+ ws.send('Hello, WebSocket!')
705
+ ws.send({ type: 'message', content: 'Hello' })
706
+
707
+ // 检查连接状态
708
+ if (ws.isConnected()) {
709
+ console.log('Connected')
710
+ }
711
+
712
+ // 断开连接
713
+ ws.disconnect()
714
+
715
+ // 方式 2: 使用 quickConnect
716
+ const ws2 = quickConnect('echo.websocket.org', {
717
+ onMessage: (data) => console.log('Received:', data),
718
+ })
719
+
720
+ // 重新连接
721
+ ws.reconnect()
722
+ ```
723
+
724
+ **API 列表:**
725
+
726
+ #### 创建客户端
727
+
728
+ | 类/函数 | 说明 | 示例 |
729
+ | --------------------------------------------- | --------------------- | -------------------------------------- |
730
+ | `createWebSocket(options)` | 创建 WebSocket 客户端 | `createWebSocket({url: '...'})` |
731
+ | `quickConnect(url, handlers?)` | 快速连接 | `quickConnect('...')` |
732
+ | `WebSocketClient` | WebSocket 客户端类 | `new WebSocketClient({url: '...'})` |
733
+
734
+ #### 连接管理
735
+
736
+ | 类/函数 | 说明 | 示例 |
737
+ | --------------------------------------------- | --------------------- | -------------------------------------- |
738
+ | `connect()` | 连接 | `ws.connect()` |
739
+ | `disconnect()` | 断开连接 | `ws.disconnect()` |
740
+ | `reconnect()` | 重新连接 | `ws.reconnect()` |
741
+ | `getState()` | 获取连接状态 | `ws.getState()` |
742
+ | `isConnected()` | 是否已连接 | `ws.isConnected()` |
743
+ | `getInstance()` | 获取 WebSocket 实例 | `ws.getInstance()` |
744
+
745
+ #### 消息发送
746
+
747
+ | 类/函数 | 说明 | 示例 |
748
+ | --------------------------------------------- | --------------------- | -------------------------------------- |
749
+ | `send(data)` | 发送消息(异步) | `ws.send('Hello')` |
750
+ | `sendSync(data)` | 发送消息(同步) | `ws.sendSync('Hello')` |
751
+
752
+ #### 事件处理
753
+
754
+ | 类/函数 | 说明 | 示例 |
755
+ | --------------------------------------------- | --------------------- | -------------------------------------- |
756
+ | `on(event, handler)` | 设置事件处理器 | `ws.on('message', handler)` |
757
+ | `off(event, handler?)` | 移除事件处理器 | `ws.off('message', handler)` |
758
+
759
+ #### 配置选项
760
+
761
+ | 选项 | 说明 | 默认值 |
762
+ | --------------------------------------------- | --------------------- | -------------------------------------- |
763
+ | `url` | WebSocket 地址 | - |
764
+ | `protocol` | 协议 (ws/wss) | 自动检测 |
765
+ | `protocols` | 子协议 | [] |
766
+ | `autoReconnect` | 自动重连 | true |
767
+ | `reconnectAttempts` | 重连次数 | 3 |
768
+ | `reconnectInterval` | 重连间隔(ms) | 3000 |
769
+ | `heartbeatInterval` | 心跳间隔(ms) | 30000 |
770
+ | `heartbeatMessage` | 心跳消息 | 'ping' |
771
+ | `heartbeatTimeout` | 心跳超时(ms) | 5000 |
772
+ | `connectTimeout` | 连接超时(ms) | 10000 |
773
+ | `debug` | 调试日志 | true |
774
+
775
+ #### 事件处理器
776
+
777
+ | 事件 | 说明 | 示例 |
778
+ | --------------------------------------------- | --------------------- | -------------------------------------- |
779
+ | `onOpen` | 连接成功 | `onOpen: (event) => void` |
780
+ | `onMessage` | 接收消息 | `onMessage: (data, event) => void` |
781
+ | `onClose` | 连接关闭 | `onClose: (event) => void` |
782
+ | `onError` | 错误 | `onError: (event) => void` |
783
+ | `onReconnect` | 重连开始 | `onReconnect: (attempt) => void` |
784
+ | `onReconnectSuccess` | 重连成功 | `onReconnectSuccess: (attempt) => void`|
785
+ | `onReconnectFailed` | 重连失败 | `onReconnectFailed: () => void` |
786
+ | `onHeartbeat` | 心跳 | `onHeartbeat: () => void` |
787
+ | `onHeartbeatTimeout` | 心跳超时 | `onHeartbeatTimeout: () => void` |
788
+
675
789
  ### 💾 Storage Module - 存储处理
676
790
 
677
791
  基于浏览器 Web Storage API 和 Cookie(使用 [js-cookie](https://github.com/js-cookie/js-cookie) 封装),提供统一的存储操作功能。
@@ -0,0 +1,229 @@
1
+ /**
2
+ * WebSocket Module - WebSocket 工具
3
+ *
4
+ * 提供简化的 WebSocket 连接、消息发送、心跳检测和重连机制
5
+ */
6
+ /**
7
+ * WebSocket 连接状态
8
+ */
9
+ declare enum WebSocketState {
10
+ CONNECTING = 0,
11
+ OPEN = 1,
12
+ CLOSING = 2,
13
+ CLOSED = 3
14
+ }
15
+ /**
16
+ * WebSocket 配置选项
17
+ */
18
+ interface WebSocketOptions {
19
+ /** WebSocket 服务器地址 */
20
+ url: string;
21
+ /** 协议(wss:// 或 ws://),默认自动检测 */
22
+ protocol?: 'ws' | 'wss';
23
+ /** 子协议 */
24
+ protocols?: string | string[];
25
+ /** 是否自动重连,默认 true */
26
+ autoReconnect?: boolean;
27
+ /** 重连次数,默认 3 */
28
+ reconnectAttempts?: number;
29
+ /** 重连间隔(毫秒),默认 3000 */
30
+ reconnectInterval?: number;
31
+ /** 心跳检测间隔(毫秒),默认 30000 */
32
+ heartbeatInterval?: number;
33
+ /** 心跳消息内容,默认 'ping' */
34
+ heartbeatMessage?: string | object;
35
+ /** 心跳超时时间(毫秒),默认 5000 */
36
+ heartbeatTimeout?: number;
37
+ /** 连接超时时间(毫秒),默认 10000 */
38
+ connectTimeout?: number;
39
+ /** 是否记录日志,默认 true */
40
+ debug?: boolean;
41
+ }
42
+ /**
43
+ * WebSocket 消息类型
44
+ */
45
+ type WebSocketMessage = string | object | ArrayBuffer | Blob;
46
+ /**
47
+ * WebSocket 事件处理器
48
+ */
49
+ interface WebSocketEventHandlers {
50
+ /** 连接成功回调 */
51
+ onOpen?: (event: Event) => void;
52
+ /** 接收消息回调 */
53
+ onMessage?: (data: WebSocketMessage, event: MessageEvent) => void;
54
+ /** 连接关闭回调 */
55
+ onClose?: (event: CloseEvent) => void;
56
+ /** 错误回调 */
57
+ onError?: (event: Event) => void;
58
+ /** 重连开始回调 */
59
+ onReconnect?: (attempt: number) => void;
60
+ /** 重连成功回调 */
61
+ onReconnectSuccess?: (attempt: number) => void;
62
+ /** 重连失败回调 */
63
+ onReconnectFailed?: () => void;
64
+ /** 心跳回调 */
65
+ onHeartbeat?: () => void;
66
+ /** 心跳超时回调 */
67
+ onHeartbeatTimeout?: () => void;
68
+ }
69
+ /**
70
+ * WebSocket 实例接口
71
+ */
72
+ interface IWebSocketClient {
73
+ /** 连接 WebSocket */
74
+ connect(): void;
75
+ /** 断开连接 */
76
+ disconnect(): void;
77
+ /** 发送消息 */
78
+ send(data: WebSocketMessage): Promise<void>;
79
+ /** 发送消息(不带 Promise) */
80
+ sendSync(data: WebSocketMessage): void;
81
+ /** 获取连接状态 */
82
+ getState(): WebSocketState;
83
+ /** 是否已连接 */
84
+ isConnected(): boolean;
85
+ /** 获取 WebSocket 实例 */
86
+ getInstance(): WebSocket | null;
87
+ /** 设置事件处理器 */
88
+ on<K extends keyof WebSocketEventHandlers>(event: K, handler: WebSocketEventHandlers[K]): void;
89
+ /** 移除事件处理器 */
90
+ off<K extends keyof WebSocketEventHandlers>(event: K, handler?: WebSocketEventHandlers[K]): void;
91
+ /** 重新连接 */
92
+ reconnect(): void;
93
+ }
94
+ /**
95
+ * WebSocket 客户端类
96
+ */
97
+ declare class WebSocketClient implements IWebSocketClient {
98
+ private ws;
99
+ private options;
100
+ private handlers;
101
+ private reconnectTimer;
102
+ private heartbeatTimer;
103
+ private heartbeatTimeoutTimer;
104
+ private reconnectCount;
105
+ private isManualDisconnect;
106
+ private messageQueue;
107
+ private connectResolve;
108
+ private connectReject;
109
+ constructor(options: WebSocketOptions);
110
+ /**
111
+ * 连接 WebSocket
112
+ */
113
+ connect(): void;
114
+ /**
115
+ * 断开连接
116
+ */
117
+ disconnect(): void;
118
+ /**
119
+ * 发送消息(异步)
120
+ */
121
+ send(data: WebSocketMessage): Promise<void>;
122
+ /**
123
+ * 发送消息(同步)
124
+ */
125
+ sendSync(data: WebSocketMessage): void;
126
+ /**
127
+ * 获取连接状态
128
+ */
129
+ getState(): WebSocketState;
130
+ /**
131
+ * 是否已连接
132
+ */
133
+ isConnected(): boolean;
134
+ /**
135
+ * 获取 WebSocket 实例
136
+ */
137
+ getInstance(): WebSocket | null;
138
+ /**
139
+ * 设置事件处理器
140
+ */
141
+ on<K extends keyof WebSocketEventHandlers>(event: K, handler: WebSocketEventHandlers[K]): void;
142
+ /**
143
+ * 移除事件处理器
144
+ */
145
+ off<K extends keyof WebSocketEventHandlers>(event: K, handler?: WebSocketEventHandlers[K]): void;
146
+ /**
147
+ * 重新连接
148
+ */
149
+ reconnect(): void;
150
+ /**
151
+ * 设置事件处理器
152
+ */
153
+ private setupEventHandlers;
154
+ /**
155
+ * 尝试重连
156
+ */
157
+ private attemptReconnect;
158
+ /**
159
+ * 启动心跳
160
+ */
161
+ private startHeartbeat;
162
+ /**
163
+ * 停止心跳
164
+ */
165
+ private stopHeartbeat;
166
+ /**
167
+ * 清理资源
168
+ */
169
+ private cleanup;
170
+ /**
171
+ * 处理错误
172
+ */
173
+ private handleError;
174
+ /**
175
+ * 日志输出
176
+ */
177
+ private log;
178
+ }
179
+ /**
180
+ * 创建 WebSocket 客户端
181
+ * @param options - 配置选项
182
+ * @returns WebSocket 客户端实例
183
+ * @example
184
+ * ```ts
185
+ * const ws = createWebSocket({
186
+ * url: 'echo.websocket.org',
187
+ * autoReconnect: true,
188
+ * onMessage: (data) => console.log('Received:', data)
189
+ * })
190
+ *
191
+ * ws.send('Hello, WebSocket!')
192
+ * ```
193
+ */
194
+ declare function createWebSocket(options: WebSocketOptions): IWebSocketClient;
195
+ /**
196
+ * 快速连接 WebSocket
197
+ * @param url - WebSocket 服务器地址
198
+ * @param handlers - 事件处理器
199
+ * @returns WebSocket 客户端实例
200
+ * @example
201
+ * ```ts
202
+ * const ws = quickConnect('echo.websocket.org', {
203
+ * onMessage: (data) => console.log('Received:', data)
204
+ * })
205
+ * ```
206
+ */
207
+ declare function quickConnect(url: string, handlers?: WebSocketEventHandlers): IWebSocketClient;
208
+ declare const _default: {
209
+ WebSocketClient: typeof WebSocketClient;
210
+ createWebSocket: typeof createWebSocket;
211
+ quickConnect: typeof quickConnect;
212
+ WebSocketState: typeof WebSocketState;
213
+ };
214
+
215
+ type index_IWebSocketClient = IWebSocketClient;
216
+ type index_WebSocketClient = WebSocketClient;
217
+ declare const index_WebSocketClient: typeof WebSocketClient;
218
+ type index_WebSocketEventHandlers = WebSocketEventHandlers;
219
+ type index_WebSocketMessage = WebSocketMessage;
220
+ type index_WebSocketOptions = WebSocketOptions;
221
+ type index_WebSocketState = WebSocketState;
222
+ declare const index_WebSocketState: typeof WebSocketState;
223
+ declare const index_createWebSocket: typeof createWebSocket;
224
+ declare const index_quickConnect: typeof quickConnect;
225
+ declare namespace index {
226
+ export { type index_IWebSocketClient as IWebSocketClient, index_WebSocketClient as WebSocketClient, type index_WebSocketEventHandlers as WebSocketEventHandlers, type index_WebSocketMessage as WebSocketMessage, type index_WebSocketOptions as WebSocketOptions, index_WebSocketState as WebSocketState, index_createWebSocket as createWebSocket, _default as default, index_quickConnect as quickConnect };
227
+ }
228
+
229
+ export { type IWebSocketClient as I, WebSocketClient as W, _default as _, type WebSocketEventHandlers as a, type WebSocketMessage as b, type WebSocketOptions as c, WebSocketState as d, createWebSocket as e, index as i, quickConnect as q };
@@ -0,0 +1,229 @@
1
+ /**
2
+ * WebSocket Module - WebSocket 工具
3
+ *
4
+ * 提供简化的 WebSocket 连接、消息发送、心跳检测和重连机制
5
+ */
6
+ /**
7
+ * WebSocket 连接状态
8
+ */
9
+ declare enum WebSocketState {
10
+ CONNECTING = 0,
11
+ OPEN = 1,
12
+ CLOSING = 2,
13
+ CLOSED = 3
14
+ }
15
+ /**
16
+ * WebSocket 配置选项
17
+ */
18
+ interface WebSocketOptions {
19
+ /** WebSocket 服务器地址 */
20
+ url: string;
21
+ /** 协议(wss:// 或 ws://),默认自动检测 */
22
+ protocol?: 'ws' | 'wss';
23
+ /** 子协议 */
24
+ protocols?: string | string[];
25
+ /** 是否自动重连,默认 true */
26
+ autoReconnect?: boolean;
27
+ /** 重连次数,默认 3 */
28
+ reconnectAttempts?: number;
29
+ /** 重连间隔(毫秒),默认 3000 */
30
+ reconnectInterval?: number;
31
+ /** 心跳检测间隔(毫秒),默认 30000 */
32
+ heartbeatInterval?: number;
33
+ /** 心跳消息内容,默认 'ping' */
34
+ heartbeatMessage?: string | object;
35
+ /** 心跳超时时间(毫秒),默认 5000 */
36
+ heartbeatTimeout?: number;
37
+ /** 连接超时时间(毫秒),默认 10000 */
38
+ connectTimeout?: number;
39
+ /** 是否记录日志,默认 true */
40
+ debug?: boolean;
41
+ }
42
+ /**
43
+ * WebSocket 消息类型
44
+ */
45
+ type WebSocketMessage = string | object | ArrayBuffer | Blob;
46
+ /**
47
+ * WebSocket 事件处理器
48
+ */
49
+ interface WebSocketEventHandlers {
50
+ /** 连接成功回调 */
51
+ onOpen?: (event: Event) => void;
52
+ /** 接收消息回调 */
53
+ onMessage?: (data: WebSocketMessage, event: MessageEvent) => void;
54
+ /** 连接关闭回调 */
55
+ onClose?: (event: CloseEvent) => void;
56
+ /** 错误回调 */
57
+ onError?: (event: Event) => void;
58
+ /** 重连开始回调 */
59
+ onReconnect?: (attempt: number) => void;
60
+ /** 重连成功回调 */
61
+ onReconnectSuccess?: (attempt: number) => void;
62
+ /** 重连失败回调 */
63
+ onReconnectFailed?: () => void;
64
+ /** 心跳回调 */
65
+ onHeartbeat?: () => void;
66
+ /** 心跳超时回调 */
67
+ onHeartbeatTimeout?: () => void;
68
+ }
69
+ /**
70
+ * WebSocket 实例接口
71
+ */
72
+ interface IWebSocketClient {
73
+ /** 连接 WebSocket */
74
+ connect(): void;
75
+ /** 断开连接 */
76
+ disconnect(): void;
77
+ /** 发送消息 */
78
+ send(data: WebSocketMessage): Promise<void>;
79
+ /** 发送消息(不带 Promise) */
80
+ sendSync(data: WebSocketMessage): void;
81
+ /** 获取连接状态 */
82
+ getState(): WebSocketState;
83
+ /** 是否已连接 */
84
+ isConnected(): boolean;
85
+ /** 获取 WebSocket 实例 */
86
+ getInstance(): WebSocket | null;
87
+ /** 设置事件处理器 */
88
+ on<K extends keyof WebSocketEventHandlers>(event: K, handler: WebSocketEventHandlers[K]): void;
89
+ /** 移除事件处理器 */
90
+ off<K extends keyof WebSocketEventHandlers>(event: K, handler?: WebSocketEventHandlers[K]): void;
91
+ /** 重新连接 */
92
+ reconnect(): void;
93
+ }
94
+ /**
95
+ * WebSocket 客户端类
96
+ */
97
+ declare class WebSocketClient implements IWebSocketClient {
98
+ private ws;
99
+ private options;
100
+ private handlers;
101
+ private reconnectTimer;
102
+ private heartbeatTimer;
103
+ private heartbeatTimeoutTimer;
104
+ private reconnectCount;
105
+ private isManualDisconnect;
106
+ private messageQueue;
107
+ private connectResolve;
108
+ private connectReject;
109
+ constructor(options: WebSocketOptions);
110
+ /**
111
+ * 连接 WebSocket
112
+ */
113
+ connect(): void;
114
+ /**
115
+ * 断开连接
116
+ */
117
+ disconnect(): void;
118
+ /**
119
+ * 发送消息(异步)
120
+ */
121
+ send(data: WebSocketMessage): Promise<void>;
122
+ /**
123
+ * 发送消息(同步)
124
+ */
125
+ sendSync(data: WebSocketMessage): void;
126
+ /**
127
+ * 获取连接状态
128
+ */
129
+ getState(): WebSocketState;
130
+ /**
131
+ * 是否已连接
132
+ */
133
+ isConnected(): boolean;
134
+ /**
135
+ * 获取 WebSocket 实例
136
+ */
137
+ getInstance(): WebSocket | null;
138
+ /**
139
+ * 设置事件处理器
140
+ */
141
+ on<K extends keyof WebSocketEventHandlers>(event: K, handler: WebSocketEventHandlers[K]): void;
142
+ /**
143
+ * 移除事件处理器
144
+ */
145
+ off<K extends keyof WebSocketEventHandlers>(event: K, handler?: WebSocketEventHandlers[K]): void;
146
+ /**
147
+ * 重新连接
148
+ */
149
+ reconnect(): void;
150
+ /**
151
+ * 设置事件处理器
152
+ */
153
+ private setupEventHandlers;
154
+ /**
155
+ * 尝试重连
156
+ */
157
+ private attemptReconnect;
158
+ /**
159
+ * 启动心跳
160
+ */
161
+ private startHeartbeat;
162
+ /**
163
+ * 停止心跳
164
+ */
165
+ private stopHeartbeat;
166
+ /**
167
+ * 清理资源
168
+ */
169
+ private cleanup;
170
+ /**
171
+ * 处理错误
172
+ */
173
+ private handleError;
174
+ /**
175
+ * 日志输出
176
+ */
177
+ private log;
178
+ }
179
+ /**
180
+ * 创建 WebSocket 客户端
181
+ * @param options - 配置选项
182
+ * @returns WebSocket 客户端实例
183
+ * @example
184
+ * ```ts
185
+ * const ws = createWebSocket({
186
+ * url: 'echo.websocket.org',
187
+ * autoReconnect: true,
188
+ * onMessage: (data) => console.log('Received:', data)
189
+ * })
190
+ *
191
+ * ws.send('Hello, WebSocket!')
192
+ * ```
193
+ */
194
+ declare function createWebSocket(options: WebSocketOptions): IWebSocketClient;
195
+ /**
196
+ * 快速连接 WebSocket
197
+ * @param url - WebSocket 服务器地址
198
+ * @param handlers - 事件处理器
199
+ * @returns WebSocket 客户端实例
200
+ * @example
201
+ * ```ts
202
+ * const ws = quickConnect('echo.websocket.org', {
203
+ * onMessage: (data) => console.log('Received:', data)
204
+ * })
205
+ * ```
206
+ */
207
+ declare function quickConnect(url: string, handlers?: WebSocketEventHandlers): IWebSocketClient;
208
+ declare const _default: {
209
+ WebSocketClient: typeof WebSocketClient;
210
+ createWebSocket: typeof createWebSocket;
211
+ quickConnect: typeof quickConnect;
212
+ WebSocketState: typeof WebSocketState;
213
+ };
214
+
215
+ type index_IWebSocketClient = IWebSocketClient;
216
+ type index_WebSocketClient = WebSocketClient;
217
+ declare const index_WebSocketClient: typeof WebSocketClient;
218
+ type index_WebSocketEventHandlers = WebSocketEventHandlers;
219
+ type index_WebSocketMessage = WebSocketMessage;
220
+ type index_WebSocketOptions = WebSocketOptions;
221
+ type index_WebSocketState = WebSocketState;
222
+ declare const index_WebSocketState: typeof WebSocketState;
223
+ declare const index_createWebSocket: typeof createWebSocket;
224
+ declare const index_quickConnect: typeof quickConnect;
225
+ declare namespace index {
226
+ export { type index_IWebSocketClient as IWebSocketClient, index_WebSocketClient as WebSocketClient, type index_WebSocketEventHandlers as WebSocketEventHandlers, type index_WebSocketMessage as WebSocketMessage, type index_WebSocketOptions as WebSocketOptions, index_WebSocketState as WebSocketState, index_createWebSocket as createWebSocket, _default as default, index_quickConnect as quickConnect };
227
+ }
228
+
229
+ export { type IWebSocketClient as I, WebSocketClient as W, _default as _, type WebSocketEventHandlers as a, type WebSocketMessage as b, type WebSocketOptions as c, WebSocketState as d, createWebSocket as e, index as i, quickConnect as q };