web-utility-streams 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +470 -2
- package/lib/ConcatStream.d.mts +22 -0
- package/lib/ConcatStream.mjs +67 -0
- package/lib/DebugStream.d.mts +3 -0
- package/lib/DebugStream.mjs +12 -0
- package/lib/DeferredStream.d.mts +16 -0
- package/lib/DeferredStream.mjs +51 -0
- package/lib/EmptyStream.d.mts +3 -0
- package/lib/EmptyStream.mjs +9 -0
- package/lib/EventSourceDecoderStream.d.mts +39 -0
- package/lib/EventSourceDecoderStream.mjs +106 -0
- package/lib/EventSourceEncoderStream.d.mts +34 -0
- package/lib/EventSourceEncoderStream.mjs +57 -0
- package/lib/FilterMapStream.d.mts +8 -0
- package/lib/FilterMapStream.mjs +19 -0
- package/lib/FilterStream.d.mts +4 -0
- package/lib/FilterStream.mjs +9 -0
- package/lib/JsonDecoderStream.d.mts +55 -0
- package/lib/JsonDecoderStream.mjs +120 -0
- package/lib/JsonEncoderStream.d.mts +51 -0
- package/lib/JsonEncoderStream.mjs +96 -0
- package/lib/JsonTokenDecoderStream.d.mts +43 -0
- package/lib/JsonTokenDecoderStream.mjs +62 -0
- package/lib/JsonTokenizer-BFV5P0dO.mjs +298 -0
- package/lib/LazyStream.d.mts +18 -0
- package/lib/LazyStream.mjs +53 -0
- package/lib/LineEndings-CET4b2lJ.d.mts +5 -0
- package/lib/LineSplitter-CPGPZH7w.mjs +64 -0
- package/lib/MapStream.d.mts +7 -0
- package/lib/MapStream.mjs +18 -0
- package/lib/NewlineDelimitedJsonDecoderStream.d.mts +18 -0
- package/lib/NewlineDelimitedJsonDecoderStream.mjs +48 -0
- package/lib/NewlineDelimitedJsonEncoderStream.d.mts +15 -0
- package/lib/NewlineDelimitedJsonEncoderStream.mjs +16 -0
- package/lib/SplitLinesStream.d.mts +8 -0
- package/lib/SplitLinesStream.mjs +24 -0
- package/lib/TransformPipelineStream.d.mts +7 -0
- package/lib/TransformPipelineStream.mjs +17 -0
- package/lib/UnionStream.d.mts +21 -0
- package/lib/UnionStream.mjs +79 -0
- package/lib/consumers.d.mts +25 -0
- package/lib/consumers.mjs +82 -0
- package/lib/isPromiseLike-SjGgF7zP.mjs +9 -0
- package/lib/readableStreamToGenerator.d.mts +8 -0
- package/lib/readableStreamToGenerator.mjs +64 -0
- package/package.json +127 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Forbes Lindesay
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,471 @@
|
|
|
1
|
-
#
|
|
1
|
+
# web-utility-streams
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Various utility streams that are very useful for working with web streams.
|
|
4
|
+
|
|
5
|
+
## Contents
|
|
6
|
+
|
|
7
|
+
**Transform streams**
|
|
8
|
+
|
|
9
|
+
- [`DebugStream`](#debugstream) - Call a function with each chunk as it passes through.
|
|
10
|
+
- [`EventSourceDecoderStream`](#eventsourcedecoderstream) - Decode `text/event-stream` (Server-Sent Events) text into events.
|
|
11
|
+
- [`EventSourceEncoderStream`](#eventsourceencoderstream) - Encode events as `text/event-stream` (Server-Sent Events) text.
|
|
12
|
+
- [`FilterMapStream`](#filtermapstream) - Map each chunk, dropping any that map to `undefined`.
|
|
13
|
+
- [`FilterStream`](#filterstream) - Only keep the chunks that match a predicate.
|
|
14
|
+
- [`JsonDecoderStream`](#jsondecoderstream) - Emit the elements of a JSON array or object as they are parsed.
|
|
15
|
+
- [`JsonEncoderStream`](#jsonencoderstream) - Encode a stream of values as a JSON array or object.
|
|
16
|
+
- [`JsonTokenDecoderStream`](#jsontokendecoderstream) - Split JSON text into tokens.
|
|
17
|
+
- [`MapStream`](#mapstream) - Transform each chunk with a sync or async function.
|
|
18
|
+
- [`NewlineDelimitedJsonDecoderStream`](#newlinedelimitedjsondecoderstream) - Parse each line of NDJSON text into a value.
|
|
19
|
+
- [`NewlineDelimitedJsonEncoderStream`](#newlinedelimitedjsonencoderstream) - Encode each value as a line of NDJSON.
|
|
20
|
+
- [`SplitLinesStream`](#splitlinesstream) - Split text into lines.
|
|
21
|
+
- [`TransformPipelineStream`](#transformpipelinestream) - Combine several transform streams into one.
|
|
22
|
+
|
|
23
|
+
**Readable streams**
|
|
24
|
+
|
|
25
|
+
- [`ConcatStream`](#concatstream) - Join streams one after another.
|
|
26
|
+
- [`DeferredStream`](#deferredstream) - Return a stream now whose contents come from a promise.
|
|
27
|
+
- [`EmptyStream`](#emptystream) - A stream that closes immediately.
|
|
28
|
+
- [`LazyStream`](#lazystream) - Create the underlying stream when it is first read.
|
|
29
|
+
- [`UnionStream`](#unionstream) - Merge streams, emitting chunks as they arrive.
|
|
30
|
+
|
|
31
|
+
**Utilities**
|
|
32
|
+
|
|
33
|
+
- [`consumers`](#consumers) - Read a whole stream as text, JSON or bytes.
|
|
34
|
+
- [`readableStreamToGenerator`](#readablestreamtogenerator) - Convert a stream into an async generator that cancels promptly.
|
|
35
|
+
|
|
36
|
+
## Installation
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
npm install web-utility-streams
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Each utility is a separate module, imported by name, e.g. `web-utility-streams/MapStream`.
|
|
43
|
+
|
|
44
|
+
All of the transform streams are safe to use in a pipeline: if any part of the pipeline errors or is cancelled, the error is propagated, and can be handled with a single `try`/`catch` around the call to `pipeTo`, without causing unhandled promise rejections:
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
try {
|
|
48
|
+
await source.pipeThrough(new MapStream(fn)).pipeTo(destination);
|
|
49
|
+
} catch (ex) {
|
|
50
|
+
// Handle errors from the source, the transform, or the destination
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Transform streams
|
|
55
|
+
|
|
56
|
+
### DebugStream
|
|
57
|
+
|
|
58
|
+
Pass every chunk through unchanged, calling a function with each one as it goes past. By default, chunks are logged with `console.log`. This is useful for debugging a pipeline. If the function throws, the stream is errored.
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
import DebugStream from "web-utility-streams/DebugStream";
|
|
62
|
+
|
|
63
|
+
const events = response
|
|
64
|
+
.body!.pipeThrough(new TextDecoderStream())
|
|
65
|
+
.pipeThrough(new DebugStream((text) => console.debug("Received:", text)))
|
|
66
|
+
.pipeThrough(new EventSourceDecoderStream())
|
|
67
|
+
.pipeThrough(new DebugStream());
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### EventSourceDecoderStream
|
|
71
|
+
|
|
72
|
+
Decode a stream of text in the `text/event-stream` format into `EventSourceEvent` objects (`{type, data, id, retryMilliseconds}`), following the parsing rules in the HTML spec. The text can be split into chunks at any point. The `id` and `retryMilliseconds` properties of each event are the values of any `id` and `retry` fields received since the previous event, or `null` if there were none. An incomplete event at the end of the stream is discarded.
|
|
73
|
+
|
|
74
|
+
To be notified of every `id` and `retry` field as soon as it is received, even if no event follows it, pass `onId` and/or `onRetry` options. This is useful for implementing reconnection, which needs the last event ID and the latest reconnection time. If either callback throws, the stream is errored.
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
let lastEventId = "";
|
|
78
|
+
let reconnectDelay = 3000;
|
|
79
|
+
|
|
80
|
+
const events = response.body!.pipeThrough(new TextDecoderStream()).pipeThrough(
|
|
81
|
+
new EventSourceDecoderStream({
|
|
82
|
+
onId: (id) => (lastEventId = id),
|
|
83
|
+
onRetry: (retryMilliseconds) => (reconnectDelay = retryMilliseconds),
|
|
84
|
+
}),
|
|
85
|
+
);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import EventSourceDecoderStream from "web-utility-streams/EventSourceDecoderStream";
|
|
90
|
+
|
|
91
|
+
const response = await fetch("https://example.com/events");
|
|
92
|
+
const events = response
|
|
93
|
+
.body!.pipeThrough(new TextDecoderStream())
|
|
94
|
+
.pipeThrough(new EventSourceDecoderStream());
|
|
95
|
+
|
|
96
|
+
for await (const event of events) {
|
|
97
|
+
console.log(event.type, event.data);
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
The `EventSourceEvent` type for the decoded events is also exported from this module:
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
import type { EventSourceEvent } from "web-utility-streams/EventSourceDecoderStream";
|
|
105
|
+
|
|
106
|
+
function handleEvent(event: EventSourceEvent) {
|
|
107
|
+
if (event.type === "update") {
|
|
108
|
+
console.log(JSON.parse(event.data));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### EventSourceEncoderStream
|
|
114
|
+
|
|
115
|
+
Encode events in the [`text/event-stream`](https://html.spec.whatwg.org/multipage/server-sent-events.html) (Server-Sent Events) format. Each event needs a `data` string, and can optionally have a `type` (defaults to `"message"`), an `id` and a `retryMilliseconds` reconnection time (sent as the `retry` field). Multi-line `data` is supported. Lines end with `"\n"` by default, but you can pass `{ lineEnding: "\r\n" }` or `{ lineEnding: "\r" }` to the constructor. Events that can't be encoded (e.g. an `id` that contains a line break) error the stream.
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import EventSourceEncoderStream from "web-utility-streams/EventSourceEncoderStream";
|
|
119
|
+
|
|
120
|
+
return new Response(
|
|
121
|
+
updates
|
|
122
|
+
.pipeThrough(
|
|
123
|
+
new MapStream((update) => ({
|
|
124
|
+
type: "update",
|
|
125
|
+
id: update.id,
|
|
126
|
+
data: JSON.stringify(update),
|
|
127
|
+
})),
|
|
128
|
+
)
|
|
129
|
+
.pipeThrough(new EventSourceEncoderStream())
|
|
130
|
+
.pipeThrough(new TextEncoderStream()),
|
|
131
|
+
{ headers: { "Content-Type": "text/event-stream" } },
|
|
132
|
+
);
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### FilterMapStream
|
|
136
|
+
|
|
137
|
+
Transform each chunk using a sync or async function, dropping any chunks for which the function returns `undefined`. This is useful when you want to filter and map in a single step.
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
import FilterMapStream from "web-utility-streams/FilterMapStream";
|
|
141
|
+
|
|
142
|
+
const activeUserEmails = userIds.pipeThrough(
|
|
143
|
+
new FilterMapStream(async (id: string) => {
|
|
144
|
+
const user = await db.users.get(id);
|
|
145
|
+
return user.active ? user.email : undefined;
|
|
146
|
+
}),
|
|
147
|
+
);
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### FilterStream
|
|
151
|
+
|
|
152
|
+
Only keep chunks for which the filter function returns `true`. Type guards can be used to narrow the type of the output.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
import FilterStream from "web-utility-streams/FilterStream";
|
|
156
|
+
|
|
157
|
+
const strings = values.pipeThrough(
|
|
158
|
+
new FilterStream((v: unknown): v is string => typeof v === "string"),
|
|
159
|
+
);
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### JsonDecoderStream
|
|
163
|
+
|
|
164
|
+
Decode a JSON array or object from a stream of text, emitting each element as soon as it has been parsed, without waiting for the rest of the document. This lets you start processing a large JSON response before it has finished downloading. For an array, each element is emitted. For an object, each property is emitted as a `[key, value]` tuple. By default the root of the document is streamed; if the array or object is nested inside other objects, pass the keys that lead to it as `path`.
|
|
165
|
+
|
|
166
|
+
The whole document is validated, but only the elements being emitted are kept in memory, unless you pass `onExtraData` (see below). If the document isn't valid JSON, the stream errors when the problem is found. For speed, each element (and each object or array being discarded) is parsed in one go once its end is reached, so a problem inside one is found at its end, or after 1MB of it for larger values. If there's no array or object at `path`, the stream errors once the whole document has been parsed. Because elements are emitted as soon as they're parsed, some may be emitted before an error later in the document is found. If a streamed object repeats a key, a tuple is emitted for each occurrence.
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import JsonDecoderStream from "web-utility-streams/JsonDecoderStream";
|
|
170
|
+
|
|
171
|
+
// Response body: {"total": 1000, "results": [{...}, {...}, ...]}
|
|
172
|
+
const response = await fetch("https://example.com/api/search");
|
|
173
|
+
const results = response
|
|
174
|
+
.body!.pipeThrough(new TextDecoderStream())
|
|
175
|
+
.pipeThrough(new JsonDecoderStream({ path: ["results"] }));
|
|
176
|
+
|
|
177
|
+
for await (const result of results) {
|
|
178
|
+
console.log(result);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Response body: {"users": {"alice": {...}, "bob": {...}, ...}}
|
|
182
|
+
const users = (await fetch("https://example.com/api/users"))
|
|
183
|
+
.body!.pipeThrough(new TextDecoderStream())
|
|
184
|
+
.pipeThrough(new JsonDecoderStream({ path: ["users"] }));
|
|
185
|
+
|
|
186
|
+
for await (const [name, user] of users as ReadableStream<[string, unknown]>) {
|
|
187
|
+
console.log(name, user);
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
To also get the rest of the document, pass an `onExtraData` callback. Once the whole document has been parsed, it's called with the document with the value at `path` replaced by `undefined` (the key is still there). This is the same shape as the `extraData` option of `JsonEncoderStream`, so the two round trip. If `path` is empty, it's called with `undefined`. It's called as soon as the end of the document is reached, which may be before you've read all the elements from the stream, and it isn't called if the document turns out to be invalid before then. If it throws, the stream errors. Note that if `onExtraData` is provided, everything outside `path` is kept in memory until the end of the document.
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
// Response body: {"total": 1000, "results": [...], "next": "abc"}
|
|
195
|
+
let pageInfo: unknown;
|
|
196
|
+
const results = response.body!.pipeThrough(new TextDecoderStream()).pipeThrough(
|
|
197
|
+
new JsonDecoderStream({
|
|
198
|
+
path: ["results"],
|
|
199
|
+
onExtraData: (data) => (pageInfo = data),
|
|
200
|
+
}),
|
|
201
|
+
);
|
|
202
|
+
|
|
203
|
+
for await (const result of results) {
|
|
204
|
+
console.log(result);
|
|
205
|
+
}
|
|
206
|
+
console.log(pageInfo); // { total: 1000, results: undefined, next: "abc" }
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
### JsonEncoderStream
|
|
210
|
+
|
|
211
|
+
Encode a stream of values as a single JSON document, with the values as the elements of an array. With `{ mode: "object" }`, the input must be `[key, value]` tuples, which become the properties of an object. This is the opposite of `JsonDecoderStream`, and lets you start sending a large JSON response before all the data is ready.
|
|
212
|
+
|
|
213
|
+
By default the array or object is the root of the document. To nest it inside other objects, pass the keys that lead to it as `path`, and any other properties as `extraData` (which must not have a value at `path`). The other properties are written before the streamed values, so readers get them straight away. Values are encoded the same way `JSON.stringify` encodes them inside an array or object: `undefined`, functions and symbols become `null` in an array, and those properties are left out of an object. Values `JSON.stringify` can't encode, such as `BigInt` values or circular structures, error the stream.
|
|
214
|
+
|
|
215
|
+
The start of the document is output immediately, each value is output as its own chunk, and the end of the document is output when the input closes.
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
import JsonEncoderStream from "web-utility-streams/JsonEncoderStream";
|
|
219
|
+
|
|
220
|
+
// Response body: {"total":1000,"results":[{...},{...},...]}
|
|
221
|
+
return new Response(
|
|
222
|
+
results
|
|
223
|
+
.pipeThrough(
|
|
224
|
+
new JsonEncoderStream({ path: ["results"], extraData: { total: 1000 } }),
|
|
225
|
+
)
|
|
226
|
+
.pipeThrough(new TextEncoderStream()),
|
|
227
|
+
{ headers: { "Content-Type": "application/json" } },
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
// Response body: {"alice":{...},"bob":{...},...}
|
|
231
|
+
const usersJson = users
|
|
232
|
+
.pipeThrough(new MapStream((user: User) => [user.name, user]))
|
|
233
|
+
.pipeThrough(new JsonEncoderStream({ mode: "object" }));
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
### JsonTokenDecoderStream
|
|
237
|
+
|
|
238
|
+
Split a stream of JSON text into tokens. There are three types of token: `PUNCTUATION` tokens, whose `value` is one of `{`, `}`, `[`, `]`, `:` or `,`; `KEY` tokens, for object keys, whose `value` is the decoded key; and `LITERAL` tokens, whose `value` is the decoded string, number, boolean or `null`. A string is a `KEY` if it is directly inside an object, immediately after the `{` or a `,`. Each token also has the `position` of its first character in the text. The text can be split into chunks at any point, and whitespace is skipped. The text must be a single JSON value (usually an object or array). Each token is checked to be valid, and to be in a valid place in the document (e.g. brackets match, and every key is followed by a `:`), so you can use this to build your own streaming JSON parser without checking the structure yourself. A problem (e.g. a bad escape sequence in a string, or a missing comma) errors the stream with a `SyntaxError` as soon as it's found, after emitting the tokens before it, and so does the input ending before the value is complete. A number, boolean or `null` is only emitted once the next character arrives (or the input ends), as it could continue in the next chunk.
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
import JsonTokenDecoderStream from "web-utility-streams/JsonTokenDecoderStream";
|
|
242
|
+
|
|
243
|
+
const tokens = readableStream.pipeThrough(new JsonTokenDecoderStream());
|
|
244
|
+
// For the text `{"a": [1, true]}`:
|
|
245
|
+
// { type: "PUNCTUATION", value: "{", position: 0 }
|
|
246
|
+
// { type: "KEY", value: "a", position: 1 }
|
|
247
|
+
// { type: "PUNCTUATION", value: ":", position: 4 }
|
|
248
|
+
// { type: "PUNCTUATION", value: "[", position: 6 }
|
|
249
|
+
// { type: "LITERAL", value: 1, position: 7 }
|
|
250
|
+
// { type: "PUNCTUATION", value: ",", position: 8 }
|
|
251
|
+
// { type: "LITERAL", value: true, position: 10 }
|
|
252
|
+
// { type: "PUNCTUATION", value: "]", position: 14 }
|
|
253
|
+
// { type: "PUNCTUATION", value: "}", position: 15 }
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
The `JsonToken` type is also exported from this module.
|
|
257
|
+
|
|
258
|
+
### MapStream
|
|
259
|
+
|
|
260
|
+
Transform each chunk using a sync or async function. Chunks are processed one at a time, and output in the same order as the input. If the function throws, the stream is errored.
|
|
261
|
+
|
|
262
|
+
```ts
|
|
263
|
+
import MapStream from "web-utility-streams/MapStream";
|
|
264
|
+
|
|
265
|
+
const users = userIds.pipeThrough(
|
|
266
|
+
new MapStream(async (id: string) => await db.users.get(id)),
|
|
267
|
+
);
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
### NewlineDelimitedJsonDecoderStream
|
|
271
|
+
|
|
272
|
+
Decode a stream of text in the newline delimited JSON format. Text can be split across chunks in any way, any line ending is supported, and blank lines are ignored. By default, a line of invalid JSON errors the stream, but you can pass an `onError` option to handle invalid lines yourself, e.g. by skipping them or enqueuing a replacement value.
|
|
273
|
+
|
|
274
|
+
```ts
|
|
275
|
+
import NewlineDelimitedJsonDecoderStream from "web-utility-streams/NewlineDelimitedJsonDecoderStream";
|
|
276
|
+
|
|
277
|
+
const response = await fetch("https://example.com/results.ndjson");
|
|
278
|
+
const results = response.body!.pipeThrough(new TextDecoderStream()).pipeThrough(
|
|
279
|
+
new NewlineDelimitedJsonDecoderStream({
|
|
280
|
+
onError: (invalidLine, error, controller) => {
|
|
281
|
+
console.warn(`Skipping invalid line: ${invalidLine}`);
|
|
282
|
+
},
|
|
283
|
+
}),
|
|
284
|
+
);
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### NewlineDelimitedJsonEncoderStream
|
|
288
|
+
|
|
289
|
+
Encode each chunk as a line of JSON ([NDJSON](https://github.com/ndjson/ndjson-spec)). Lines end with `"\n"` by default, but you can pass `{ lineEnding: "\r\n" }` or `{ lineEnding: "\r" }` to the constructor. Values that can't be represented as JSON (e.g. `undefined`, `BigInt` values or circular structures) error the stream.
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
import NewlineDelimitedJsonEncoderStream from "web-utility-streams/NewlineDelimitedJsonEncoderStream";
|
|
293
|
+
|
|
294
|
+
return new Response(
|
|
295
|
+
results
|
|
296
|
+
.pipeThrough(new NewlineDelimitedJsonEncoderStream())
|
|
297
|
+
.pipeThrough(new TextEncoderStream()),
|
|
298
|
+
{ headers: { "Content-Type": "application/x-ndjson" } },
|
|
299
|
+
);
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
### SplitLinesStream
|
|
303
|
+
|
|
304
|
+
Split a stream of text into lines. Lines may end with `\n`, `\r\n` or `\r`, and the line endings are not included in the output. Blank lines are preserved. A final line without a line ending is emitted when the input ends.
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
import SplitLinesStream from "web-utility-streams/SplitLinesStream";
|
|
308
|
+
|
|
309
|
+
const response = await fetch("https://example.com/log.txt");
|
|
310
|
+
const lines = response
|
|
311
|
+
.body!.pipeThrough(new TextDecoderStream())
|
|
312
|
+
.pipeThrough(new SplitLinesStream());
|
|
313
|
+
|
|
314
|
+
for await (const line of lines) {
|
|
315
|
+
console.log(line);
|
|
316
|
+
}
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
### TransformPipelineStream
|
|
320
|
+
|
|
321
|
+
Combine a series of transform streams into a single transform stream. The function you pass is given an `input` with a `pipeThrough` method, and must return the final readable stream.
|
|
322
|
+
|
|
323
|
+
```ts
|
|
324
|
+
import TransformPipelineStream from "web-utility-streams/TransformPipelineStream";
|
|
325
|
+
import EventSourceDecoderStream, {
|
|
326
|
+
type EventSourceEvent,
|
|
327
|
+
} from "web-utility-streams/EventSourceDecoderStream";
|
|
328
|
+
|
|
329
|
+
class BytesToEventsStream extends TransformPipelineStream<
|
|
330
|
+
Uint8Array,
|
|
331
|
+
EventSourceEvent
|
|
332
|
+
> {
|
|
333
|
+
constructor() {
|
|
334
|
+
super((input) =>
|
|
335
|
+
input
|
|
336
|
+
.pipeThrough(new TextDecoderStream())
|
|
337
|
+
.pipeThrough(new EventSourceDecoderStream()),
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const events = response.body!.pipeThrough(new BytesToEventsStream());
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
## Readable streams
|
|
346
|
+
|
|
347
|
+
### ConcatStream
|
|
348
|
+
|
|
349
|
+
Join multiple readable streams into a single stream, emitting all the chunks from the first stream, then all the chunks from the second stream, and so on. The output closes once all the sources have closed, if any source errors the output errors and the other sources are cancelled, and cancelling the output cancels all the sources. All the sources are locked immediately, but each one is only read once the streams before it have closed.
|
|
350
|
+
|
|
351
|
+
```ts
|
|
352
|
+
import ConcatStream from "web-utility-streams/ConcatStream";
|
|
353
|
+
|
|
354
|
+
const allPages = new ConcatStream([page1Results, page2Results, page3Results]);
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
An optional [queuing strategy](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream#queuingstrategy) can be passed as the second argument, to control how far ahead of the reader the sources are read. By default, one chunk is read ahead. With `{ highWaterMark: 0 }`, the sources are only read when the output is read.
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
const allPages = new ConcatStream([page1Results, page2Results], {
|
|
361
|
+
highWaterMark: 0,
|
|
362
|
+
});
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
### DeferredStream
|
|
366
|
+
|
|
367
|
+
A readable stream that you can return immediately, when the stream with the actual content is only available later, from a `Promise<ReadableStream<T>>`. Once the promise resolves, the chunks of that stream are passed through. If the promise rejects, the stream errors with that error when read. Errors from the resolved stream are forwarded, and cancelling the `DeferredStream` cancels the resolved stream, even if the promise hasn't resolved yet. Nothing is read from the resolved stream until the `DeferredStream` is read.
|
|
368
|
+
|
|
369
|
+
```ts
|
|
370
|
+
import DeferredStream from "web-utility-streams/DeferredStream";
|
|
371
|
+
|
|
372
|
+
function getResults(query: string): ReadableStream<Result> {
|
|
373
|
+
return new DeferredStream(
|
|
374
|
+
fetch(`/api/results?q=${encodeURIComponent(query)}`).then((response) =>
|
|
375
|
+
response
|
|
376
|
+
.body!.pipeThrough(new TextDecoderStream())
|
|
377
|
+
.pipeThrough(new NewlineDelimitedJsonDecoderStream()),
|
|
378
|
+
),
|
|
379
|
+
);
|
|
380
|
+
}
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
### EmptyStream
|
|
384
|
+
|
|
385
|
+
A readable stream that is closed immediately, without emitting any chunks. Its chunk type is `never`, so it can be returned wherever a `ReadableStream<T>` is expected.
|
|
386
|
+
|
|
387
|
+
```ts
|
|
388
|
+
import EmptyStream from "web-utility-streams/EmptyStream";
|
|
389
|
+
|
|
390
|
+
function getEvents(user: User | null): ReadableStream<Event> {
|
|
391
|
+
if (!user) return new EmptyStream();
|
|
392
|
+
return getEventsForUser(user);
|
|
393
|
+
}
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
### LazyStream
|
|
397
|
+
|
|
398
|
+
A readable stream that only creates its underlying stream when it is first read, by calling a function that returns a `ReadableStream` or a `Promise<ReadableStream<T>>`. This is useful when creating the stream is expensive, or has side effects such as making a request, and the stream may never be read. Unlike [`DeferredStream`](#deferredstream), which takes a promise for work that has already started, nothing happens until the stream is read.
|
|
399
|
+
|
|
400
|
+
The function is called at most once. If it throws or its promise rejects, the stream errors with that error. Errors from the underlying stream are forwarded. Cancelling the `LazyStream` before it is read does not call the function, and cancelling it later cancels the underlying stream, even if the promise hasn't resolved yet. Nothing is read from the underlying stream until the `LazyStream` is read.
|
|
401
|
+
|
|
402
|
+
```ts
|
|
403
|
+
import LazyStream from "web-utility-streams/LazyStream";
|
|
404
|
+
|
|
405
|
+
const results = new LazyStream(async () => {
|
|
406
|
+
const response = await fetch("/api/results");
|
|
407
|
+
return response
|
|
408
|
+
.body!.pipeThrough(new TextDecoderStream())
|
|
409
|
+
.pipeThrough(new NewlineDelimitedJsonDecoderStream());
|
|
410
|
+
});
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
### UnionStream
|
|
414
|
+
|
|
415
|
+
Merge multiple readable streams into a single stream, emitting chunks in the order they become available. The output closes once all the sources have closed. If any source errors, the output errors and the other sources are cancelled. Cancelling the output cancels all the sources. Backpressure is respected, so the sources are only read from while the output is being read.
|
|
416
|
+
|
|
417
|
+
```ts
|
|
418
|
+
import UnionStream from "web-utility-streams/UnionStream";
|
|
419
|
+
|
|
420
|
+
const allEvents = new UnionStream([userEvents, systemEvents]);
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
An optional [queuing strategy](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream#queuingstrategy) can be passed as the second argument, to control how far ahead of the reader the sources are read. By default, one chunk is read ahead. With `{ highWaterMark: 0 }`, the sources are only read when the output is read. Because the sources are read in parallel, the output can buffer one more chunk per source than the high water mark allows.
|
|
424
|
+
|
|
425
|
+
```ts
|
|
426
|
+
const allEvents = new UnionStream([userEvents, systemEvents], {
|
|
427
|
+
highWaterMark: 0,
|
|
428
|
+
});
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
## Utilities
|
|
432
|
+
|
|
433
|
+
### consumers
|
|
434
|
+
|
|
435
|
+
`textFromStream`, `jsonFromStream` and `bytesFromStream` functions that read an entire stream and return its contents, matching the `text`, `json` and `bytes` functions in [`node:stream/consumers`](https://nodejs.org/api/webstreams.html#utility-consumers). They accept a `ReadableStream` or any async iterable, with chunks that are strings, `ArrayBuffer`s or typed arrays.
|
|
436
|
+
|
|
437
|
+
- `textFromStream(stream)` decodes the contents as UTF-8 text.
|
|
438
|
+
- `jsonFromStream(stream)` decodes the contents as UTF-8 text and parses it with `JSON.parse`.
|
|
439
|
+
- `bytesFromStream(stream)` joins the contents into a single `Uint8Array`. String chunks are UTF-8 encoded.
|
|
440
|
+
|
|
441
|
+
Each function rejects if the stream errors. If a chunk has an invalid type, the function rejects and cancels the stream.
|
|
442
|
+
|
|
443
|
+
```ts
|
|
444
|
+
import {
|
|
445
|
+
bytesFromStream,
|
|
446
|
+
jsonFromStream,
|
|
447
|
+
textFromStream,
|
|
448
|
+
} from "web-utility-streams/consumers";
|
|
449
|
+
|
|
450
|
+
const config = await jsonFromStream(configStream);
|
|
451
|
+
const html = await textFromStream(
|
|
452
|
+
renderStream.pipeThrough(new MapStream((chunk) => chunk.html)),
|
|
453
|
+
);
|
|
454
|
+
const image = await bytesFromStream(imageStream);
|
|
455
|
+
```
|
|
456
|
+
|
|
457
|
+
### readableStreamToGenerator
|
|
458
|
+
|
|
459
|
+
Convert a `ReadableStream` into an `AsyncGenerator`. Unlike the built-in async iterator on `ReadableStream`, calling `return()` or `throw()` on the generator (e.g. by breaking out of a `for await` loop) immediately cancels the stream, even while waiting for the next chunk. This is important for things like GraphQL subscriptions, to ensure resources are cleaned up promptly when a client disconnects. The generator also supports `await using`.
|
|
460
|
+
|
|
461
|
+
```ts
|
|
462
|
+
import readableStreamToGenerator from "web-utility-streams/readableStreamToGenerator";
|
|
463
|
+
|
|
464
|
+
const subscriptionResolver = {
|
|
465
|
+
subscribe: () => readableStreamToGenerator(getEventStream()),
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
for await (const event of readableStreamToGenerator(stream)) {
|
|
469
|
+
if (event.type === "done") break; // cancels the stream
|
|
470
|
+
}
|
|
471
|
+
```
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type ConcatStreamEvent<T extends readonly ReadableStream[]> = T[number] extends ReadableStream<infer U> ? U : never;
|
|
2
|
+
/**
|
|
3
|
+
* Join multiple source streams into a single output stream, by reading all
|
|
4
|
+
* events from the first stream, then all events from the second stream, and
|
|
5
|
+
* so on.
|
|
6
|
+
*
|
|
7
|
+
* All the source streams are locked immediately, but each one is only read
|
|
8
|
+
* once all the streams before it have closed. Backpressure is handled, so if
|
|
9
|
+
* you pause reading from the output, we will also pause reading from the
|
|
10
|
+
* current source stream.
|
|
11
|
+
*
|
|
12
|
+
* The output closes once the last source stream has closed. If any source
|
|
13
|
+
* stream errors, the output is errored and all other source streams are
|
|
14
|
+
* cancelled. If the output is cancelled, all source streams are cancelled.
|
|
15
|
+
*
|
|
16
|
+
* The optional `queuingStrategy` controls how far ahead of the reader the
|
|
17
|
+
* source streams are read. By default, one chunk is read ahead. With
|
|
18
|
+
* `{ highWaterMark: 0 }`, the sources are only read when the output is read.
|
|
19
|
+
*/
|
|
20
|
+
export default class ConcatStream<const T extends readonly ReadableStream[]> extends ReadableStream<ConcatStreamEvent<T>> {
|
|
21
|
+
constructor(streams: T, queuingStrategy?: QueuingStrategy<ConcatStreamEvent<T>>);
|
|
22
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// src/ConcatStream.ts
|
|
2
|
+
/**
|
|
3
|
+
* Join multiple source streams into a single output stream, by reading all
|
|
4
|
+
* events from the first stream, then all events from the second stream, and
|
|
5
|
+
* so on.
|
|
6
|
+
*
|
|
7
|
+
* All the source streams are locked immediately, but each one is only read
|
|
8
|
+
* once all the streams before it have closed. Backpressure is handled, so if
|
|
9
|
+
* you pause reading from the output, we will also pause reading from the
|
|
10
|
+
* current source stream.
|
|
11
|
+
*
|
|
12
|
+
* The output closes once the last source stream has closed. If any source
|
|
13
|
+
* stream errors, the output is errored and all other source streams are
|
|
14
|
+
* cancelled. If the output is cancelled, all source streams are cancelled.
|
|
15
|
+
*
|
|
16
|
+
* The optional `queuingStrategy` controls how far ahead of the reader the
|
|
17
|
+
* source streams are read. By default, one chunk is read ahead. With
|
|
18
|
+
* `{ highWaterMark: 0 }`, the sources are only read when the output is read.
|
|
19
|
+
*/
|
|
20
|
+
var ConcatStream = class extends ReadableStream {
|
|
21
|
+
constructor(streams, queuingStrategy) {
|
|
22
|
+
const remainingReaders = streams.map((stream) => stream.getReader()).reverse();
|
|
23
|
+
let currentReader = remainingReaders.pop();
|
|
24
|
+
let isFinished = false;
|
|
25
|
+
const cancelRemainingReaders = async (reason) => {
|
|
26
|
+
const results = await Promise.allSettled(remainingReaders.map((reader) => reader.cancel(reason)));
|
|
27
|
+
for (const result of results) if (result.status === "rejected") throw result.reason;
|
|
28
|
+
};
|
|
29
|
+
let controller;
|
|
30
|
+
const onError = (err) => {
|
|
31
|
+
if (isFinished) return;
|
|
32
|
+
isFinished = true;
|
|
33
|
+
controller.error(err);
|
|
34
|
+
cancelRemainingReaders(err).catch(() => {});
|
|
35
|
+
};
|
|
36
|
+
const onResult = (result) => {
|
|
37
|
+
if (isFinished) return;
|
|
38
|
+
if (!result.done) {
|
|
39
|
+
controller.enqueue(result.value);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
currentReader = remainingReaders.pop();
|
|
43
|
+
return readNext();
|
|
44
|
+
};
|
|
45
|
+
const readNext = () => {
|
|
46
|
+
if (!currentReader) {
|
|
47
|
+
isFinished = true;
|
|
48
|
+
controller.close();
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
return currentReader.read().then(onResult, onError);
|
|
52
|
+
};
|
|
53
|
+
super({
|
|
54
|
+
start(c) {
|
|
55
|
+
controller = c;
|
|
56
|
+
},
|
|
57
|
+
pull: readNext,
|
|
58
|
+
async cancel(reason) {
|
|
59
|
+
if (isFinished) return;
|
|
60
|
+
isFinished = true;
|
|
61
|
+
if (currentReader) remainingReaders.push(currentReader);
|
|
62
|
+
await cancelRemainingReaders(reason);
|
|
63
|
+
}
|
|
64
|
+
}, queuingStrategy);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
export { ConcatStream as default };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// src/DebugStream.ts
|
|
2
|
+
var DebugStream = class extends TransformStream {
|
|
3
|
+
constructor(onValue = (value) => {
|
|
4
|
+
console.log(value);
|
|
5
|
+
}) {
|
|
6
|
+
super({ transform(chunk, controller) {
|
|
7
|
+
onValue(chunk);
|
|
8
|
+
controller.enqueue(chunk);
|
|
9
|
+
} });
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
export { DebugStream as default };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `ReadableStream` that is available immediately, but whose contents come
|
|
3
|
+
* from a stream that will only be available later, once the promise resolves.
|
|
4
|
+
*
|
|
5
|
+
* - If the promise rejects (or does not resolve to an unlocked
|
|
6
|
+
* `ReadableStream`), the stream errors with that error when read.
|
|
7
|
+
* - Errors from the underlying stream are forwarded.
|
|
8
|
+
* - Cancelling this stream cancels the underlying stream, waiting for the
|
|
9
|
+
* promise to resolve first if necessary.
|
|
10
|
+
*
|
|
11
|
+
* Nothing is read from the underlying stream until this stream is read, so
|
|
12
|
+
* backpressure is preserved.
|
|
13
|
+
*/
|
|
14
|
+
export default class DeferredStream<T> extends ReadableStream<T> {
|
|
15
|
+
constructor(stream: PromiseLike<ReadableStream<T>>);
|
|
16
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// src/DeferredStream.ts
|
|
2
|
+
/**
|
|
3
|
+
* A `ReadableStream` that is available immediately, but whose contents come
|
|
4
|
+
* from a stream that will only be available later, once the promise resolves.
|
|
5
|
+
*
|
|
6
|
+
* - If the promise rejects (or does not resolve to an unlocked
|
|
7
|
+
* `ReadableStream`), the stream errors with that error when read.
|
|
8
|
+
* - Errors from the underlying stream are forwarded.
|
|
9
|
+
* - Cancelling this stream cancels the underlying stream, waiting for the
|
|
10
|
+
* promise to resolve first if necessary.
|
|
11
|
+
*
|
|
12
|
+
* Nothing is read from the underlying stream until this stream is read, so
|
|
13
|
+
* backpressure is preserved.
|
|
14
|
+
*/
|
|
15
|
+
var DeferredStream = class extends ReadableStream {
|
|
16
|
+
constructor(stream) {
|
|
17
|
+
let isCancelled = false;
|
|
18
|
+
let controller;
|
|
19
|
+
let reader;
|
|
20
|
+
const readerPromise = Promise.resolve(stream).then((stream) => reader = stream.getReader());
|
|
21
|
+
readerPromise.catch(() => {});
|
|
22
|
+
const onResult = (result) => {
|
|
23
|
+
if (isCancelled) return;
|
|
24
|
+
if (result.done) controller.close();
|
|
25
|
+
else controller.enqueue(result.value);
|
|
26
|
+
};
|
|
27
|
+
super({
|
|
28
|
+
start(c) {
|
|
29
|
+
controller = c;
|
|
30
|
+
},
|
|
31
|
+
pull() {
|
|
32
|
+
if (reader) return reader.read().then(onResult);
|
|
33
|
+
return readerPromise.then((reader) => {
|
|
34
|
+
if (isCancelled) return;
|
|
35
|
+
return reader.read().then(onResult);
|
|
36
|
+
});
|
|
37
|
+
},
|
|
38
|
+
async cancel(reason) {
|
|
39
|
+
isCancelled = true;
|
|
40
|
+
let reader;
|
|
41
|
+
try {
|
|
42
|
+
reader = await readerPromise;
|
|
43
|
+
} catch {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
await reader.cancel(reason);
|
|
47
|
+
}
|
|
48
|
+
}, { highWaterMark: 0 });
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
export { DeferredStream as default };
|