@ahoo-wang/fetcher-eventstream 2.9.6 → 2.9.8
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 +119 -1
- package/README.zh-CN.md +119 -1
- package/dist/eventStreamConverter.d.ts +76 -10
- package/dist/eventStreamConverter.d.ts.map +1 -1
- package/dist/eventStreamResultExtractor.d.ts +35 -8
- package/dist/eventStreamResultExtractor.d.ts.map +1 -1
- package/dist/index.d.ts +48 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.es.js +107 -33
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +3 -3
- package/dist/index.umd.js.map +1 -1
- package/dist/jsonServerSentEventTransformStream.d.ts +134 -2
- package/dist/jsonServerSentEventTransformStream.d.ts.map +1 -1
- package/dist/readableStreamAsyncIterable.d.ts +37 -1
- package/dist/readableStreamAsyncIterable.d.ts.map +1 -1
- package/dist/readableStreams.d.ts +21 -0
- package/dist/readableStreams.d.ts.map +1 -1
- package/dist/responses.d.ts +5 -3
- package/dist/responses.d.ts.map +1 -1
- package/dist/serverSentEventTransformStream.d.ts +42 -0
- package/dist/serverSentEventTransformStream.d.ts.map +1 -1
- package/dist/textLineTransformStream.d.ts +64 -3
- package/dist/textLineTransformStream.d.ts.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -24,6 +24,7 @@ APIs.
|
|
|
24
24
|
- **🛡️ TypeScript Support**: Complete TypeScript type definitions
|
|
25
25
|
- **⚡ Performance Optimized**: Efficient parsing and streaming for high-performance applications
|
|
26
26
|
- **🤖 LLM Streaming Ready**: Native support for streaming responses from popular LLM APIs like OpenAI GPT, Claude, etc.
|
|
27
|
+
- **🔚 Stream Termination**: Automatic stream termination detection for clean resource management and completion handling
|
|
27
28
|
|
|
28
29
|
## 🚀 Quick Start
|
|
29
30
|
|
|
@@ -245,6 +246,47 @@ for await (const event of response.requiredJsonEventStream<MyDataType>()) {
|
|
|
245
246
|
}
|
|
246
247
|
```
|
|
247
248
|
|
|
249
|
+
### Advanced Usage with Termination Detection
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
import { Fetcher } from '@ahoo-wang/fetcher';
|
|
253
|
+
import {
|
|
254
|
+
toJsonServerSentEventStream,
|
|
255
|
+
type TerminateDetector,
|
|
256
|
+
} from '@ahoo-wang/fetcher-eventstream';
|
|
257
|
+
|
|
258
|
+
const fetcher = new Fetcher({
|
|
259
|
+
baseURL: 'https://api.openai.com/v1',
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
// Define termination detector for OpenAI-style completion
|
|
263
|
+
const terminateOnDone: TerminateDetector = event => event.data === '[DONE]';
|
|
264
|
+
|
|
265
|
+
// Get raw event stream
|
|
266
|
+
const response = await fetcher.post('/chat/completions', {
|
|
267
|
+
body: {
|
|
268
|
+
model: 'gpt-3.5-turbo',
|
|
269
|
+
messages: [{ role: 'user', content: 'Hello!' }],
|
|
270
|
+
stream: true,
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
// Convert to typed JSON stream with automatic termination
|
|
275
|
+
const jsonStream = toJsonServerSentEventStream<ChatCompletionChunk>(
|
|
276
|
+
response.requiredEventStream(),
|
|
277
|
+
terminateOnDone,
|
|
278
|
+
);
|
|
279
|
+
|
|
280
|
+
// Process streaming response with automatic termination
|
|
281
|
+
for await (const event of jsonStream) {
|
|
282
|
+
const content = event.data.choices[0]?.delta?.content;
|
|
283
|
+
if (content) {
|
|
284
|
+
console.log('Token:', content);
|
|
285
|
+
// Stream automatically terminates when '[DONE]' is received
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
```
|
|
289
|
+
|
|
248
290
|
### Manual Conversion
|
|
249
291
|
|
|
250
292
|
```typescript
|
|
@@ -310,24 +352,49 @@ for await (const event of response.requiredEventStream()) {
|
|
|
310
352
|
### toJsonServerSentEventStream
|
|
311
353
|
|
|
312
354
|
Converts a `ServerSentEventStream` to a `JsonServerSentEventStream<DATA>` for handling Server-Sent Events with JSON
|
|
313
|
-
data.
|
|
355
|
+
data. Optionally supports stream termination detection for automatic stream closure.
|
|
314
356
|
|
|
315
357
|
#### Signature
|
|
316
358
|
|
|
317
359
|
```typescript
|
|
318
360
|
function toJsonServerSentEventStream<DATA>(
|
|
319
361
|
serverSentEventStream: ServerSentEventStream,
|
|
362
|
+
terminateDetector?: TerminateDetector,
|
|
320
363
|
): JsonServerSentEventStream<DATA>;
|
|
321
364
|
```
|
|
322
365
|
|
|
323
366
|
#### Parameters
|
|
324
367
|
|
|
325
368
|
- `serverSentEventStream`: The `ServerSentEventStream` to convert
|
|
369
|
+
- `terminateDetector`: Optional function to detect when the stream should be terminated. When provided, the stream will automatically close when the detector returns `true` for an event.
|
|
326
370
|
|
|
327
371
|
#### Returns
|
|
328
372
|
|
|
329
373
|
- `JsonServerSentEventStream<DATA>`: A readable stream of `JsonServerSentEvent<DATA>` objects
|
|
330
374
|
|
|
375
|
+
#### Examples
|
|
376
|
+
|
|
377
|
+
```typescript
|
|
378
|
+
// Basic usage without termination detection
|
|
379
|
+
const jsonStream = toJsonServerSentEventStream<MyData>(serverSentEventStream);
|
|
380
|
+
|
|
381
|
+
// With termination detection for OpenAI-style completion
|
|
382
|
+
const terminateOnDone: TerminateDetector = event => event.data === '[DONE]';
|
|
383
|
+
const terminatingStream = toJsonServerSentEventStream<MyData>(
|
|
384
|
+
serverSentEventStream,
|
|
385
|
+
terminateOnDone,
|
|
386
|
+
);
|
|
387
|
+
|
|
388
|
+
// Custom termination logic
|
|
389
|
+
const terminateOnError: TerminateDetector = event => {
|
|
390
|
+
return event.event === 'error' || event.data.includes('ERROR');
|
|
391
|
+
};
|
|
392
|
+
const errorHandlingStream = toJsonServerSentEventStream<MyData>(
|
|
393
|
+
serverSentEventStream,
|
|
394
|
+
terminateOnError,
|
|
395
|
+
);
|
|
396
|
+
```
|
|
397
|
+
|
|
331
398
|
### JsonServerSentEvent
|
|
332
399
|
|
|
333
400
|
Interface defining the structure of a Server-Sent Event with JSON data.
|
|
@@ -348,6 +415,57 @@ type JsonServerSentEventStream<DATA> = ReadableStream<
|
|
|
348
415
|
>;
|
|
349
416
|
```
|
|
350
417
|
|
|
418
|
+
### TerminateDetector
|
|
419
|
+
|
|
420
|
+
A function type for detecting when a Server-Sent Event stream should be terminated. This is commonly used with LLM APIs that send a special termination event to signal the end of a response stream.
|
|
421
|
+
|
|
422
|
+
#### Signature
|
|
423
|
+
|
|
424
|
+
```typescript
|
|
425
|
+
type TerminateDetector = (event: ServerSentEvent) => boolean;
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
#### Parameters
|
|
429
|
+
|
|
430
|
+
- `event`: The current `ServerSentEvent` being processed
|
|
431
|
+
|
|
432
|
+
#### Returns
|
|
433
|
+
|
|
434
|
+
- `boolean`: `true` if the stream should be terminated, `false` otherwise
|
|
435
|
+
|
|
436
|
+
#### Examples
|
|
437
|
+
|
|
438
|
+
```typescript
|
|
439
|
+
// OpenAI-style termination (common pattern)
|
|
440
|
+
const terminateOnDone: TerminateDetector = event => event.data === '[DONE]';
|
|
441
|
+
|
|
442
|
+
// Event-based termination
|
|
443
|
+
const terminateOnComplete: TerminateDetector = event => event.event === 'done';
|
|
444
|
+
|
|
445
|
+
// Custom termination with multiple conditions
|
|
446
|
+
const terminateOnFinish: TerminateDetector = event => {
|
|
447
|
+
return (
|
|
448
|
+
event.event === 'done' ||
|
|
449
|
+
event.event === 'error' ||
|
|
450
|
+
event.data === '[DONE]' ||
|
|
451
|
+
event.data.includes('TERMINATE')
|
|
452
|
+
);
|
|
453
|
+
};
|
|
454
|
+
|
|
455
|
+
// Usage with toJsonServerSentEventStream
|
|
456
|
+
const stream = toJsonServerSentEventStream<MyData>(
|
|
457
|
+
serverSentEventStream,
|
|
458
|
+
terminateOnDone,
|
|
459
|
+
);
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
#### Common Use Cases
|
|
463
|
+
|
|
464
|
+
- **LLM Streaming**: Detect completion markers like `[DONE]` from OpenAI, Claude, or other LLM APIs
|
|
465
|
+
- **Error Handling**: Terminate streams when error events are received
|
|
466
|
+
- **Custom Protocols**: Implement application-specific termination logic
|
|
467
|
+
- **Resource Management**: Automatically close streams when certain conditions are met
|
|
468
|
+
|
|
351
469
|
### toServerSentEventStream
|
|
352
470
|
|
|
353
471
|
Converts a `Response` object with a `text/event-stream` body to a `ServerSentEventStream`.
|
package/README.zh-CN.md
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
- **🛡️ TypeScript 支持**:完整的 TypeScript 类型定义
|
|
21
21
|
- **⚡ 性能优化**:高效的解析和流处理,适用于高性能应用
|
|
22
22
|
- **🤖 LLM 流准备就绪**: 原生支持来自流行 LLM API(如 OpenAI GPT、Claude 等)的流式响应
|
|
23
|
+
- **🔚 流终止检测**:自动流终止检测,实现干净的资源管理和完成处理
|
|
23
24
|
|
|
24
25
|
## 🚀 快速开始
|
|
25
26
|
|
|
@@ -216,6 +217,47 @@ for await (const event of response.requiredJsonEventStream<MyDataType>()) {
|
|
|
216
217
|
}
|
|
217
218
|
```
|
|
218
219
|
|
|
220
|
+
### 高级用法与终止检测
|
|
221
|
+
|
|
222
|
+
```typescript
|
|
223
|
+
import { Fetcher } from '@ahoo-wang/fetcher';
|
|
224
|
+
import {
|
|
225
|
+
toJsonServerSentEventStream,
|
|
226
|
+
type TerminateDetector,
|
|
227
|
+
} from '@ahoo-wang/fetcher-eventstream';
|
|
228
|
+
|
|
229
|
+
const fetcher = new Fetcher({
|
|
230
|
+
baseURL: 'https://api.openai.com/v1',
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
// 定义 OpenAI 风格完成的终止检测器
|
|
234
|
+
const terminateOnDone: TerminateDetector = event => event.data === '[DONE]';
|
|
235
|
+
|
|
236
|
+
// 获取原始事件流
|
|
237
|
+
const response = await fetcher.post('/chat/completions', {
|
|
238
|
+
body: {
|
|
239
|
+
model: 'gpt-3.5-turbo',
|
|
240
|
+
messages: [{ role: 'user', content: '你好!' }],
|
|
241
|
+
stream: true,
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
// 转换为带自动终止的类型化 JSON 流
|
|
246
|
+
const jsonStream = toJsonServerSentEventStream<ChatCompletionChunk>(
|
|
247
|
+
response.requiredEventStream(),
|
|
248
|
+
terminateOnDone,
|
|
249
|
+
);
|
|
250
|
+
|
|
251
|
+
// 处理带自动终止的流式响应
|
|
252
|
+
for await (const event of jsonStream) {
|
|
253
|
+
const content = event.data.choices[0]?.delta?.content;
|
|
254
|
+
if (content) {
|
|
255
|
+
console.log('令牌:', content);
|
|
256
|
+
// 当收到 '[DONE]' 时流会自动终止
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
219
261
|
### 手动转换
|
|
220
262
|
|
|
221
263
|
```typescript
|
|
@@ -278,24 +320,49 @@ for await (const event of response.requiredEventStream()) {
|
|
|
278
320
|
|
|
279
321
|
### toJsonServerSentEventStream
|
|
280
322
|
|
|
281
|
-
将 `ServerSentEventStream` 转换为 `JsonServerSentEventStream<DATA>`,用于处理带有 JSON
|
|
323
|
+
将 `ServerSentEventStream` 转换为 `JsonServerSentEventStream<DATA>`,用于处理带有 JSON 数据的服务器发送事件。可选支持流终止检测以实现自动流关闭。
|
|
282
324
|
|
|
283
325
|
#### 签名
|
|
284
326
|
|
|
285
327
|
```typescript
|
|
286
328
|
function toJsonServerSentEventStream<DATA>(
|
|
287
329
|
serverSentEventStream: ServerSentEventStream,
|
|
330
|
+
terminateDetector?: TerminateDetector,
|
|
288
331
|
): JsonServerSentEventStream<DATA>;
|
|
289
332
|
```
|
|
290
333
|
|
|
291
334
|
#### 参数
|
|
292
335
|
|
|
293
336
|
- `serverSentEventStream`:要转换的 ServerSentEventStream
|
|
337
|
+
- `terminateDetector`:可选的函数,用于检测何时应该终止流。当提供时,当检测器对某个事件返回 `true` 时,流将自动关闭。
|
|
294
338
|
|
|
295
339
|
#### 返回
|
|
296
340
|
|
|
297
341
|
- `JsonServerSentEventStream<DATA>`:带有 JSON 数据的 ServerSentEvent 对象的可读流
|
|
298
342
|
|
|
343
|
+
#### 示例
|
|
344
|
+
|
|
345
|
+
```typescript
|
|
346
|
+
// 基本用法,不使用终止检测
|
|
347
|
+
const jsonStream = toJsonServerSentEventStream<MyData>(serverSentEventStream);
|
|
348
|
+
|
|
349
|
+
// 使用终止检测处理 OpenAI 风格的完成
|
|
350
|
+
const terminateOnDone: TerminateDetector = event => event.data === '[DONE]';
|
|
351
|
+
const terminatingStream = toJsonServerSentEventStream<MyData>(
|
|
352
|
+
serverSentEventStream,
|
|
353
|
+
terminateOnDone,
|
|
354
|
+
);
|
|
355
|
+
|
|
356
|
+
// 自定义终止逻辑
|
|
357
|
+
const terminateOnError: TerminateDetector = event => {
|
|
358
|
+
return event.event === 'error' || event.data.includes('ERROR');
|
|
359
|
+
};
|
|
360
|
+
const errorHandlingStream = toJsonServerSentEventStream<MyData>(
|
|
361
|
+
serverSentEventStream,
|
|
362
|
+
terminateOnError,
|
|
363
|
+
);
|
|
364
|
+
```
|
|
365
|
+
|
|
299
366
|
### JsonServerSentEvent
|
|
300
367
|
|
|
301
368
|
定义带有 JSON 数据的服务器发送事件结构的接口。
|
|
@@ -316,6 +383,57 @@ type JsonServerSentEventStream<DATA> = ReadableStream<
|
|
|
316
383
|
>;
|
|
317
384
|
```
|
|
318
385
|
|
|
386
|
+
### TerminateDetector
|
|
387
|
+
|
|
388
|
+
用于检测服务器发送事件流何时应该终止的函数类型。这通常用于 LLM API 发送特殊终止事件来表示响应流结束的情况。
|
|
389
|
+
|
|
390
|
+
#### 签名
|
|
391
|
+
|
|
392
|
+
```typescript
|
|
393
|
+
type TerminateDetector = (event: ServerSentEvent) => boolean;
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
#### 参数
|
|
397
|
+
|
|
398
|
+
- `event`:当前正在处理的 `ServerSentEvent`
|
|
399
|
+
|
|
400
|
+
#### 返回
|
|
401
|
+
|
|
402
|
+
- `boolean`:如果应该终止流则返回 `true`,否则返回 `false`
|
|
403
|
+
|
|
404
|
+
#### 示例
|
|
405
|
+
|
|
406
|
+
```typescript
|
|
407
|
+
// OpenAI 风格的终止(常见模式)
|
|
408
|
+
const terminateOnDone: TerminateDetector = event => event.data === '[DONE]';
|
|
409
|
+
|
|
410
|
+
// 基于事件的终止
|
|
411
|
+
const terminateOnComplete: TerminateDetector = event => event.event === 'done';
|
|
412
|
+
|
|
413
|
+
// 具有多个条件的自定义终止
|
|
414
|
+
const terminateOnFinish: TerminateDetector = event => {
|
|
415
|
+
return (
|
|
416
|
+
event.event === 'done' ||
|
|
417
|
+
event.event === 'error' ||
|
|
418
|
+
event.data === '[DONE]' ||
|
|
419
|
+
event.data.includes('TERMINATE')
|
|
420
|
+
);
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
// 与 toJsonServerSentEventStream 一起使用
|
|
424
|
+
const stream = toJsonServerSentEventStream<MyData>(
|
|
425
|
+
serverSentEventStream,
|
|
426
|
+
terminateOnDone,
|
|
427
|
+
);
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
#### 常见用例
|
|
431
|
+
|
|
432
|
+
- **LLM 流式传输**:检测来自 OpenAI、Claude 或其他 LLM API 的完成标记,如 `[DONE]`
|
|
433
|
+
- **错误处理**:在收到错误事件时终止流
|
|
434
|
+
- **自定义协议**:实现应用程序特定的终止逻辑
|
|
435
|
+
- **资源管理**:在满足特定条件时自动关闭流
|
|
436
|
+
|
|
319
437
|
### toServerSentEventStream
|
|
320
438
|
|
|
321
439
|
将带有 `text/event-stream` 主体的 Response 对象转换为 ServerSentEvent 对象的可读流。
|
|
@@ -2,33 +2,99 @@ import { ServerSentEvent } from './serverSentEventTransformStream';
|
|
|
2
2
|
import { FetcherError } from '@ahoo-wang/fetcher';
|
|
3
3
|
/**
|
|
4
4
|
* A ReadableStream of ServerSentEvent objects.
|
|
5
|
+
*
|
|
6
|
+
* This type represents a stream that yields Server-Sent Event objects as they are parsed
|
|
7
|
+
* from a raw event stream. Each chunk in the stream contains a complete SSE event with
|
|
8
|
+
* its metadata (event type, ID, retry interval) and data.
|
|
9
|
+
*
|
|
10
|
+
* @see {@link ServerSentEvent} for the structure of individual events
|
|
11
|
+
* @see {@link toServerSentEventStream} for converting HTTP responses to this type
|
|
5
12
|
*/
|
|
6
13
|
export type ServerSentEventStream = ReadableStream<ServerSentEvent>;
|
|
7
14
|
/**
|
|
8
15
|
* Custom error class for event stream conversion errors.
|
|
9
|
-
*
|
|
16
|
+
*
|
|
17
|
+
* This error is thrown when there are issues converting an HTTP Response to a ServerSentEventStream.
|
|
18
|
+
* It extends FetcherError to provide additional context about the failed conversion, including
|
|
19
|
+
* the original Response object and any underlying cause.
|
|
20
|
+
*
|
|
21
|
+
* @extends {FetcherError}
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```typescript
|
|
25
|
+
* try {
|
|
26
|
+
* const eventStream = toServerSentEventStream(response);
|
|
27
|
+
* } catch (error) {
|
|
28
|
+
* if (error instanceof EventStreamConvertError) {
|
|
29
|
+
* console.error('Failed to convert response to event stream:', error.message);
|
|
30
|
+
* console.log('Response status:', error.response.status);
|
|
31
|
+
* }
|
|
32
|
+
* }
|
|
33
|
+
* ```
|
|
10
34
|
*/
|
|
11
35
|
export declare class EventStreamConvertError extends FetcherError {
|
|
12
36
|
readonly response: Response;
|
|
13
37
|
/**
|
|
14
38
|
* Creates a new EventStreamConvertError instance.
|
|
15
|
-
*
|
|
39
|
+
*
|
|
40
|
+
* @param response - The Response object associated with the error, providing context
|
|
41
|
+
* about the failed conversion (status, headers, etc.)
|
|
16
42
|
* @param errorMsg - Optional error message describing what went wrong during conversion
|
|
17
|
-
* @param cause - Optional underlying error that caused this error
|
|
43
|
+
* @param cause - Optional underlying error that caused this conversion error
|
|
18
44
|
*/
|
|
19
45
|
constructor(response: Response, errorMsg?: string, cause?: Error | any);
|
|
20
46
|
}
|
|
21
47
|
/**
|
|
22
48
|
* Converts a Response object to a ServerSentEventStream.
|
|
23
49
|
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
50
|
+
* This function takes an HTTP Response object and converts its body into a stream of
|
|
51
|
+
* Server-Sent Event objects. The conversion process involves several transformation steps:
|
|
52
|
+
*
|
|
53
|
+
* 1. **TextDecoderStream**: Decodes the raw Uint8Array response body to UTF-8 strings
|
|
54
|
+
* 2. **TextLineTransformStream**: Splits the text stream into individual lines
|
|
55
|
+
* 3. **ServerSentEventTransformStream**: Parses the line-based SSE format into structured events
|
|
56
|
+
*
|
|
57
|
+
* The resulting stream can be consumed using async iteration or other stream methods.
|
|
58
|
+
*
|
|
59
|
+
* @param response - The HTTP Response object to convert. Must have a readable body stream.
|
|
60
|
+
* @returns A ReadableStream that yields ServerSentEvent objects as they are parsed from the response
|
|
61
|
+
* @throws {EventStreamConvertError} If the response body is null or cannot be processed
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```typescript
|
|
65
|
+
* // Convert an SSE response to an event stream
|
|
66
|
+
* const response = await fetch('/api/events');
|
|
67
|
+
* const eventStream = toServerSentEventStream(response);
|
|
68
|
+
*
|
|
69
|
+
* // Consume events asynchronously
|
|
70
|
+
* for await (const event of eventStream) {
|
|
71
|
+
* console.log(`Event: ${event.event}, Data: ${event.data}`);
|
|
72
|
+
*
|
|
73
|
+
* // Handle different event types
|
|
74
|
+
* switch (event.event) {
|
|
75
|
+
* case 'message':
|
|
76
|
+
* handleMessage(event.data);
|
|
77
|
+
* break;
|
|
78
|
+
* case 'error':
|
|
79
|
+
* handleError(event.data);
|
|
80
|
+
* break;
|
|
81
|
+
* }
|
|
82
|
+
* }
|
|
83
|
+
* ```
|
|
28
84
|
*
|
|
29
|
-
* @
|
|
30
|
-
*
|
|
31
|
-
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```typescript
|
|
87
|
+
* // Handle conversion errors
|
|
88
|
+
* try {
|
|
89
|
+
* const eventStream = toServerSentEventStream(response);
|
|
90
|
+
* // Use the stream...
|
|
91
|
+
* } catch (error) {
|
|
92
|
+
* if (error instanceof EventStreamConvertError) {
|
|
93
|
+
* console.error('Event stream conversion failed:', error.message);
|
|
94
|
+
* console.log('Response status:', error.response.status);
|
|
95
|
+
* }
|
|
96
|
+
* }
|
|
97
|
+
* ```
|
|
32
98
|
*/
|
|
33
99
|
export declare function toServerSentEventStream(response: Response): ServerSentEventStream;
|
|
34
100
|
//# sourceMappingURL=eventStreamConverter.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eventStreamConverter.d.ts","sourceRoot":"","sources":["../src/eventStreamConverter.ts"],"names":[],"mappings":"AAcA,OAAO,EACL,KAAK,eAAe,EAErB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD
|
|
1
|
+
{"version":3,"file":"eventStreamConverter.d.ts","sourceRoot":"","sources":["../src/eventStreamConverter.ts"],"names":[],"mappings":"AAcA,OAAO,EACL,KAAK,eAAe,EAErB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD;;;;;;;;;GASG;AACH,MAAM,MAAM,qBAAqB,GAAG,cAAc,CAAC,eAAe,CAAC,CAAC;AAEpE;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qBAAa,uBAAwB,SAAQ,YAAY;aAUrC,QAAQ,EAAE,QAAQ;IATpC;;;;;;;OAOG;gBAEe,QAAQ,EAAE,QAAQ,EAClC,QAAQ,CAAC,EAAE,MAAM,EACjB,KAAK,CAAC,EAAE,KAAK,GAAG,GAAG;CAOtB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AACH,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,QAAQ,GACjB,qBAAqB,CASvB"}
|
|
@@ -2,19 +2,46 @@ import { ResultExtractor } from '@ahoo-wang/fetcher';
|
|
|
2
2
|
import { ServerSentEventStream } from './eventStreamConverter';
|
|
3
3
|
import { JsonServerSentEventStream } from './jsonServerSentEventTransformStream';
|
|
4
4
|
/**
|
|
5
|
-
* ServerSentEventStream result extractor
|
|
5
|
+
* ServerSentEventStream result extractor for Fetcher HTTP client.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* This result extractor is designed to work with the Fetcher HTTP client library.
|
|
8
|
+
* It extracts a ServerSentEventStream from an HTTP response that contains Server-Sent Events.
|
|
9
|
+
* The extractor validates that the response supports event streaming and converts the
|
|
10
|
+
* response body into a properly typed event stream.
|
|
11
|
+
*
|
|
12
|
+
* This extractor should be used when you want to consume raw Server-Sent Events
|
|
13
|
+
* without JSON parsing, maintaining the original string data format.
|
|
14
|
+
*
|
|
15
|
+
* @param exchange - The FetchExchange object containing request and response information
|
|
16
|
+
* @returns A ReadableStream that yields ServerSentEvent objects as they are parsed from the response
|
|
17
|
+
* @throws {ExchangeError} When the server response does not support ServerSentEventStream
|
|
18
|
+
* (e.g., wrong content type, no response body)
|
|
19
|
+
*
|
|
20
|
+
*
|
|
21
|
+
* @see {@link ServerSentEventStream} for the stream type
|
|
22
|
+
* @see {@link JsonEventStreamResultExtractor} for JSON-parsed event streams
|
|
10
23
|
*/
|
|
11
24
|
export declare const EventStreamResultExtractor: ResultExtractor<ServerSentEventStream>;
|
|
12
25
|
/**
|
|
13
|
-
* JsonServerSentEventStream result extractor
|
|
26
|
+
* JsonServerSentEventStream result extractor for Fetcher HTTP client.
|
|
27
|
+
*
|
|
28
|
+
* This result extractor is designed to work with the Fetcher HTTP client library.
|
|
29
|
+
* It extracts a JsonServerSentEventStream from an HTTP response that contains Server-Sent Events
|
|
30
|
+
* with JSON data. The extractor validates that the response supports event streaming and converts
|
|
31
|
+
* the response body into a properly typed event stream with automatic JSON parsing.
|
|
32
|
+
*
|
|
33
|
+
* This extractor should be used when you want to consume Server-Sent Events where the event
|
|
34
|
+
* data is JSON-formatted, providing type-safe access to parsed JSON objects instead of raw strings.
|
|
35
|
+
*
|
|
36
|
+
* @template DATA - The expected type of the JSON data in the server-sent events
|
|
37
|
+
* @param exchange - The FetchExchange object containing request and response information
|
|
38
|
+
* @returns A ReadableStream that yields ServerSentEvent objects with parsed JSON data as they are received
|
|
39
|
+
* @throws {ExchangeError} When the server response does not support JsonServerSentEventStream
|
|
40
|
+
* (e.g., wrong content type, no response body, invalid JSON)
|
|
41
|
+
*
|
|
14
42
|
*
|
|
15
|
-
* @
|
|
16
|
-
* @
|
|
17
|
-
* @throws ExchangeError exception when server does not support JsonServerSentEventStream
|
|
43
|
+
* @see {@link JsonServerSentEventStream} for the stream type with JSON data
|
|
44
|
+
* @see {@link EventStreamResultExtractor} for raw string event streams
|
|
18
45
|
*/
|
|
19
46
|
export declare const JsonEventStreamResultExtractor: ResultExtractor<JsonServerSentEventStream<any>>;
|
|
20
47
|
//# sourceMappingURL=eventStreamResultExtractor.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eventStreamResultExtractor.d.ts","sourceRoot":"","sources":["../src/eventStreamResultExtractor.ts"],"names":[],"mappings":"AAaA,OAAO,EAAiB,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AAEjF
|
|
1
|
+
{"version":3,"file":"eventStreamResultExtractor.d.ts","sourceRoot":"","sources":["../src/eventStreamResultExtractor.ts"],"names":[],"mappings":"AAaA,OAAO,EAAiB,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAC/D,OAAO,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAC;AAEjF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,0BAA0B,EAAE,eAAe,CACtD,qBAAqB,CAGtB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,8BAA8B,EAAE,eAAe,CAC1D,yBAAyB,CAAC,GAAG,CAAC,CAG/B,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @packageDocumentation
|
|
3
|
+
* @module @ahoo-wang/fetcher-eventstream
|
|
4
|
+
*
|
|
5
|
+
* # EventStream Package
|
|
6
|
+
*
|
|
7
|
+
* A comprehensive TypeScript library for handling Server-Sent Events (SSE) and stream processing.
|
|
8
|
+
* This package provides utilities for converting, transforming, and consuming event streams with
|
|
9
|
+
* full TypeScript support and async iteration capabilities.
|
|
10
|
+
*
|
|
11
|
+
* ## Key Features
|
|
12
|
+
*
|
|
13
|
+
* - **Server-Sent Event Processing**: Parse and transform SSE streams into typed objects
|
|
14
|
+
* - **JSON Event Streams**: Convert raw SSE to typed JSON event streams with optional termination detection
|
|
15
|
+
* - **Stream Utilities**: Async iteration support for ReadableStreams
|
|
16
|
+
* - **HTTP Response Handling**: Specialized extractors for event stream responses
|
|
17
|
+
* - **Type Safety**: Full TypeScript support with generic types and strict typing
|
|
18
|
+
*
|
|
19
|
+
* ## Quick Start
|
|
20
|
+
*
|
|
21
|
+
* ```typescript
|
|
22
|
+
* import {
|
|
23
|
+
* toJsonServerSentEventStream,
|
|
24
|
+
* type TerminateDetector
|
|
25
|
+
* } from '@ahoo-wang/fetcher-eventstream';
|
|
26
|
+
*
|
|
27
|
+
* // Convert a Server-Sent Event stream to typed JSON events
|
|
28
|
+
* const terminateOnDone: TerminateDetector = (event) => event.data === '[DONE]';
|
|
29
|
+
* const jsonStream = toJsonServerSentEventStream<MyData>(sseStream, terminateOnDone);
|
|
30
|
+
*
|
|
31
|
+
* // Consume the stream
|
|
32
|
+
* for await (const event of jsonStream) {
|
|
33
|
+
* console.log('Received:', event.data);
|
|
34
|
+
* }
|
|
35
|
+
* ```
|
|
36
|
+
*
|
|
37
|
+
* ## Main Components
|
|
38
|
+
*
|
|
39
|
+
* - `toJsonServerSentEventStream()` - Convert SSE streams to typed JSON streams
|
|
40
|
+
* - `JsonServerSentEventTransformStream` - Transform stream class with termination support
|
|
41
|
+
* - `ServerSentEventStream` - Raw server-sent event stream type
|
|
42
|
+
* - `ReadableStreamAsyncIterable` - Async iteration utilities for streams
|
|
43
|
+
* - `EventStreamResultExtractor` - HTTP response extractor for event streams
|
|
44
|
+
*
|
|
45
|
+
* @see {@link toJsonServerSentEventStream} for the main conversion function
|
|
46
|
+
* @see {@link JsonServerSentEventTransformStream} for stream transformation
|
|
47
|
+
* @see {@link TerminateDetector} for termination detection
|
|
48
|
+
*/
|
|
1
49
|
export * from './eventStreamConverter';
|
|
2
50
|
export * from './jsonServerSentEventTransformStream';
|
|
3
51
|
export * from './eventStreamResultExtractor';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,wBAAwB,CAAC;AACvC,cAAc,sCAAsC,CAAC;AACrD,cAAc,8BAA8B,CAAC;AAC7C,cAAc,aAAa,CAAC;AAC5B,cAAc,kCAAkC,CAAC;AACjD,cAAc,2BAA2B,CAAC;AAC1C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,mBAAmB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AAEH,cAAc,wBAAwB,CAAC;AACvC,cAAc,sCAAsC,CAAC;AACrD,cAAc,8BAA8B,CAAC;AAC7C,cAAc,aAAa,CAAC;AAC5B,cAAc,kCAAkC,CAAC;AACjD,cAAc,2BAA2B,CAAC;AAC1C,cAAc,+BAA+B,CAAC;AAC9C,cAAc,mBAAmB,CAAC"}
|