Skip to content

Commit 7f69281

Browse files
committed
docs: 添加文档
1 parent 57d86c8 commit 7f69281

File tree

3 files changed

+241
-13
lines changed

3 files changed

+241
-13
lines changed

README.md

Lines changed: 112 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,125 @@
1-
# tsdown-starter
1+
# @wyatex/event-source-parse
22

3-
A starter for creating a TypeScript package.
3+
[简体中文](./README.zh-CN.md)
44

5-
## Development
5+
[![NPM Version](https://img.shields.io/npm/v/@wyatex/event-source-parse?style=flat-square&color=cb3837)](https://www.npmjs.com/package/@wyatex/event-source-parse)
6+
[![License](https://img.shields.io/npm/l/@wyatex/event-source-parse?style=flat-square&color=blue)](https://github.com/wyatex/event-source-parse/blob/main/LICENSE)
7+
[![CI](https://img.shields.io/github/actions/workflow/status/wyatex/event-source-parse/ci.yml?style=flat-square&label=build)](https://github.com/wyatex/event-source-parse/actions)
8+
[![Codecov](https://img.shields.io/codecov/c/github/wyatex/event-source-parse?style=flat-square)](https://codecov.io/gh/wyatex/event-source-parse)
69

7-
- Install dependencies:
10+
A robust, zero-dependency parser for **Server-Sent Events (SSE)** streams.
11+
12+
This library is designed to consume `ReadableStream` or `AsyncIterable` and parse them into event messages. It is written in TypeScript and optimized for modern runtimes like Node.js, Bun, Deno, and Browsers.
13+
14+
### ✨ Key Features
15+
16+
* **Universal Support**: Works with standard Web API `ReadableStream` and Node.js streams.
17+
* **🧩 Azure OpenAI Compatible**: Includes a specific flush mechanism to handle streams that don't end with a newline (common in Azure OpenAI / LangChain scenarios), ensuring no data is lost.
18+
* **TypeScript**: Fully typed with TS sources included.
19+
* **Lightweight**: No runtime dependencies.
20+
21+
## 📦 Installation
822

923
```bash
10-
npm install
24+
# npm
25+
npm install @wyatex/event-source-parse
26+
27+
# bun
28+
bun add @wyatex/event-source-parse
29+
30+
# pnpm
31+
pnpm add @wyatex/event-source-parse
32+
33+
# yarn
34+
yarn add @wyatex/event-source-parse
1135
```
1236

13-
- Run the unit tests:
37+
## 🚀 Usage
1438

15-
```bash
16-
npm run test
39+
### 1. High-Level Usage (Recommended)
40+
41+
The easiest way to consume a stream is using the helper function `convertEventStreamToIterableReadableDataStream`. This converts a raw SSE stream directly into an async iterable of data strings.
42+
43+
```typescript
44+
import { convertEventStreamToIterableReadableDataStream } from '@wyatex/event-source-parse'
45+
46+
async function consumeStream() {
47+
const response = await fetch('https://api.openai.com/v1/chat/completions', {
48+
method: 'POST',
49+
body: JSON.stringify({ stream: true, /* ... */ }),
50+
})
51+
52+
if (!response.body) throw new Error('No body')
53+
54+
// Convert the raw stream into an iterable of data strings
55+
const stream = convertEventStreamToIterableReadableDataStream(response.body)
56+
57+
for await (const chunk of stream) {
58+
console.log('Received chunk:', chunk)
59+
}
60+
}
61+
```
62+
63+
### 2. Low-Level Control (Pipeline)
64+
65+
If you need full control over the parsing process (e.g., accessing `event` ID, `retry` time, or custom event types), you can compose the parser functions manually.
66+
67+
```typescript
68+
import { getBytes, getLines, getMessages } from '@wyatex/event-source-parse'
69+
70+
async function parseCustomStream(stream: ReadableStream) {
71+
// 1. Create a message handler
72+
const onMessage = (msg) => {
73+
console.log('Event:', msg.event)
74+
console.log('Data:', msg.data)
75+
console.log('ID:', msg.id)
76+
}
77+
78+
// 2. Create the pipeline
79+
// getMessages -> processes lines into EventSourceMessage objects
80+
// getLines -> processes raw bytes into lines
81+
const processLine = getMessages(onMessage)
82+
const processChunk = getLines(processLine)
83+
84+
// 3. Start reading bytes from the stream
85+
await getBytes(stream, processChunk)
86+
}
87+
```
88+
89+
### 3. Handling Metadata Events
90+
91+
The high-level helpers allow you to hook into specific events like `metadata` without disrupting the main data flow.
92+
93+
```typescript
94+
const stream = convertEventStreamToIterableReadableDataStream(
95+
response.body,
96+
(metadata) => {
97+
console.log('Received metadata:', metadata)
98+
}
99+
)
17100
```
18101

19-
- Build the library:
102+
## 🛠️ Development
103+
104+
This project uses **Bun** for development.
20105

21106
```bash
22-
npm run build
107+
# Install dependencies
108+
bun install
109+
110+
# Run tests
111+
bun run test
112+
113+
# Run tests with coverage
114+
bun run test:coverage
115+
116+
# Lint code
117+
bun run lint
118+
119+
# Build library
120+
bun run build
23121
```
122+
123+
## 📄 License
124+
125+
MIT

README.zh-CN.md

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
# @wyatex/event-source-parse
2+
3+
[English](./README.md)
4+
5+
[![NPM Version](https://img.shields.io/npm/v/@wyatex/event-source-parse?style=flat-square&color=cb3837)](https://www.npmjs.com/package/@wyatex/event-source-parse)
6+
[![License](https://img.shields.io/npm/l/@wyatex/event-source-parse?style=flat-square&color=blue)](https://github.com/wyatex/event-source-parse/blob/main/LICENSE)
7+
[![CI](https://img.shields.io/github/actions/workflow/status/wyatex/event-source-parse/ci.yml?style=flat-square&label=build)](https://github.com/wyatex/event-source-parse/actions)
8+
[![Codecov](https://img.shields.io/codecov/c/github/wyatex/event-source-parse?style=flat-square)](https://codecov.io/gh/wyatex/event-source-parse)
9+
10+
一个健壮的、零依赖的 **Server-Sent Events (SSE)** 流解析器。
11+
12+
该库旨在接收 `ReadableStream``AsyncIterable` 并将其解析为标准事件消息。它完全使用 TypeScript 编写,并针对 Node.js、Bun、Deno 和现代浏览器等运行时进行了优化。
13+
14+
### ✨ 主要特性
15+
16+
* **通用支持**:同时支持标准 Web API `ReadableStream` 和 Node.js 流。
17+
* **🧩 Azure OpenAI 兼容**:内置了特殊的刷新(flush)机制,能够处理不以换行符结尾的流(这在 Azure OpenAI / LangChain 场景中很常见),确保最后一条消息不会丢失。
18+
* **TypeScript**:完全类型化,分发包中包含 TS 源码。
19+
* **轻量级**:无运行时依赖。
20+
21+
## 📦 安装
22+
23+
```bash
24+
# npm
25+
npm install @wyatex/event-source-parse
26+
27+
# bun
28+
bun add @wyatex/event-source-parse
29+
30+
# pnpm
31+
pnpm add @wyatex/event-source-parse
32+
33+
# yarn
34+
yarn add @wyatex/event-source-parse
35+
```
36+
37+
## 🚀 使用方法
38+
39+
### 1. 高级用法(推荐)
40+
41+
消费流数据最简单的方法是使用辅助函数 `convertEventStreamToIterableReadableDataStream`。它可以直接将原始 SSE 流转换为由 `data` 字符串组成的异步可迭代对象(Async Iterable)。
42+
43+
```typescript
44+
import { convertEventStreamToIterableReadableDataStream } from '@wyatex/event-source-parse'
45+
46+
async function consumeStream() {
47+
const response = await fetch('https://api.openai.com/v1/chat/completions', {
48+
method: 'POST',
49+
body: JSON.stringify({ stream: true, /* ... */ }),
50+
})
51+
52+
if (!response.body) throw new Error('No body')
53+
54+
// 将原始流转换为数据字符串的迭代器
55+
const stream = convertEventStreamToIterableReadableDataStream(response.body)
56+
57+
for await (const chunk of stream) {
58+
console.log('收到数据块:', chunk)
59+
}
60+
}
61+
```
62+
63+
### 2. 低级控制(管道模式)
64+
65+
如果你需要完全控制解析过程(例如获取 `event` ID、`retry` 重试时间或自定义事件类型),可以手动组合解析器函数。
66+
67+
```typescript
68+
import { getBytes, getLines, getMessages } from '@wyatex/event-source-parse'
69+
70+
async function parseCustomStream(stream: ReadableStream) {
71+
// 1. 创建消息处理器
72+
const onMessage = (msg) => {
73+
console.log('事件类型:', msg.event)
74+
console.log('数据内容:', msg.data)
75+
console.log('事件ID:', msg.id)
76+
}
77+
78+
// 2. 创建处理管道
79+
// getMessages -> 将行数据处理成 EventSourceMessage 对象
80+
// getLines -> 将原始字节处理成行
81+
const processLine = getMessages(onMessage)
82+
const processChunk = getLines(processLine)
83+
84+
// 3. 开始从流中读取字节
85+
await getBytes(stream, processChunk)
86+
}
87+
```
88+
89+
### 3. 处理元数据事件
90+
91+
高级辅助函数允许你在不中断主数据流的情况下,通过回调钩入特定事件(如 `metadata`)。
92+
93+
```typescript
94+
const stream = convertEventStreamToIterableReadableDataStream(
95+
response.body,
96+
(metadata) => {
97+
console.log('收到元数据:', metadata)
98+
}
99+
)
100+
```
101+
102+
## 🛠️ 本地开发
103+
104+
本项目使用 **Bun** 进行开发。
105+
106+
```bash
107+
# 安装依赖
108+
bun install
109+
110+
# 运行测试
111+
bun run test
112+
113+
# 运行带覆盖率的测试
114+
bun run test:coverage
115+
116+
# 代码风格检查 (Lint)
117+
bun run lint
118+
119+
# 构建库
120+
bun run build
121+
```
122+
123+
## 📄 许可证
124+
125+
MIT

package.json

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515
},
1616
"exports": {
1717
".": {
18-
"import": "./dist/index.mjs",
19-
"require": "./dist/index.cjs"
18+
"require": "./dist/index.cjs",
19+
"import": "./dist/index.mjs"
2020
},
2121
"./package.json": "./package.json"
2222
},
@@ -49,6 +49,7 @@
4949
"vitest": "^4.0.15"
5050
},
5151
"publishConfig": {
52-
"registry": "https://registry.npmjs.org"
52+
"registry": "https://registry.npmjs.org",
53+
"access": "public"
5354
}
5455
}

0 commit comments

Comments
 (0)