message-nexus 1.0.1 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # message-nexus
2
2
 
3
- 一个统一、类型安全、支持多种传输协议的跨上下文消息通信库。
3
+ A unified, type-safe cross-context message communication library supporting multiple transport protocols.
4
4
 
5
- ## 安装
5
+ ## Installation
6
6
 
7
7
  ```bash
8
8
  npm install message-nexus
@@ -10,144 +10,150 @@ npm install message-nexus
10
10
  pnpm add message-nexus
11
11
  ```
12
12
 
13
- ## 特性
13
+ ## Features
14
14
 
15
- - **统一接口**: 支持 Mitt(进程内)、PostMessageiframe/window 间)、BroadcastChannel(跨标签页)、WebSocket(网络通信)
16
- - **类型安全**: 完整的 TypeScript 支持,泛型类型推断
17
- - **请求-响应模式**: Promise 风格的异步通信,内置超时保护
18
- - **自动重连**: WebSocket 自动重连机制,支持指数退避
19
- - **消息队列**: 离线消息缓存,连接恢复后自动发送
20
- - **重试机制**: 请求失败自动重试,可配置重试次数和延迟
21
- - **消息验证**: 运行时消息格式验证,防止非法消息
22
- - **监控指标**: 内置消息统计和性能监控
23
- - **结构化日志**: 支持自定义日志处理器,便于调试和生产监控
24
- - **资源管理**: 所有 Driver 支持 `destroy()` 方法,正确清理资源
15
+ - **Unified Interface**: Supports Mitt (in-process), PostMessage (iframe/window), BroadcastChannel (cross-tab), and WebSocket (network communication)
16
+ - **JSON-RPC 2.0 Compliance**: Strict adherence to the JSON-RPC 2.0 specification for standardized communication
17
+ - **Envelope Pattern**: Extensible message envelope containing routing information (from, to) and metadata
18
+ - **Type Safety**: Full TypeScript support with generic type inference
19
+ - **Request-Response Pattern**: Promise-style asynchronous communication with built-in timeout protection
20
+ - **Auto Reconnect**: WebSocket automatic reconnection mechanism with exponential backoff support
21
+ - **Message Queue**: Offline message caching, automatically sent after connection recovery
22
+ - **Retry Mechanism**: Automatic retry on request failure, configurable retry counts and delays
23
+ - **Message Validation**: Runtime message format validation to prevent illegal messages
24
+ - **Monitoring Metrics**: Built-in message statistics and performance monitoring
25
+ - **Structured Logging**: Supports custom log handlers for easy debugging and production monitoring
26
+ - **Resource Management**: All drivers support the `destroy()` method to properly clean up resources.
25
27
 
26
- ## 快速开始
28
+ ## Quick Start
27
29
 
28
- ### 1. 进程内通信(Mitt
30
+ ### 1. In-Process Communication (Mitt)
29
31
 
30
32
  ```typescript
31
33
  import MessageNexus, { MittDriver, createEmitter } from 'message-nexus'
32
34
 
33
- // 共享的 emitter
35
+ // Shared emitter
34
36
  const emitter = createEmitter()
35
37
 
36
38
  const driver = new MittDriver(emitter)
37
39
  const nexus = new MessageNexus(driver)
38
40
 
39
- // 发送请求
40
- const response = await nexus.request('GET_DATA', { id: 123 })
41
+ // Send request
42
+ const response = await nexus.invoke('GET_DATA', { id: 123 })
41
43
  console.log(response)
42
44
 
43
- // 监听命令
45
+ // Send one-way notification
46
+ nexus.notify('UPDATE_STATUS', { status: 'active' })
47
+
48
+ // Listen for commands
44
49
  const receiverDriver = new MittDriver(emitter)
45
50
  const receiverNexus = new MessageNexus(receiverDriver)
46
- const unsubscribe = receiverNexus.onCommand((data) => {
47
- if (data.type === 'GET_DATA') {
48
- receiverNexus.reply(data.id, { name: 'test', value: 42 })
49
- }
51
+ const unsubscribe = receiverNexus.handle('GET_DATA', (params, context) => {
52
+ return { name: 'test', value: 42 }
53
+ })
54
+
55
+ // Listen for notifications
56
+ const unsubscribeNotify = receiverNexus.onNotification('UPDATE_STATUS', (params, context) => {
57
+ console.log('Notification received:', params)
50
58
  })
51
59
  ```
52
60
 
53
- ### 2. iframe/Window 通信(PostMessage
61
+ ### 2. iframe/Window Communication (PostMessage)
54
62
 
