sse-stream-plugin-react 1.0.0 → 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/CHANGELOG.md ADDED
@@ -0,0 +1,39 @@
1
+ # 更新日志
2
+
3
+ 本文件记录 sse-stream-plugin-react 的版本变更。
4
+
5
+ 格式参考 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
6
+
7
+ ## [1.1.1] - 2026-12-01
8
+
9
+ ### 文档
10
+
11
+ - README 新增英文文档(单文件双语:英文在上、中文在下,顶部/底部附语言切换锚点),覆盖安装、快速开始、API、生命周期、暂停/继续/重新开始与高级用法。
12
+ - 本次为纯文档发布,无源码与 API 变更。
13
+
14
+ ## [1.1.0] - 2026-11-19
15
+
16
+ ### 新增
17
+
18
+ - 新增 `resume()`:复用当前实例从断点续传;实例不存在或上次流已正常结束时自动退化为重新开始。
19
+ - 新增 `restart()`:销毁旧实例并清空输出,从头重新请求(与原 `start()` 行为一致)。
20
+ - 新增 `close()`:销毁实例与订阅并复位状态,用于「直接停止」;已输出内容保留。
21
+ - 新增 `closed` 事件监听:无论通过 `close()` 还是直接调用 `instance.destroy()`,`status` / `loading` / `instance` 都会同步复位。
22
+ - 订阅 `connecting` 事件:自动重连或续传期间 `loading` 能正确恢复为 `true`。
23
+
24
+ ### 变更
25
+
26
+ - `stop()` 由调用 `destroy()` 改为调用核心 SDK 新增的 `abort()`:只中断当前流,实例与已输出内容保留,可通过 `resume()` 继续。
27
+ - peerDependencies 中 `sse-stream-plugin-sdk` 升级为 `^1.1.0`(`stop()` 依赖新增的 `abort()`)。
28
+ - `start()` 行为保持不变,等价于 `restart()`。
29
+
30
+ ## [1.0.0] - 2026-10-04
31
+
32
+ ### 新增
33
+
34
+ - 首次发布。sse-stream-plugin-sdk 的 React Hooks 封装。
35
+ - 提供 `useSSEStream` Hook:以声明式方式管理 SSE 连接,返回流式文本 `text`、加载状态 `loading`、连接状态 `status` 以及 `start` / `stop` 控制方法。
36
+ - 支持 `getBody`(每次发起连接时动态读取请求体)、`onMessage` / `onError` 等回调,并可透传核心 SDK 的 plugins、headers 等全部配置。
37
+ - 自动管理实例生命周期与事件订阅,组件卸载时自动销毁连接。
38
+ - peerDependencies:`react >= 16.8.0`、`sse-stream-plugin-sdk ^1.0.0`。
39
+ - 产物格式:ESM(`dist/index.mjs`)、CJS(`dist/index.cjs`)及 TypeScript 类型声明(`dist/index.d.ts`)。
package/README.md CHANGED
@@ -1,117 +1,411 @@
1
- # sse-stream-plugin-react
2
-
3
- [sse-stream-plugin-sdk](../core) 的 React Hooks 封装。将插件化 SSE SDK 封装为声明式响应式 API,自动管理实例生命周期与事件订阅。
4
-
5
- ## 安装
6
-
7
- 需要同时安装核心 SDK:
8
-
9
- ```bash
10
- npm install sse-stream-plugin-react sse-stream-plugin-sdk
11
- # 或
12
- pnpm add sse-stream-plugin-react sse-stream-plugin-sdk
13
- ```
14
-
15
- > `react` 为 peerDependency,要求 `>=16.8.0`。
16
-
17
- ## 快速开始
18
-
19
- ```tsx
20
- import { useSSEStream } from 'sse-stream-plugin-react'
21
- import { recommendedPlugins } from 'sse-stream-plugin-sdk'
22
-
23
- function Chat() {
24
- const { text, loading, status, start, stop } = useSSEStream({
25
- url: 'https://api.example.com/stream',
26
- method: 'POST',
27
- getBody: () => JSON.stringify({ prompt: '你好' }),
28
- headers: { 'Content-Type': 'application/json' },
29
- plugins: recommendedPlugins(),
30
- onMessage: (data) => console.log(data),
31
- onError: (err) => console.error(err),
32
- })
33
-
34
- return (
35
- <div>
36
- <button onClick={start} disabled={loading}>发送</button>
37
- <button onClick={stop}>停止</button>
38
- <p>{status}</p>
39
- <pre>{text}</pre>
40
- </div>
41
- )
42
- }
43
- ```
44
-
45
- ## API
46
-
47
- ### `useSSEStream(options)`
48
-
49
- #### 入参 `UseSSEStreamOptions`
50
-
51
- 继承 `PluginSSEOptions` 的核心字段,并追加事件回调与动态 body:
52
-
53
- | 字段 | 类型 | 说明 |
54
- |------|------|------|
55
- | `url` | `string` | 请求地址(必填) |
56
- | `method` | `'GET' \| 'POST'` | 请求方法,默认 `GET` |
57
- | `body` | `string` | 请求体字符串 |
58
- | `getBody` | `() => string` | 每次 `start` 时动态生成请求体,优先级高于 `body` |
59
- | `headers` | `Record<string, string>` | 自定义请求头 |
60
- | `transport` | `string \| TransportFactory` | 传输层,省略则自动探测 `fetch` |
61
- | `parser` | `ParserFactory` | 自定义解析器 |
62
- | `plugins` | `SSEPlugin[]` | 插件列表 |
63
- | `onMessage` | `(data, event) => void` | 收到 message 事件回调 |
64
- | `onOpen` | `(info: { transport }) => void` | 连接打开回调 |
65
- | `onEnd` | `() => void` | 流结束回调 |
66
- | `onError` | `(err) => void` | 错误回调 |
67
-
68
- > 事件回调通过 `ref` 始终取最新值,不会出现闭包过期问题。
69
-
70
- #### 返回值 `UseSSEStreamReturn`
71
-
72
- | 字段 | 类型 | 说明 |
73
- |------|------|------|
74
- | `text` | `string` | 已拼接的消息文本(`message` 事件 `data` 累加) |
75
- | `status` | `string` | 连接状态描述 |
76
- | `loading` | `boolean` | 是否处于连接中/流式接收中 |
77
- | `msgCount` | `number` | 已接收 message 事件条数 |
78
- | `charCount` | `number` | 已接收字符总数 |
79
- | `start` | `() => void` | 发起一次连接(先销毁旧连接) |
80
- | `stop` | `() => void` | 手动断开并销毁实例 |
81
- | `instance` | `PluginSSE \| null` | 当前实例(便于 `use()` 追加插件等高级操作) |
82
-
83
- ## 生命周期
84
-
85
- - 组件卸载时自动 `destroy()` 实例并清空订阅,无需手动清理
86
- - `start()` 会先销毁旧连接再创建新连接,可重复调用
87
-
88
- ## 高级用法
89
-
90
- ### 通过 `instance` 追加插件
91
-
92
- ```tsx
93
- const { instance, start } = useSSEStream({ url, method: 'POST' })
94
-
95
- useEffect(() => {
96
- if (instance) {
97
- instance.use(loggerPlugin())
98
- }
99
- }, [instance])
100
- ```
101
-
102
- ### 小程序环境
103
-
104
- 通过 `transport` 传入小程序传输层工厂:
105
-
106
- ```tsx
107
- import { createMpTransport } from 'sse-stream-plugin-sdk'
108
-
109
- useSSEStream({
110
- url,
111
- transport: createMpTransport(() => wx),
112
- })
113
- ```
114
-
115
- ## License
116
-
117
- MIT
1
+ <a id="english"></a>
2
+
3
+ **English** | [简体中文](#zh-cn)
4
+
5
+ # sse-stream-plugin-react
6
+
7
+ React Hooks wrapper for [sse-stream-plugin-sdk](../core). Wraps the plugin-based SSE SDK into a declarative, reactive API, automatically managing the instance lifecycle and event subscriptions.
8
+
9
+ ## Install
10
+
11
+ The core SDK must be installed as well:
12
+
13
+ ```bash
14
+ npm install sse-stream-plugin-react sse-stream-plugin-sdk
15
+ # or
16
+ pnpm add sse-stream-plugin-react sse-stream-plugin-sdk
17
+ ```
18
+
19
+ > `react` is a peerDependency, requiring `>=16.8.0`.
20
+
21
+ ## Quick Start
22
+
23
+ ```tsx
24
+ import { useSSEStream } from 'sse-stream-plugin-react'
25
+ import { recommendedPlugins } from 'sse-stream-plugin-sdk'
26
+
27
+ function Chat() {
28
+ const { text, loading, status, start, stop } = useSSEStream({
29
+ url: 'https://api.example.com/stream',
30
+ method: 'POST',
31
+ getBody: () => JSON.stringify({ prompt: 'Hello' }),
32
+ headers: { 'Content-Type': 'application/json' },
33
+ plugins: recommendedPlugins(),
34
+ onMessage: (data) => console.log(data),
35
+ onError: (err) => console.error(err),
36
+ })
37
+
38
+ return (
39
+ <div>
40
+ <button onClick={start} disabled={loading}>Send</button>
41
+ <button onClick={stop}>Pause</button>
42
+ <p>{status}</p>
43
+ <pre>{text}</pre>
44
+ </div>
45
+ )
46
+ }
47
+ ```
48
+
49
+ ## API
50
+
51
+ ### `useSSEStream(options)`
52
+
53
+ #### Parameters `UseSSEStreamOptions`
54
+
55
+ Inherits the core fields of `PluginSSEOptions`, and adds event callbacks plus a dynamic body:
56
+
57
+ | Field | Type | Description |
58
+ |------|------|------|
59
+ | `url` | `string` | Request URL (required) |
60
+ | `method` | `'GET' \| 'POST'` | HTTP method, default `GET` |
61
+ | `body` | `string` | Request body string |
62
+ | `getBody` | `() => string` | Dynamically generates the request body on each `start`, takes precedence over `body` |
63
+ | `headers` | `Record<string, string>` | Custom request headers |
64
+ | `transport` | `string \| TransportFactory` | Transport, auto-detects `fetch` when omitted |
65
+ | `parser` | `ParserFactory` | Custom parser |
66
+ | `plugins` | `SSEPlugin[]` | Plugin list |
67
+ | `onMessage` | `(data, event) => void` | Callback on a `message` event |
68
+ | `onOpen` | `(info: { transport }) => void` | Callback when the connection opens |
69
+ | `onEnd` | `() => void` | Callback when the stream ends |
70
+ | `onError` | `(err) => void` | Error callback |
71
+
72
+ > Event callbacks always read the latest value via `ref`, so there's no stale-closure issue.
73
+
74
+ #### Return value `UseSSEStreamReturn`
75
+
76
+ | Field | Type | Description |
77
+ |------|------|------|
78
+ | `text` | `string` | Concatenated message text (accumulated `message` event `data`) |
79
+ | `status` | `string` | Connection status description |
80
+ | `loading` | `boolean` | Whether connecting / streaming |
81
+ | `msgCount` | `number` | Number of `message` events received |
82
+ | `charCount` | `number` | Total characters received |
83
+ | `start` | `() => void` | Start a connection (destroys the old instance and clears output; equivalent to `restart`) |
84
+ | `restart` | `() => void` | Restart: discard output and create a new instance |
85
+ | `stop` | `() => void` | Pause: interrupt the current stream, keep the instance and output |
86
+ | `resume` | `() => void` | Resume: reuse the instance to continue from the breakpoint |
87
+ | `close` | `() => void` | Fully stop: destroy the instance and subscriptions (permanently disconnect) |
88
+ | `instance` | `PluginSSE \| null` | Current instance (for advanced ops like `use()` to add plugins) |
89
+
90
+ ## Lifecycle
91
+
92
+ - On component unmount the instance is automatically `destroy()`ed and subscriptions are cleared — no manual cleanup needed
93
+ - `start()` / `restart()` destroy the old connection before creating a new one; can be called repeatedly
94
+ - `stop()` only interrupts the connection (internally calls `abort()`); the instance and output are kept, and `resume()` can continue
95
+ - `close()` fully stops: internally calls `destroy()`, releases plugin resources and clears subscriptions; you must `start()` again afterwards
96
+ - When the stream has ended normally or the instance hasn't been created, `resume()` automatically falls back to `restart()`
97
+
98
+ ## Pause, Resume & Restart
99
+
100
+ The `stop()` / `resume()` / `restart()` combo lets you "pause mid-stream and resume from the breakpoint later":
101
+
102
+ ```tsx
103
+ import { useSSEStream } from 'sse-stream-plugin-react'
104
+ import { recommendedPlugins } from 'sse-stream-plugin-sdk'
105
+
106
+ function Chat() {
107
+ const { text, status, loading, start, stop, resume, restart } = useSSEStream({
108
+ url: 'https://api.example.com/stream',
109
+ method: 'POST',
110
+ getBody: () => JSON.stringify({ prompt: 'Hello' }),
111
+ headers: { 'Content-Type': 'application/json' },
112
+ plugins: recommendedPlugins(),
113
+ })
114
+
115
+ return (
116
+ <div>
117
+ <button onClick={start}>Send</button>
118
+ {/* interrupt the connection, keep the output, status becomes "Paused" */}
119
+ <button onClick={stop} disabled={!loading}>Pause</button>
120
+ {/* reuse the instance to continue, text appends to existing content */}
121
+ <button onClick={resume}>Resume</button>
122
+ {/* discard output and resend the request */}
123
+ <button onClick={restart}>Regenerate</button>
124
+ <p>{status}</p>
125
+ <pre>{text}</pre>
126
+ </div>
127
+ )
128
+ }
129
+ ```
130
+
131
+ | Method | Behavior | `text` | Connection position |
132
+ |------|------|--------|----------|
133
+ | `stop()` | Interrupt current stream, keep instance | Kept | Kept |
134
+ | `resume()` | Reuse instance to reconnect | Kept and appended | Resumes with `Last-Event-ID` |
135
+ | `restart()` | Destroy old instance, resend | Cleared | From scratch |
136
+ | `close()` | Destroy instance and subscriptions, fully stop | Kept | Cleared |
137
+
138
+ > `resume()`'s resumable transfer depends on the server supporting `Last-Event-ID`. If the server doesn't support it, the resume becomes a full resend — use `restart()` instead or add a dedup plugin.
139
+
140
+ ### Fully stop (close)
141
+
142
+ `stop()` only pauses; the instance is still resident. If the user wants to truly end the session, use `close()`:
143
+
144
+ ```tsx
145
+ import { useSSEStream } from 'sse-stream-plugin-react'
146
+
147
+ function Chat() {
148
+ const { text, status, loading, start, stop, close } = useSSEStream({
149
+ url: 'https://api.example.com/stream',
150
+ method: 'POST',
151
+ getBody: () => JSON.stringify({ prompt: 'Hello' }),
152
+ })
153
+
154
+ return (
155
+ <div>
156
+ <button onClick={start}>Send</button>
157
+ <button onClick={stop} disabled={!loading}>Pause</button>
158
+ {/* destroy the instance, release plugin resources and clear event subscriptions; unrecoverable */}
159
+ <button onClick={close}>Stop</button>
160
+ <p>{status}</p>{/* "Stopped" after close */}
161
+ <pre>{text}</pre>
162
+ </div>
163
+ )
164
+ }
165
+ ```
166
+
167
+ Key points:
168
+
169
+ - `close()` is equivalent to calling `destroy()` on the instance: abort the request, run plugin dispose callbacks, clear event subscriptions
170
+ - Afterwards `status` becomes "Stopped", `loading` becomes `false`, `instance` becomes `null`
171
+ - The already-output `text` is kept; clicking "Send" (`start()`) again creates a brand-new instance from scratch
172
+ - On component unmount `destroy()` is called automatically, so manual invocation is usually unnecessary; `close()` suits "the user explicitly ends the session and wants resources released immediately"
173
+ - Calling `instance?.destroy()` directly has the same effect; the Hook syncs state via the `closed` event
174
+
175
+ ## Advanced Usage
176
+
177
+ ### Add plugins via `instance`
178
+
179
+ ```tsx
180
+ const { instance, start } = useSSEStream({ url, method: 'POST' })
181
+
182
+ useEffect(() => {
183
+ if (instance) {
184
+ instance.use(loggerPlugin())
185
+ }
186
+ }, [instance])
187
+ ```
188
+
189
+ ### Mini-program environment
190
+
191
+ Pass a mini-program transport factory via `transport`:
192
+
193
+ ```tsx
194
+ import { createMpTransport } from 'sse-stream-plugin-sdk'
195
+
196
+ useSSEStream({
197
+ url,
198
+ transport: createMpTransport(() => wx),
199
+ })
200
+ ```
201
+
202
+ ## License
203
+
204
+ MIT
205
+
206
+ ---
207
+
208
+ <a id="zh-cn"></a>
209
+
210
+ [← English](#english) | **简体中文**
211
+
212
+ # sse-stream-plugin-react
213
+
214
+ [sse-stream-plugin-sdk](../core) 的 React Hooks 封装。将插件化 SSE SDK 封装为声明式响应式 API,自动管理实例生命周期与事件订阅。
215
+
216
+ ## 安装
217
+
218
+ 需要同时安装核心 SDK:
219
+
220
+ ```bash
221
+ npm install sse-stream-plugin-react sse-stream-plugin-sdk
222
+ # 或
223
+ pnpm add sse-stream-plugin-react sse-stream-plugin-sdk
224
+ ```
225
+
226
+ > `react` 为 peerDependency,要求 `>=16.8.0`。
227
+
228
+ ## 快速开始
229
+
230
+ ```tsx
231
+ import { useSSEStream } from 'sse-stream-plugin-react'
232
+ import { recommendedPlugins } from 'sse-stream-plugin-sdk'
233
+
234
+ function Chat() {
235
+ const { text, loading, status, start, stop } = useSSEStream({
236
+ url: 'https://api.example.com/stream',
237
+ method: 'POST',
238
+ getBody: () => JSON.stringify({ prompt: '你好' }),
239
+ headers: { 'Content-Type': 'application/json' },
240
+ plugins: recommendedPlugins(),
241
+ onMessage: (data) => console.log(data),
242
+ onError: (err) => console.error(err),
243
+ })
244
+
245
+ return (
246
+ <div>
247
+ <button onClick={start} disabled={loading}>发送</button>
248
+ <button onClick={stop}>暂停</button>
249
+ <p>{status}</p>
250
+ <pre>{text}</pre>
251
+ </div>
252
+ )
253
+ }
254
+ ```
255
+
256
+ ## API
257
+
258
+ ### `useSSEStream(options)`
259
+
260
+ #### 入参 `UseSSEStreamOptions`
261
+
262
+ 继承 `PluginSSEOptions` 的核心字段,并追加事件回调与动态 body:
263
+
264
+ | 字段 | 类型 | 说明 |
265
+ |------|------|------|
266
+ | `url` | `string` | 请求地址(必填) |
267
+ | `method` | `'GET' \| 'POST'` | 请求方法,默认 `GET` |
268
+ | `body` | `string` | 请求体字符串 |
269
+ | `getBody` | `() => string` | 每次 `start` 时动态生成请求体,优先级高于 `body` |
270
+ | `headers` | `Record<string, string>` | 自定义请求头 |
271
+ | `transport` | `string \| TransportFactory` | 传输层,省略则自动探测 `fetch` |
272
+ | `parser` | `ParserFactory` | 自定义解析器 |
273
+ | `plugins` | `SSEPlugin[]` | 插件列表 |
274
+ | `onMessage` | `(data, event) => void` | 收到 message 事件回调 |
275
+ | `onOpen` | `(info: { transport }) => void` | 连接打开回调 |
276
+ | `onEnd` | `() => void` | 流结束回调 |
277
+ | `onError` | `(err) => void` | 错误回调 |
278
+
279
+ > 事件回调通过 `ref` 始终取最新值,不会出现闭包过期问题。
280
+
281
+ #### 返回值 `UseSSEStreamReturn`
282
+
283
+ | 字段 | 类型 | 说明 |
284
+ |------|------|------|
285
+ | `text` | `string` | 已拼接的消息文本(`message` 事件 `data` 累加) |
286
+ | `status` | `string` | 连接状态描述 |
287
+ | `loading` | `boolean` | 是否处于连接中/流式接收中 |
288
+ | `msgCount` | `number` | 已接收 message 事件条数 |
289
+ | `charCount` | `number` | 已接收字符总数 |
290
+ | `start` | `() => void` | 发起连接(销毁旧实例、清空已输出内容,等价 `restart`) |
291
+ | `restart` | `() => void` | 重新开始:丢弃已输出内容并新建实例 |
292
+ | `stop` | `() => void` | 暂停:中断当前流,保留实例与已输出内容 |
293
+ | `resume` | `() => void` | 继续:复用实例从断点续传 |
294
+ | `close` | `() => void` | 彻底停止:销毁实例与订阅(永久断开) |
295
+ | `instance` | `PluginSSE \| null` | 当前实例(便于 `use()` 追加插件等高级操作) |
296
+
297
+ ## 生命周期
298
+
299
+ - 组件卸载时自动 `destroy()` 实例并清空订阅,无需手动清理
300
+ - `start()` / `restart()` 会先销毁旧连接再创建新连接,可重复调用
301
+ - `stop()` 只中断连接(内部调用 `abort()`),实例与已输出内容保留,可用 `resume()` 继续
302
+ - `close()` 彻底停止:内部调用 `destroy()`,释放插件资源并清空订阅,之后需重新 `start()`
303
+ - 流已正常结束或实例尚未创建时,`resume()` 自动退化为 `restart()`
304
+
305
+ ## 暂停、继续与重新开始
306
+
307
+ `stop()` / `resume()` / `restart()` 组合可实现「流式输出到一半暂停,稍后从断点继续」:
308
+
309
+ ```tsx
310
+ import { useSSEStream } from 'sse-stream-plugin-react'
311
+ import { recommendedPlugins } from 'sse-stream-plugin-sdk'
312
+
313
+ function Chat() {
314
+ const { text, status, loading, start, stop, resume, restart } = useSSEStream({
315
+ url: 'https://api.example.com/stream',
316
+ method: 'POST',
317
+ getBody: () => JSON.stringify({ prompt: '你好' }),
318
+ headers: { 'Content-Type': 'application/json' },
319
+ plugins: recommendedPlugins(),
320
+ })
321
+
322
+ return (
323
+ <div>
324
+ <button onClick={start}>发送</button>
325
+ {/* 中断连接,已输出内容保留,status 变为「已暂停」 */}
326
+ <button onClick={stop} disabled={!loading}>暂停</button>
327
+ {/* 复用实例继续,text 在原有内容基础上追加 */}
328
+ <button onClick={resume}>继续</button>
329
+ {/* 丢弃已输出内容,重新发送请求 */}
330
+ <button onClick={restart}>重新生成</button>
331
+ <p>{status}</p>
332
+ <pre>{text}</pre>
333
+ </div>
334
+ )
335
+ }
336
+ ```
337
+
338
+ | 方法 | 行为 | `text` | 连接位点 |
339
+ |------|------|--------|----------|
340
+ | `stop()` | 中断当前流,实例保留 | 保留 | 保留 |
341
+ | `resume()` | 复用实例重新连接 | 保留并追加 | 携带 `Last-Event-ID` 续传 |
342
+ | `restart()` | 销毁旧实例,重新发送 | 清空 | 从头开始 |
343
+ | `close()` | 销毁实例与订阅,彻底停止 | 保留 | 清空 |
344
+
345
+ > `resume()` 的断点续传依赖服务端支持 `Last-Event-ID`。若服务端不支持,续传会变成全量重发,请改用 `restart()` 或额外加去重插件。
346
+
347
+ ### 彻底停止(close)
348
+
349
+ `stop()` 只是暂停,实例仍然驻留;若用户要真正结束本次会话,用 `close()`:
350
+
351
+ ```tsx
352
+ import { useSSEStream } from 'sse-stream-plugin-react'
353
+
354
+ function Chat() {
355
+ const { text, status, loading, start, stop, close } = useSSEStream({
356
+ url: 'https://api.example.com/stream',
357
+ method: 'POST',
358
+ getBody: () => JSON.stringify({ prompt: '你好' }),
359
+ })
360
+
361
+ return (
362
+ <div>
363
+ <button onClick={start}>发送</button>
364
+ <button onClick={stop} disabled={!loading}>暂停</button>
365
+ {/* 销毁实例、释放插件资源并清空事件订阅,不可恢复 */}
366
+ <button onClick={close}>停止</button>
367
+ <p>{status}</p>{/* close 后为「已停止」 */}
368
+ <pre>{text}</pre>
369
+ </div>
370
+ )
371
+ }
372
+ ```
373
+
374
+ 要点:
375
+
376
+ - `close()` 等价于对实例执行 `destroy()`:中止请求、执行插件销毁回调、清空事件订阅
377
+ - 之后 `status` 变为「已停止」、`loading` 变为 `false`、`instance` 变为 `null`
378
+ - 已输出的 `text` 保留;再次点击「发送」(`start()`)会创建全新实例,从头开始
379
+ - 组件卸载时会自动 `destroy()`,通常无需手动调用;`close()` 适用于「用户明确结束会话、希望立即释放资源」的场景
380
+ - 直接调用 `instance?.destroy()` 效果相同,Hook 会通过 `closed` 事件同步复位状态
381
+
382
+ ## 高级用法
383
+
384
+ ### 通过 `instance` 追加插件
385
+
386
+ ```tsx
387
+ const { instance, start } = useSSEStream({ url, method: 'POST' })
388
+
389
+ useEffect(() => {
390
+ if (instance) {
391
+ instance.use(loggerPlugin())
392
+ }
393
+ }, [instance])
394
+ ```
395
+
396
+ ### 小程序环境
397
+
398
+ 通过 `transport` 传入小程序传输层工厂:
399
+
400
+ ```tsx
401
+ import { createMpTransport } from 'sse-stream-plugin-sdk'
402
+
403
+ useSSEStream({
404
+ url,
405
+ transport: createMpTransport(() => wx),
406
+ })
407
+ ```
408
+
409
+ ## License
410
+
411
+ MIT
package/dist/index.cjs CHANGED
@@ -16,6 +16,10 @@ function useSSEStream(options) {
16
16
  const optionsRef = react.useRef(options);
17
17
  optionsRef.current = options;
18
18
  const sseRef = react.useRef(null);
19
+ /** 上一次连接是否正常结束(正常结束后续传位点已归零,resume 需从头开始) */
20
+ const endedRef = react.useRef(false);
21
+ /** 是否仍挂载,避免卸载时 destroy 触发的 closed 回调再更新状态 */
22
+ const mountedRef = react.useRef(true);
19
23
  const [text, setText] = react.useState('');
20
24
  const [status, setStatus] = react.useState('未连接');
21
25
  const [loading, setLoading] = react.useState(false);
@@ -23,15 +27,24 @@ function useSSEStream(options) {
23
27
  const [charCount, setCharCount] = react.useState(0);
24
28
  // 组件卸载:释放连接、清空订阅
25
29
  react.useEffect(() => {
30
+ mountedRef.current = true;
26
31
  return () => {
32
+ mountedRef.current = false;
27
33
  sseRef.current?.destroy();
28
34
  sseRef.current = null;
29
35
  };
30
36
  }, []);
37
+ // 暂停:中断当前流但保留实例与已输出内容,状态由 abort 事件更新
31
38
  const stop = react.useCallback(() => {
32
- sseRef.current?.destroy();
33
- sseRef.current = null;
34
- setStatus('已手动断开');
39
+ sseRef.current?.abort();
40
+ }, []);
41
+ // 彻底停止:销毁实例与订阅,状态由 closed 事件统一复位
42
+ const close = react.useCallback(() => {
43
+ if (sseRef.current) {
44
+ sseRef.current.destroy();
45
+ return;
46
+ }
47
+ setStatus('已停止');
35
48
  setLoading(false);
36
49
  }, []);
37
50
  const start = react.useCallback(() => {
@@ -43,6 +56,7 @@ function useSSEStream(options) {
43
56
  setCharCount(0);
44
57
  setStatus('连接中…');
45
58
  setLoading(true);
59
+ endedRef.current = false;
46
60
  const sse = new sseStreamPluginSdk.PluginSSE({
47
61
  url,
48
62
  method: method ?? 'GET',
@@ -52,6 +66,11 @@ function useSSEStream(options) {
52
66
  parser,
53
67
  plugins,
54
68
  });
69
+ // 每次(含自动重连、resume)发起连接都会触发,保证 loading 状态不丢失
70
+ sse.on('connecting', () => {
71
+ setStatus('连接中…');
72
+ setLoading(true);
73
+ });
55
74
  sse.on('open', ({ transport: name }) => {
56
75
  setStatus(`已连接(${name})`);
57
76
  onOpen?.({ transport: name });
@@ -63,6 +82,7 @@ function useSSEStream(options) {
63
82
  onMessage?.(data, event);
64
83
  });
65
84
  sse.on('end', () => {
85
+ endedRef.current = true;
66
86
  setStatus('流正常结束');
67
87
  setLoading(false);
68
88
  onEnd?.();
@@ -73,9 +93,32 @@ function useSSEStream(options) {
73
93
  setLoading(false);
74
94
  onError?.(err);
75
95
  });
96
+ sse.on('abort', () => {
97
+ setStatus('已暂停');
98
+ setLoading(false);
99
+ });
100
+ sse.on('closed', () => {
101
+ if (!mountedRef.current)
102
+ return;
103
+ endedRef.current = false;
104
+ sseRef.current = null;
105
+ setStatus('已停止');
106
+ setLoading(false);
107
+ });
76
108
  sseRef.current = sse;
77
109
  sse.connect();
78
110
  }, []);
111
+ // 继续:复用实例从断点续传;无实例或上次已正常结束时退化为重新开始
112
+ const resume = react.useCallback(() => {
113
+ const sse = sseRef.current;
114
+ if (!sse || endedRef.current) {
115
+ start();
116
+ return;
117
+ }
118
+ setStatus('连接中…');
119
+ setLoading(true);
120
+ void sse.start();
121
+ }, [start]);
79
122
  return {
80
123
  text,
81
124
  status,
@@ -83,7 +126,10 @@ function useSSEStream(options) {
83
126
  msgCount,
84
127
  charCount,
85
128
  start,
129
+ restart: start,
86
130
  stop,
131
+ resume,
132
+ close,
87
133
  instance: sseRef.current,
88
134
  };
89
135
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/useSSEStream.ts"],"sourcesContent":[null],"names":["useRef","useState","useEffect","useCallback","PluginSSE"],"mappings":";;;;;AAAA;;;;;;;AAOG;AAuCG,SAAU,YAAY,CAAC,OAA4B,EAAA;;AAEvD,IAAA,MAAM,UAAU,GAAGA,YAAM,CAAC,OAAO,CAAC;AAClC,IAAA,UAAU,CAAC,OAAO,GAAG,OAAO;AAE5B,IAAA,MAAM,MAAM,GAAGA,YAAM,CAAmB,IAAI,CAAC;IAC7C,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAGC,cAAQ,CAAC,EAAE,CAAC;IACpC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAGA,cAAQ,CAAC,KAAK,CAAC;IAC3C,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAGA,cAAQ,CAAC,KAAK,CAAC;IAC7C,MAAM,CAAC,QAAQ,EAAE,WAAW,CAAC,GAAGA,cAAQ,CAAC,CAAC,CAAC;IAC3C,MAAM,CAAC,SAAS,EAAE,YAAY,CAAC,GAAGA,cAAQ,CAAC,CAAC,CAAC;;IAG7CC,eAAS,CAAC,MAAK;AACb,QAAA,OAAO,MAAK;AACV,YAAA,M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CAAC,CAAC;QACF,GAAG,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,IAAY,EAAE,KAAkB,KAAI;YACrD,OAAO,CAAC,CAAC,IAAI,KAAK,IAAI,GAAG,IAAI,CAAC;YAC9B,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AACzB,YAAA,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC;AACpC,YAAA,SAAS,GAAG,IAAI,EAAE,KAAK,CAAC;AAC1B,QAAA,CAAC,CAAC;AACF,QAAA,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,MAAK;YACjB,SAAS,CAAC,OAAO,CAAC;YAClB,UAAU,CAAC,KAAK,CAAC;YACjB,KAAK,IAAI;AACX,QAAA,CAAC,CAAC;QACF,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,GAAY,KAAI;AAC/B,YAAA,MAAM,GAAG,GAAG,GAAG,YAAY,KAAK,GAAG,GAAG,CAAC,OAAO,GAAG,MAAM,CAAC,GAAG,CAAC;AAC5D,YAAA,SAAS,CAAC,CAAA,GAAA,EAAM,GAAG,CAAA,CAAE,CAAC;YACtB,UAAU,CAAC,KAAK,CAAC;AACjB,YAAA,OAAO,GAAG,GAAG,CAAC;AAChB,QAAA,CAAC,CAAC;AAEF,QAAA,MAAM,CAAC,OAAO,GAAG,GAAG;QACpB,GAAG,CAAC,OAAO,EAAE;IACf,CAAC,EAAE,EAAE,CAAC;IAEN,OAAO;QACL,IAAI;QACJ,MAAM;QACN,OAAO;QACP,QAAQ;QACR,SAAS;QACT,KAAK;QACL,IAAI;QACJ,QAAQ,EAAE,MAAM,CAAC,OAAO;KACzB;AACH;;"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/useSSEStream.ts"],"sourcesContent":[null],"names":["useRef","useState","useEffect","useCallback","PluginSSE"],"mappings":";;;;;AAAA;;;;;;;AAOG;AA6CG,SAAU,YAAY,CAAC,OAA4B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CAAC,OAAO,EAAE;IACf,CAAC,EAAE,EAAE,CAAC;;AAGN,IAAA,MAAM,MAAM,GAAGD,iBAAW,CAAC,MAAK;AAC9B,QAAA,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO;AAC1B,QAAA,IAAI,CAAC,GAAG,IAAI,QAAQ,CAAC,OAAO,EAAE;AAC5B,YAAA,KAAK,EAAE;YACP;QACF;QACA,SAAS,CAAC,MAAM,CAAC;QACjB,UAAU,CAAC,IAAI,CAAC;AAChB,QAAA,KAAK,GAAG,CAAC,KAAK,EAAE;AAClB,IAAA,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;IAEX,OAAO;QACL,IAAI;QACJ,MAAM;QACN,OAAO;QACP,QAAQ;QACR,SAAS;QACT,KAAK;AACL,QAAA,OAAO,EAAE,KAAK;QACd,IAAI;QACJ,MAAM;QACN,KAAK;QACL,QAAQ,EAAE,MAAM,CAAC,OAAO;KACzB;AACH;;"}
package/dist/index.d.ts CHANGED
@@ -24,10 +24,16 @@ interface UseSSEStreamReturn {
24
24
  msgCount: number;
25
25
  /** 已接收字符总数 */
26
26
  charCount: number;
27
- /** 发起一次连接(先销毁旧连接) */
27
+ /** 发起一次连接:销毁旧实例并清空已输出内容,从头开始(等价 restart) */
28
28
  start: () => void;
29
- /** 手动断开并销毁实例 */
29
+ /** 重新开始:丢弃已输出内容并新建实例(等价 start) */
30
+ restart: () => void;
31
+ /** 暂停:中断当前流,保留实例与已输出内容,可用 resume 继续 */
30
32
  stop: () => void;
33
+ /** 继续:复用实例从断点续传(无实例或上次已正常结束时退化为重新开始) */
34
+ resume: () => void;
35
+ /** 彻底停止:销毁实例与订阅并复位状态,已输出内容保留 */
36
+ close: () => void;
31
37
  /** 当前 PluginSSE 实例(便于 use() 追加插件等高级操作) */
32
38
  instance: PluginSSE | null;
33
39
  }
package/dist/index.mjs CHANGED
@@ -14,6 +14,10 @@ function useSSEStream(options) {
14
14
  const optionsRef = useRef(options);
15
15
  optionsRef.current = options;
16
16
  const sseRef = useRef(null);
17
+ /** 上一次连接是否正常结束(正常结束后续传位点已归零,resume 需从头开始) */
18
+ const endedRef = useRef(false);
19
+ /** 是否仍挂载,避免卸载时 destroy 触发的 closed 回调再更新状态 */
20
+ const mountedRef = useRef(true);
17
21
  const [text, setText] = useState('');
18
22
  const [status, setStatus] = useState('未连接');
19
23
  const [loading, setLoading] = useState(false);
@@ -21,15 +25,24 @@ function useSSEStream(options) {
21
25
  const [charCount, setCharCount] = useState(0);
22
26
  // 组件卸载:释放连接、清空订阅
23
27
  useEffect(() => {
28
+ mountedRef.current = true;
24
29
  return () => {
30
+ mountedRef.current = false;
25
31
  sseRef.current?.destroy();
26
32
  sseRef.current = null;
27
33
  };
28
34
  }, []);
35
+ // 暂停:中断当前流但保留实例与已输出内容,状态由 abort 事件更新
29
36
  const stop = useCallback(() => {
30
- sseRef.current?.destroy();
31
- sseRef.current = null;
32
- setStatus('已手动断开');
37
+ sseRef.current?.abort();
38
+ }, []);
39
+ // 彻底停止:销毁实例与订阅,状态由 closed 事件统一复位
40
+ const close = useCallback(() => {
41
+ if (sseRef.current) {
42
+ sseRef.current.destroy();
43
+ return;
44
+ }
45
+ setStatus('已停止');
33
46
  setLoading(false);
34
47
  }, []);
35
48
  const start = useCallback(() => {
@@ -41,6 +54,7 @@ function useSSEStream(options) {
41
54
  setCharCount(0);
42
55
  setStatus('连接中…');
43
56
  setLoading(true);
57
+ endedRef.current = false;
44
58
  const sse = new PluginSSE({
45
59
  url,
46
60
  method: method ?? 'GET',
@@ -50,6 +64,11 @@ function useSSEStream(options) {
50
64
  parser,
51
65
  plugins,
52
66
  });
67
+ // 每次(含自动重连、resume)发起连接都会触发,保证 loading 状态不丢失
68
+ sse.on('connecting', () => {
69
+ setStatus('连接中…');
70
+ setLoading(true);
71
+ });
53
72
  sse.on('open', ({ transport: name }) => {
54
73
  setStatus(`已连接(${name})`);
55
74
  onOpen?.({ transport: name });
@@ -61,6 +80,7 @@ function useSSEStream(options) {
61
80
  onMessage?.(data, event);
62
81
  });
63
82
  sse.on('end', () => {
83
+ endedRef.current = true;
64
84
  setStatus('流正常结束');
65
85
  setLoading(false);
66
86
  onEnd?.();
@@ -71,9 +91,32 @@ function useSSEStream(options) {
71
91
  setLoading(false);
72
92
  onError?.(err);
73
93
  });
94
+ sse.on('abort', () => {
95
+ setStatus('已暂停');
96
+ setLoading(false);
97
+ });
98
+ sse.on('closed', () => {
99
+ if (!mountedRef.current)
100
+ return;
101
+ endedRef.current = false;
102
+ sseRef.current = null;
103
+ setStatus('已停止');
104
+ setLoading(false);
105
+ });
74
106
  sseRef.current = sse;
75
107
  sse.connect();
76
108
  }, []);
109
+ // 继续:复用实例从断点续传;无实例或上次已正常结束时退化为重新开始
110
+ const resume = useCallback(() => {
111
+ const sse = sseRef.current;
112
+ if (!sse || endedRef.current) {
113
+ start();
114
+ return;
115
+ }
116
+ setStatus('连接中…');
117
+ setLoading(true);
118
+ void sse.start();
119
+ }, [start]);
77
120
  return {
78
121
  text,
79
122
  status,
@@ -81,7 +124,10 @@ function useSSEStream(options) {
81
124
  msgCount,
82
125
  charCount,
83
126
  start,
127
+ restart: start,
84
128
  stop,
129
+ resume,
130
+ close,
85
131
  instance: sseRef.current,
86
132
  };
87
133
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/useSSEStream.ts"],"sourcesContent":[null],"names":[],"mappings":";;;AAAA;;;;;;;AAOG;AAuCG,SAAU,YAAY,CAAC,OAA4B,EAAA;;AAEvD,IAAA,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC;AAClC,IAAA,UAAU,CAAC,OAAO,GAAG,OAAO;AAE5B,IAAA,MAAM,MAAM,GAAG,MAAM,CAAmB,IAAI,CAAC;IAC7C,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAC,EAAE,CAAC;IACpC,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC;IAC3C,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,YAAA,QAAQ,CAAC,OAAO,GAAG,KAAK;AACxB,YAAA,MAAM,CAAC,OAAO,GAAG,IAAI;YACrB,SAAS,CAAC,KAAK,CAAC;YAChB,UAAU,CAAC,KAAK,CAAC;AACnB,QAAA,CAAC,CAAC;AAEF,QAAA,MAAM,CAAC,OAAO,GAAG,GAAG;QACpB,GAAG,CAAC,OAAO,EAAE;IACf,CAAC,EAAE,EAAE,CAAC;;AAGN,IAAA,MAAM,MAAM,GAAG,WAAW,CAAC,MAAK;AAC9B,QAAA,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO;AAC1B,QAAA,IAAI,CAAC,GAAG,IAAI,QAAQ,CAAC,OAAO,EAAE;AAC5B,YAAA,KAAK,EAAE;YACP;QACF;QACA,SAAS,CAAC,MAAM,CAAC;QACjB,UAAU,CAAC,IAAI,CAAC;AAChB,QAAA,KAAK,GAAG,CAAC,KAAK,EAAE;AAClB,IAAA,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;IAEX,OAAO;QACL,IAAI;QACJ,MAAM;QACN,OAAO;QACP,QAAQ;QACR,SAAS;QACT,KAAK;AACL,QAAA,OAAO,EAAE,KAAK;QACd,IAAI;QACJ,MAAM;QACN,KAAK;QACL,QAAQ,EAAE,MAAM,CAAC,OAAO;KACzB;AACH;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sse-stream-plugin-react",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "React Hooks for sse-stream-plugin-sdk",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -24,19 +24,20 @@
24
24
  "files": [
25
25
  "dist",
26
26
  "LICENSE",
27
- "README.md"
27
+ "README.md",
28
+ "CHANGELOG.md"
28
29
  ],
29
- "scripts": {
30
- "build": "rollup -c",
31
- "build:prod": "rollup -c --environment NODE_ENV:production"
32
- },
33
30
  "peerDependencies": {
34
31
  "react": ">=16.8.0",
35
- "sse-stream-plugin-sdk": "^1.0.0"
32
+ "sse-stream-plugin-sdk": "^1.1.0"
36
33
  },
37
34
  "devDependencies": {
38
35
  "@types/react": "^19.2.18",
39
36
  "react": "^19.2.8",
40
- "sse-stream-plugin-sdk": "workspace:*"
37
+ "sse-stream-plugin-sdk": "1.1.1"
38
+ },
39
+ "scripts": {
40
+ "build": "rollup -c",
41
+ "build:prod": "rollup -c --environment NODE_ENV:production"
41
42
  }
42
- }
43
+ }