55
63
  ```typescript
56
64
  import MessageNexus, { PostMessageDriver } from 'message-nexus'
57
65
 
58
- // 发送方
66
+ // Sender
59
67
  const driver = new PostMessageDriver(window.parent, 'https://example.com')
60
68
  const nexus = new MessageNexus(driver)
61
69
 
62
- const response = await nexus.request('PING')
70
+ const response = await nexus.invoke('PING')
63
71
  console.log('Pong:', response)
64
72
 
65
- // 接收方
73
+ // Receiver
66
74
  const iframeDriver = new PostMessageDriver(iframe.contentWindow, 'https://example.com')
67
75
  const iframeNexus = new MessageNexus(iframeDriver)
68
76
 
69
- iframeNexus.onCommand((data) => {
70
- if (data.type === 'PING') {
71
- iframeNexus.reply(data.id, { time: Date.now() })
72
- }
77
+ iframeNexus.handle('PING', (params, context) => {
78
+ return { time: Date.now() }
73
79
  })
74
80
  ```
75
81
 
76
- ### 3. 跨标签页通信(BroadcastChannel
82
+ ### 3. Cross-Tab Communication (BroadcastChannel)
77
83
 
78
84
  ```typescript
79
85
  import MessageNexus, { BroadcastDriver } from 'message-nexus'
80
86
 
81
- // 创建 BroadcastDriver,指定频道名称
87
+ // Create BroadcastDriver, specifying the channel name
82
88
  const driver = new BroadcastDriver({ channel: 'my-app-channel' })
83
89
  const nexus = new MessageNexus(driver)
84
90
 
85
- // 监听命令
86
- nexus.onCommand((data) => {
87
- console.log('Received:', data.type, data.payload)
88
- nexus.reply(data.id, { result: 'success' })
91
+ // Listen for commands
92
+ nexus.handle('SYNC_STATE', (params, context) => {
93
+ console.log('Received:', params)
94
+ return { result: 'success' }
89
95
  })
90
96
 
91
- // 发送请求(会在所有同频道的标签页中广播)
92
- const response = await nexus.request({
93
- type: 'SYNC_STATE',
94
- payload: { state: '...' },
97
+ // Send request (will be broadcast to all tabs on the same channel)
98
+ const response = await nexus.invoke({
99
+ method: 'SYNC_STATE',
100
+ params: { state: '...' },
95
101
  })
96
102
 
97
- // 接收方
103
+ // Receiver
98
104
  const receiverDriver = new BroadcastDriver({ channel: 'my-app-channel' })
99
105
  const receiverNexus = new MessageNexus(receiverDriver)
100
- receiverNexus.onCommand((data) => {
101
- console.log('Received:', data.type, data.payload)
102
- receiverNexus.reply(data.id, { result: 'success' })
106
+ receiverNexus.handle('SYNC_STATE', (params, context) => {
107
+ console.log('Received:', params)
108
+ return { result: 'success' }
103
109
  })
104
110
  ```
105
111
 
106
- ### 4. WebSocket 通信
112
+ ### 4. WebSocket Communication
107
113
 
108
114
  ```typescript
109
115
  import MessageNexus, { WebSocketDriver } from 'message-nexus'
110
116
 
111
- // 自动重连配置
117
+ // Automatic reconnection configuration
112
118
  const driver = new WebSocketDriver({
113
119
  url: 'wss://api.example.com/ws',
114
120
  reconnect: {
115
- maxRetries: 5, // 最大重试次数
116
- retryInterval: 3000, // 重试间隔(毫秒)
121
+ maxRetries: 5, // Maximum retry count
122
+ retryInterval: 3000, // Retry interval (milliseconds)
117
123
  },
118
124
  })
119
125
 
120
126
  const nexus = new MessageNexus(driver)
121
127
 
122
- // 发送请求
123
- const response = await nexus.request({
124
- type: 'GET_USER',
125
- payload: { userId: 123 },
128
+ // Send request
129
+ const response = await nexus.invoke({
130
+ method: 'GET_USER',
131
+ params: { userId: 123 },
126
132
  timeout: 5000,
127
- retryCount: 3, // 失败重试 3
128
- retryDelay: 1000, // 重试延迟
133
+ retryCount: 3, // Retry 3 times on failure
134
+ retryDelay: 1000, // Retry delay
129
135
  })
130
136
 
131
- // 接收方
137
+ // Receiver
132
138
  const receiverDriver = new WebSocketDriver({
133
139
  url: 'wss://api.example.com/ws',
134
140
  reconnect: {
135
- maxRetries: 5, // 最大重试次数
136
- retryInterval: 3000, // 重试间隔(毫秒)
141
+ maxRetries: 5, // Maximum retry count
142
+ retryInterval: 3000, // Retry interval (milliseconds)
137
143
  },
138
144
  })
139
145
  const receiverNexus = new MessageNexus(receiverDriver)
140
- receiverNexus.onCommand((data) => {
141
- console.log('Received:', data.type, data.payload)
142
- receiverNexus.reply(data.id, { result: 'success' })
146
+ receiverNexus.handle('SYNC_STATE', (params, context) => {
147
+ console.log('Received:', params)
148
+ return { result: 'success' }
143
149
  })
144
150
  ```
145
151
 
146
- ## API 文档
152
+ ## API Documentation
147
153
 
148
154
  ### MessageNexus
149
155
 
150
- #### 构造函数
156
+ #### Constructor
151
157
 
152
158
  ```typescript
153
159
  new MessageNexus<RequestPayload, ResponsePayload>(
@@ -158,44 +164,44 @@ new MessageNexus<RequestPayload, ResponsePayload>(
158
164
 
159
165
  **Options:**
160
166
 
161
- | 参数 | 类型 | 默认值 | 说明 |
162
- | ---------- | ------ | -------------- | --------------------- |
163
- | instanceId | string | auto-generated | 实例 ID,用于消息路由 |
164
- | timeout | number | 10000 | 请求超时时间(毫秒) |
165
- | logger | Logger | new Logger() | 日志实例 |
167
+ | Parameter | Type | Default Value | Description |
168
+ | ---------- | ------ | -------------- | ------------------------------------- |
169
+ | instanceId | string | auto-generated | Instance ID, used for message routing |
170
+ | timeout | number | 10000 | Request timeout (milliseconds) |
171
+ | logger | Logger | new Logger() | Logger instance |
166
172
 
167
- #### 方法
173
+ #### Methods
168
174
 
169
- ##### request()
175
+ ##### invoke()
170
176
 
171
- 发送请求并等待响应。
177
+ Send request and wait for response.
172
178
 
173
179
  ```typescript
174
- nexus.request(typeOrOptions: string | RequestOptions): Promise<ResponsePayload>
180
+ nexus.invoke<T>(methodOrOptions: string | InvokeOptions): Promise<T>
175
181
  ```
176
182
 
177
183
  **Options:**
178
184
 
179
- | 参数 | 类型 | 必填 | 说明 |
180
- | ---------- | ----------------------- | ---- | -------------------- |
181
- | type | string | | 消息类型 |
182
- | payload | unknown | | 请求数据 |
183
- | to | string | | 目标实例 ID |
184
- | metadata | Record<string, unknown> | | 元数据 |
185
- | timeout | number | | 超时时间(覆盖全局) |
186
- | retryCount | number | | 失败重试次数 |
187
- | retryDelay | number | | 重试延迟(毫秒) |
185
+ | Parameter | Type | Required | Description |
186
+ | ---------- | ----------------------- | -------- | ---------------------------- |
187
+ | method | string | Yes | Message method |
188
+ | params | unknown | No | Request data |
189
+ | to | string | No | Target instance ID |
190
+ | metadata | Record<string, unknown> | No | Metadata |
191
+ | timeout | number | No | Timeout (overrides global) |
192
+ | retryCount | number | No | Number of retries on failure |
193
+ | retryDelay | number | No | Retry delay (milliseconds) |
188
194
 
189
- **示例:**
195
+ **Example:**
190
196
 
191
197
  ```typescript
192
- // 简单请求
193
- const result = await nexus.request('FETCH_DATA')
198
+ // Simple request
199
+ const result = await nexus.invoke('FETCH_DATA')
194
200
 
195
- // 完整配置
196
- const result = await nexus.request({
197
- type: 'FETCH_DATA',
198
- payload: { id: 123 },
201
+ // Full configuration
202
+ const result = await nexus.invoke({
203
+ method: 'FETCH_DATA',
204
+ params: { id: 123 },
199
205
  to: 'target-instance',
200
206
  timeout: 5000,
201
207
  retryCount: 3,
@@ -203,87 +209,131 @@ const result = await nexus.request({
203
209
  })
204
210
  ```
205
211
 
206
- ##### onCommand()
212
+ ##### notify()
207
213
 
208
- 注册消息处理器。
214
+ Send a one-way notification (Fire-and-Forget). Does not wait for a response and does not generate an ID. Complies with JSON-RPC 2.0 Notification specification.
209
215
 
210
216
  ```typescript
211
- nexus.onCommand(handler: (data: CommandMessage) => void): () => void
217
+ nexus.notify(methodOrOptions: string | Omit<InvokeOptions, 'timeout' | 'retryCount' | 'retryDelay'>): void
212
218
  ```
213
219
 
214
- **返回值:** 取消监听的函数
220
+ **Options:**
221
+
222
+ | Parameter | Type | Required | Description |
223
+ | --------- | ----------------------- | -------- | ------------------- |
224
+ | method | string | Yes | Notification method |
225
+ | params | unknown | No | Notification data |
226
+ | to | string | No | Target instance ID |
227
+ | metadata | Record<string, unknown> | No | Metadata |
215
228
 
216
- **示例:**
229
+ **Example:**
217
230
 
218
231
  ```typescript
219
- const unsubscribe = nexus.onCommand((data) => {
220
- console.log('Received:', data.type, data.payload)
232
+ // Simple notification
233
+ nexus.notify('HEARTBEAT')
221
234
 
222
- if (data.type === 'ECHO') {
223
- nexus.reply(data.id, { echoed: data.payload })
224
- }
235
+ // Full configuration
236
+ nexus.notify({
237
+ method: 'UPDATE_STATE',
238
+ params: { state: 'ready' },
239
+ to: 'target-instance',
240
+ })
241
+ ```
242
+
243
+ ##### handle()
244
+
245
+ Register a request handler for a specific method. The return value (or resolved value of a returned Promise) is automatically sent back as the response.
246
+
247
+ ```typescript
248
+ nexus.handle<Params, Result>(method: string, handler: InvokeHandler<Params, Result>): () => void
249
+ ```
250
+
251
+ **Parameters:**
252
+
253
+ - `method`: The method name to handle.
254
+ - `handler`: A function that receives `(params, context)` and returns a result or a Promise.
255
+
256
+ **InvokeContext:**
257
+
258
+ | Property | Type | Description |
259
+ | ----------- | ------------------------- | ----------------------------------------------- |
260
+ | `messageId` | `string` | Unique identifier for the request (JSON-RPC ID) |
261
+ | `from` | `string` | Instance ID of the sender |
262
+ | `to` | `string` | Instance ID of the receiver (your instance ID) |
263
+ | `metadata` | `Record<string, unknown>` | Custom metadata sent with the envelope |
264
+
265
+ **Example:**
266
+
267
+ ```typescript
268
+ const unsubscribe = nexus.handle('ECHO', (params, context) => {
269
+ console.log(`Received ECHO from ${context.from}`)
270
+ return { echoed: params }
225
271
  })
226
272
 
227
- // 取消监听
273
+ // Unsubscribe
228
274
  unsubscribe()
229
275
  ```
230
276
 
231
- ##### reply()
277
+ ##### onNotification()
232
278
 
233
- 回复传入消息。
279
+ Register a handler for a specific notification method (one-way messages).
234
280
 
235
281
  ```typescript
236
- nexus.reply(messageId: string, payload: unknown, error?: unknown)
282
+ nexus.onNotification<Params>(method: string, handler: NotificationHandler<Params>): () => void
237
283
  ```
238
284
 
239
- **示例:**
285
+ **Example:**
240
286
 
241
287
  ```typescript
242
- nexus.reply('message-id-123', { success: true })
243
- nexus.reply('message-id-456', null, new Error('Invalid request'))
288
+ const unsubscribe = nexus.onNotification('HEARTBEAT', (params, context) => {
289
+ console.log(`Heartbeat from ${context.from}`)
290
+ })
291
+
292
+ // Unsubscribe
293
+ unsubscribe()
244
294
  ```
245
295
 
246
296
  ##### onError()
247
297
 
248
- 注册错误处理器。
298
+ Register error handler.
249
299
 
250
300
  ```typescript
251
301
  nexus.onError(handler: ErrorHandler): () => void
252
302
  ```
253
303
 
254
- **示例:**
304
+ **Example:**
255
305
 
256
306
  ```typescript
257
307
  nexus.onError((error, context) => {
258
308
  console.error('Bridge error:', error.message, context)
259
- // 发送到错误追踪服务
309
+ // Send to error tracking service
260
310
  Sentry.captureException(error, { extra: context })
261
311
  })
262
312
  ```
263
313
 
264
314
  ##### getMetrics()
265
315
 
266
- 获取监控指标。
316
+ Get monitoring metrics.
267
317
 
268
318
  ```typescript
269
319
  nexus.getMetrics(): Metrics
270
320
  ```
271
321
 
272
- **返回值:**
322
+ **Return Value:**
273
323
 
274
324
  ```typescript
275
325
  {
276
- messagesSent: number // 发送消息数
277
- messagesReceived: number // 接收消息数
278
- messagesFailed: number // 失败消息数
279
- pendingMessages: number // 待处理消息数
280
- queuedMessages: number // 队列消息数
281
- totalLatency: number // 总延迟(毫秒)
282
- averageLatency: number // 平均延迟(毫秒)
326
+ messagesSent: number // Messages sent
327
+ messagesReceived: number // Messages received
328
+ messagesFailed: number // Messages failed
329
+ pendingMessages: number // Pending messages
330
+ queuedMessages: number // Queued messages
331
+ totalLatency: number // Total latency (milliseconds)
332
+ averageLatency: number // Average latency (milliseconds)
283
333
  }
284
334
  ```
285
335
 
286
- **示例:**
336
+ **Example:**
287
337
 
288
338
  ```typescript
289
339
  const metrics = nexus.getMetrics()
@@ -295,24 +345,24 @@ console.log(
295
345
 
296
346
  ##### onMetrics()
297
347
 
298
- 注册指标变更回调。
348
+ Register metrics change callback.
299
349
 
300
350
  ```typescript
301
351
  nexus.onMetrics(callback: MetricsCallback): () => void
302
352
  ```
303
353
 
304
- **示例:**
354
+ **Example:**
305
355
 
306
356
  ```typescript
307
357
  const unsubscribe = nexus.onMetrics((metrics) => {
308
- // 发送到监控系统
358
+ // Send to monitoring system
309
359
  metricsService.report(metrics)
310
360
  })
311
361
  ```
312
362
 
313
363
  ##### flushQueue()
314
364
 
315
- 刷新消息队列,发送所有缓存的消息。
365
+ Flush the message queue, sending all cached messages.
316
366
 
317
367
  ```typescript
318
368
  nexus.flushQueue()
@@ -320,17 +370,17 @@ nexus.flushQueue()
320
370
 
321
371
  ##### destroy()
322
372
 
323
- 销毁实例,清理资源。
373
+ Destroy the instance and clean up resources.
324
374
 
325
375
  ```typescript
326
376
  nexus.destroy()
327
377
  ```
328
378
 
329
- **注意**: `destroy()` 方法会自动调用驱动的 `destroy()` 方法来清理事件监听器等资源。建议在组件卸载时调用此方法以避免内存泄漏。
379
+ **Note**: The `destroy()` method automatically calls the driver's `destroy()` method to clean up resources like event listeners. It is recommended to call this method when the component is unmounted to avoid memory leaks.
330
380
 
331
381
  ### WebSocketDriver
332
382
 
333
- #### 构造函数
383
+ #### Constructor
334
384
 
335
385
  ```typescript
336
386
  new WebSocketDriver(options: WebSocketDriverOptions)
@@ -338,20 +388,20 @@ new WebSocketDriver(options: WebSocketDriverOptions)
338
388
 
339
389
  **Options:**
340
390
 
341
- | 参数 | 类型 | 默认值 | 说明 |
342
- | --------- | --------------------------- | ------------ | ------------- |
343
- | url | string | 必填 | WebSocket URL |
344
- | reconnect | boolean \| ReconnectOptions | true | 是否自动重连 |
345
- | logger | Logger | new Logger() | 日志实例 |
391
+ | Parameter | Type | Default Value | Description |
392
+ | --------- | --------------------------- | ------------- | ---------------------------------- |
393
+ | url | string | Required | WebSocket URL |
394
+ | reconnect | boolean \| ReconnectOptions | true | Whether to automatically reconnect |
395
+ | logger | Logger | new Logger() | Logger instance |
346
396
 
347
397
  **ReconnectOptions:**
348
398
 
349
- | 参数 | 类型 | 默认值 | 说明 |
350
- | ------------- | ------ | -------- | ---------------- |
351
- | maxRetries | number | Infinity | 最大重试次数 |
352
- | retryInterval | number | 5000 | 重试间隔(毫秒) |
399
+ | Parameter | Type | Default Value | Description |
400
+ | ------------- | ------ | ------------- | ----------------------------- |
401
+ | maxRetries | number | Infinity | Maximum retry count |
402
+ | retryInterval | number | 5000 | Retry interval (milliseconds) |
353
403
 
354
- **示例:**
404
+ **Example:**
355
405
 
356
406
  ```typescript
357
407
  const driver = new WebSocketDriver({
@@ -363,11 +413,11 @@ const driver = new WebSocketDriver({
363
413
  })
364
414
  ```
365
415
 
366
- #### 方法
416
+ #### Methods
367
417
 
368
418
  ##### close()
369
419
 
370
- 关闭连接并停止重连。
420
+ Close connection and stop reconnection.
371
421
 
372
422
  ```typescript
373
423
  driver.close()
@@ -375,20 +425,20 @@ driver.close()
375
425
 
376
426
  ### PostMessageDriver
377
427
 
378
- #### 构造函数
428
+ #### Constructor
379
429
 
380
430
  ```typescript
381
431
  new PostMessageDriver(targetWindow: Window, targetOrigin: string)
382
432
  ```
383
433
 
384
- **参数:**
434
+ **Parameters:**
385
435
 
386
- | 参数 | 类型 | 必填 | 说明 |
387
- | ------------ | ------ | ---- | ------------------------------------- |
388
- | targetWindow | Window | | 目标窗口对象 |
389
- | targetOrigin | string | | 目标源地址(安全要求,不能使用 '\*' |
436
+ | Parameter | Type | Required | Description |
437
+ | ------------ | ------ | -------- | ----------------------------------------------------------------- |
438
+ | targetWindow | Window | Yes | Target window object |
439
+ | targetOrigin | string | Yes | Target origin address (security requirement, '\*' cannot be used) |
390
440
 
391
- **示例:**
441
+ **Example:**
392
442
 
393
443
  ```typescript
394
444
  const driver = new PostMessageDriver(window.parent, 'https://app.example.com')
@@ -396,27 +446,27 @@ const driver = new PostMessageDriver(window.parent, 'https://app.example.com')
396
446
 
397
447
  ### MittDriver
398
448
 
399
- #### 构造函数
449
+ #### Constructor
400
450
 
401
451
  ```typescript
402
452
  new MittDriver(emitter: Emitter<Record<string, Message>>)
403
453
  ```
404
454
 
405
- **示例:**
455
+ **Example:**
406
456
 
407
457
  ```typescript
408
458
  import { createEmitter, MittDriver } from 'message-nexus'
409
459
 
410
- // 使用工厂函数创建独立的 emitter 实例
460
+ // Use the factory function to create an independent emitter instance
411
461
  const emitter = createEmitter()
412
462
  const driver = new MittDriver(emitter)
413
463
  ```
414
464
 
415
- **注意**: 推荐使用 `createEmitter()` 工厂函数创建独立的 emitter 实例。
465
+ **Note**: It is recommended to use the `createEmitter()` factory function to create an independent emitter instance.
416
466
 
417
467
  ### BroadcastDriver
418
468
 
419
- #### 构造函数
469
+ #### Constructor
420
470
 
421
471
  ```typescript
422
472
  new BroadcastDriver(options: BroadcastDriverOptions)
@@ -424,11 +474,11 @@ new BroadcastDriver(options: BroadcastDriverOptions)
424
474
 
425
475
  **BroadcastDriverOptions:**
426
476
 
427
- | 参数 | 类型 | 默认值 | 说明 |
428
- | ------- | ------ | ------ | ------------ |
429
- | channel | string | 必填 | 广播频道名称 |
477
+ | Parameter | Type | Default Value | Description |
478
+ | --------- | ------ | ------------- | ---------------------- |
479
+ | channel | string | Required | Broadcast channel name |
430
480
 
431
- **示例:**
481
+ **Example:**
432
482
 
433
483
  ```typescript
434
484
  import { BroadcastDriver, MessageNexus } from 'message-nexus'
@@ -436,71 +486,68 @@ import { BroadcastDriver, MessageNexus } from 'message-nexus'
436
486
  const driver = new BroadcastDriver({ channel: 'my-app-channel' })
437
487
  const nexus = new MessageNexus(driver)
438
488
 
439
- // 监听来自其他标签页的消息
440
- nexus.onCommand((data) => {
441
- console.log('Received from another tab:', data)
442
- nexus.reply(data.id, { received: true })
489
+ // Listen for messages from other tabs
490
+ nexus.handle('SOME_METHOD', (params, context) => {
491
+ console.log('Received from another tab:', params)
492
+ return { received: true }
443
493
  })
444
494
 
445
- // 清理资源
495
+ // Clean up resources
446
496
  nexus.destroy()
447
497
  ```
448
498
 
449
- **特性:**
499
+ **Features:**
450
500
 
451
- - 同一源下的多个标签页可以通过相同频道名进行通信
452
- - 自动添加协议标识符,过滤非 MessageNexus 消息
453
- - 支持动态切换频道
501
+ - Multiple tabs under the same origin can communicate via the same channel name
502
+ - Automatically adds a protocol identifier to filter non-MessageNexus messages
503
+ - Supports dynamic channel switching
454
504
 
455
- ## Logger 日志
505
+ ## Advanced Usage / Techniques
456
506
 
457
- ### 基本使用
507
+ ### Asynchronous Handlers
458
508
 
459
- ```typescript
460
- import { Logger, createConsoleHandler, LogLevel } from 'message-nexus/utils/logger'
461
-
462
- const logger = new Logger('MyApp', LogLevel.DEBUG)
463
- logger.addHandler(createConsoleHandler())
464
-
465
- logger.debug('Debug message', { data: 123 })
466
- logger.info('Info message')
467
- logger.warn('Warning message')
468
- logger.error('Error message', { error: new Error('test') })
469
- ```
470
-
471
- ### 自定义日志处理器
509
+ Handlers registered via `handle()` can be `async` functions or return a `Promise`. MessageNexus will wait for the Promise to resolve before sending the response back to the caller.
472
510
 
473
511
  ```typescript
474
- const apiHandler = (entry) => {
475
- fetch('/api/logs', {
476
- method: 'POST',
477
- body: JSON.stringify(entry),
478
- })
479
- }
480
-
481
- logger.addHandler(apiHandler)
512
+ nexus.handle('FETCH_REMOTE', async (params) => {
513
+ const data = await fetch(`https://api.example.com/items/${params.id}`)
514
+ return await data.json()
515
+ })
482
516
  ```
483
517
 
484
- ### 设置日志级别
518
+ ### Suspending Responses (Manual Reply Simulation)
519
+
520
+ In some cases, you may need to wait for a user action (like clicking a button in the UI) before replying to a request. You can achieve this by returning a Promise and storing its `resolve` function.
485
521
 
486
522
  ```typescript
487
- logger.setMinLevel(LogLevel.WARN) // 只输出 WARN ERROR
488
- ```
523
+ const pendingResolvers = new Map<string, (value: any) => void>()
489
524
 
490
- ### Bridge 中使用
525
+ nexus.handle('user.confirm', (params, context) => {
526
+ return new Promise((resolve) => {
527
+ // Store the resolve function indexed by messageId
528
+ const id = context.messageId!
529
+ pendingResolvers.set(id, resolve)
491
530
 
492
- ```typescript
493
- import { Logger } from 'message-nexus/utils/logger'
531
+ // Trigger some UI to show a confirmation dialog
532
+ showDialog(params.message)
533
+ })
534
+ })
494
535
 
495
- const logger = new Logger('MyBridge')
496
- const nexus = new MessageNexus(driver, { logger })
536
+ // Later, when the user clicks "Confirm"
537
+ function onUserConfirm(id: string) {
538
+ const resolve = pendingResolvers.get(id)
539
+ if (resolve) {
540
+ resolve({ confirmed: true })
541
+ pendingResolvers.delete(id)
542
+ }
543
+ }
497
544
  ```
498
545
 
499
- ## 设计亮点
546
+ ## Design Highlights
500
547
 
501
- ### 1. 类型安全
548
+ ### 1. Type Safety
502
549
 
503
- MessageNexus 使用 TypeScript 泛型提供完整的类型推断:
550
+ MessageNexus uses TypeScript generics to provide full type inference:
504
551
 
505
552
  ```typescript
506
553
  interface UserRequest {
@@ -514,42 +561,43 @@ interface UserResponse {
514
561
 
515
562
  const nexus = new MessageNexus<UserRequest, UserResponse>(driver)
516
563
 
517
- // 完整的类型推断
518
- const response = await nexus.request({
519
- type: 'GET_USER',
520
- payload: { userId: 123 }, // 类型: UserRequest
564
+ // Full type inference
565
+ const response = await nexus.invoke({
566
+ method: 'GET_USER',
567
+ params: { userId: 123 }, // Type: UserRequest
521
568
  })
522
569
 
523
- // response 类型: UserResponse
570
+ // response Type: UserResponse
524
571
  console.log(response.name)
525
572
  ```
526
573
 
527
- ### 2. 内存安全
574
+ ### 2. Memory Safety
528
575
 
529
- - **自动清理**: 定期清理过期的消息记录
530
- - **手动清理**: `reply()` 后立即删除记录
531
- - **资源释放**: `destroy()` 方法清理所有定时器和事件监听器
532
- - **队列限制**: 消息队列有最大大小限制,防止无限增长
533
- - **Driver 生命周期**: 每个 Driver 实现 `destroy()` 方法,正确释放资源
534
- - **Emitter 隔离**: 推荐使用 `createEmitter()` 创建独立实例,避免共享单例导致的内存泄漏
576
+ - **Auto Cleanup**: Regularly clean up expired message records
577
+ - **Manual Cleanup**: Internal request records are deleted immediately after the response is received or timed out
578
+ - **Auto-Reply**: Handlers automatically send responses when the return value is resolved, ensuring no orphaned requests
579
+ - **Resource Release**: The `destroy()` method cleans up all timers and event listeners
580
+ - **Queue Limits**: The message queue has a maximum size limit to prevent infinite growth
581
+ - **Driver Lifecycle**: Each driver implements the `destroy()` method to correctly release resources
582
+ - **Emitter Isolation**: Recommended to use `createEmitter()` to create independent instances, avoiding memory leaks caused by shared singletons
535
583
 
536
- ### 3. 错误恢复
584
+ ### 3. Error Recovery
537
585
 
538
- - **自动重连**: WebSocket 断线自动重连,指数退避策略
539
- - **请求重试**: 失败请求自动重试,可配置次数和延迟
540
- - **消息队列**: 离线消息缓存,连接恢复后自动发送
541
- - **错误回调**: 统一的错误处理机制
586
+ - **Auto Reconnect**: WebSocket automatic reconnection mechanism with exponential backoff strategy
587
+ - **Request Retry**: Automatic retry on request failure, configurable retry counts and delays
588
+ - **Message Queue**: Offline message caching, automatically sent after connection recovery
589
+ - **Error Callback**: Unified error handling mechanism
542
590
 
543
- ### 4. 安全加固
591
+ ### 4. Security Hardening
544
592
 
545
- - **PostMessage**: 禁止使用 `'*'` 作为 targetOrigin,必须明确指定源地址
546
- - **BroadcastChannel**: 使用协议标识符 `__messageBridge` 区分 MessageNexus 消息和用户自定义消息
547
- - **消息验证**: 运行时验证消息格式,防止非法消息导致崩溃
548
- - **来源过滤**: 自动过滤非目标消息
593
+ - **PostMessage**: Prohibit using `'*'` as targetOrigin; the origin address must be explicitly specified
594
+ - **BroadcastChannel**: Use the protocol identifier `__messageBridge` to distinguish MessageNexus messages from user-defined messages
595
+ - **Message Validation**: Runtime validation of message format to prevent crashes from illegal messages
596
+ - **Source Filtering**: Automatically filters non-target messages
549
597
 
550
- ### 5. 可观测性
598
+ ### 5. Observability
551
599
 
552
- 内置监控指标,便于生产环境监控:
600
+ Built-in monitoring metrics for easy production environment monitoring:
553
601
 
554
602
  ```typescript
555
603
  const metrics = nexus.getMetrics()
@@ -562,34 +610,15 @@ console.log(`Avg latency: ${metrics.averageLatency}ms`)
562
610
  console.log(`Pending: ${metrics.pendingMessages}, Queued: ${metrics.queuedMessages}`)
563
611
  ```
564
612
 
565
- ### 6. 结构化日志
566
-
567
- 统一的日志接口,支持多种输出方式:
568
-
569
- ```typescript
570
- // 控制台输出
571
- logger.addHandler(createConsoleHandler())
572
-
573
- // 发送到 API
574
- logger.addHandler((entry) => {
575
- fetch('/api/logs', { body: JSON.stringify(entry) })
576
- })
577
-
578
- // 发送到 ELK
579
- logger.addHandler((entry) => {
580
- elk.send(entry)
581
- })
582
- ```
583
-
584
- ## 测试
613
+ ## Testing
585
614
 
586
- 运行单元测试:
615
+ Run unit tests:
587
616
 
588
617
  ```bash
589
618
  cd packages/message-nexus
590
619
  pnpm test:run
591
620
  ```
592
621
 
593
- ## 许可证
622
+ ## License
594
623
 
595
624
  MIT