0
# Web Streams Polyfill
1
2
Web Streams Polyfill provides a comprehensive Web Streams polyfill and ponyfill implementation based on the WHATWG specification. It offers multiple variants including modern ES2015+ and legacy ES5+ versions, both as polyfills that replace global stream implementations and as ponyfills that provide stream implementations without modifying globals.
3
4
## Package Information
5
6
- **Package Name**: web-streams-polyfill
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install web-streams-polyfill`
10
11
## Core Imports
12
13
**Ponyfill (recommended):**
14
15
```typescript
16
import {
17
ReadableStream,
18
WritableStream,
19
TransformStream,
20
CountQueuingStrategy,
21
ByteLengthQueuingStrategy
22
} from "web-streams-polyfill";
23
```
24
25
**ES5 Ponyfill:**
26
27
```typescript
28
import {
29
ReadableStream,
30
WritableStream,
31
TransformStream
32
} from "web-streams-polyfill/es5";
33
```
34
35
**Polyfill (modifies globals):**
36
37
```javascript
38
import "web-streams-polyfill/polyfill";
39
// Now ReadableStream, WritableStream, TransformStream are available globally
40
```
41
42
**CommonJS:**
43
44
```javascript
45
const {
46
ReadableStream,
47
WritableStream,
48
TransformStream
49
} = require("web-streams-polyfill");
50
```
51
52
## Basic Usage
53
54
```typescript
55
import {
56
ReadableStream,
57
WritableStream,
58
TransformStream,
59
CountQueuingStrategy
60
} from "web-streams-polyfill";
61
62
// Create a simple readable stream
63
const readable = new ReadableStream({
64
start(controller) {
65
controller.enqueue("Hello");
66
controller.enqueue("World");
67
controller.close();
68
}
69
});
70
71
// Create a transform stream that uppercases text
72
const upperCaseTransform = new TransformStream({
73
transform(chunk, controller) {
74
controller.enqueue(chunk.toString().toUpperCase());
75
}
76
});
77
78
// Create a writable stream that logs output
79
const writable = new WritableStream({
80
write(chunk) {
81
console.log("Output:", chunk);
82
}
83
});
84
85
// Pipe data through the transform to the writable
86
await readable
87
.pipeThrough(upperCaseTransform)
88
.pipeTo(writable);
89
// Output: HELLO
90
// Output: WORLD
91
```
92
93
## Architecture
94
95
Web Streams Polyfill is built around several key components that follow the WHATWG Streams Standard:
96
97
- **Stream Classes**: Core `ReadableStream`, `WritableStream`, and `TransformStream` implementations
98
- **Reader/Writer Classes**: Specialized classes for interacting with streams (`ReadableStreamDefaultReader`, `WritableStreamDefaultWriter`, etc.)
99
- **Controller Classes**: Internal controllers that manage stream state and operations
100
- **Queuing Strategies**: Backpressure management through `CountQueuingStrategy` and `ByteLengthQueuingStrategy`
101
- **Type System**: Complete TypeScript definitions with generic type preservation
102
- **Multi-variant Support**: Four different builds targeting various JavaScript environments and use cases
103
104
## Capabilities
105
106
### Readable Streams
107
108
Core readable stream functionality for creating data sources that can be read from, with support for both default and byte streams, async iteration, and BYOB (Bring Your Own Buffer) reading.
109
110
```typescript { .api }
111
class ReadableStream<R = any> {
112
constructor(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>);
113
constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });
114
115
readonly locked: boolean;
116
117
cancel(reason?: any): Promise<void>;
118
getReader(): ReadableStreamDefaultReader<R>;
119
getReader(options: { mode: 'byob' }): ReadableStreamBYOBReader;
120
pipeThrough<RS extends ReadableStream>(transform: ReadableWritablePair<R, RS>, options?: StreamPipeOptions): RS;
121
pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
122
tee(): [ReadableStream<R>, ReadableStream<R>];
123
values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
124
[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
125
126
static from<R>(asyncIterable: Iterable<R> | AsyncIterable<R> | ReadableStreamLike<R>): ReadableStream<R>;
127
}
128
129
interface UnderlyingSource<R = any> {
130
start?: (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
131
pull?: (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
132
cancel?: (reason: any) => void | PromiseLike<void>;
133
type?: undefined;
134
}
135
136
interface UnderlyingByteSource {
137
start?: (controller: ReadableByteStreamController) => void | PromiseLike<void>;
138
pull?: (controller: ReadableByteStreamController) => void | PromiseLike<void>;
139
cancel?: (reason: any) => void | PromiseLike<void>;
140
type: 'bytes';
141
autoAllocateChunkSize?: number;
142
}
143
```
144
145
[Readable Streams](./readable-streams.md)
146
147
### Writable Streams
148
149
Writable stream functionality for creating data destinations that can be written to, with backpressure support and error handling.
150
151
```typescript { .api }
152
class WritableStream<W = any> {
153
constructor(underlyingSink?: UnderlyingSink<W>, strategy?: QueuingStrategy<W>);
154
155
readonly locked: boolean;
156
157
abort(reason?: any): Promise<void>;
158
close(): Promise<void>;
159
getWriter(): WritableStreamDefaultWriter<W>;
160
}
161
162
interface UnderlyingSink<W = any> {
163
start?: (controller: WritableStreamDefaultController<W>) => void | PromiseLike<void>;
164
write?: (chunk: W, controller: WritableStreamDefaultController<W>) => void | PromiseLike<void>;
165
close?: () => void | PromiseLike<void>;
166
abort?: (reason: any) => void | PromiseLike<void>;
167
type?: undefined;
168
}
169
```
170
171
[Writable Streams](./writable-streams.md)
172
173
### Transform Streams
174
175
Transform stream functionality that connects a writable side to a readable side, allowing data to be transformed as it flows through.
176
177
```typescript { .api }
178
class TransformStream<I = any, O = any> {
179
constructor(
180
transformer?: Transformer<I, O>,
181
writableStrategy?: QueuingStrategy<I>,
182
readableStrategy?: QueuingStrategy<O>
183
);
184
185
readonly readable: ReadableStream<O>;
186
readonly writable: WritableStream<I>;
187
}
188
189
interface Transformer<I = any, O = any> {
190
start?: (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
191
transform?: (chunk: I, controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
192
flush?: (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
193
cancel?: (reason: any) => void | PromiseLike<void>;
194
readableType?: undefined;
195
writableType?: undefined;
196
}
197
```
198
199
[Transform Streams](./transform-streams.md)
200
201
### Queuing Strategies
202
203
Backpressure management through queuing strategies that control how data is buffered within streams.
204
205
```typescript { .api }
206
class CountQueuingStrategy {
207
constructor(options: { highWaterMark: number });
208
readonly highWaterMark: number;
209
readonly size: (chunk: any) => 1;
210
}
211
212
class ByteLengthQueuingStrategy {
213
constructor(options: { highWaterMark: number });
214
readonly highWaterMark: number;
215
readonly size: (chunk: ArrayBufferView) => number;
216
}
217
218
interface QueuingStrategy<T = any> {
219
highWaterMark?: number;
220
size?: (chunk: T) => number;
221
}
222
223
interface QueuingStrategyInit {
224
highWaterMark: number;
225
}
226
```
227
228
[Queuing Strategies](./queuing-strategies.md)
229
230
## Common Types
231
232
```typescript { .api }
233
interface ReadableWritablePair<R, W> {
234
readable: ReadableStream<R>;
235
writable: WritableStream<W>;
236
}
237
238
interface StreamPipeOptions {
239
preventAbort?: boolean;
240
preventCancel?: boolean;
241
preventClose?: boolean;
242
signal?: AbortSignal;
243
}
244
245
interface ReadableStreamIteratorOptions {
246
preventCancel?: boolean;
247
}
248
249
type ReadableStreamDefaultReadResult<T> =
250
| { done: false; value: T }
251
| { done: true; value: undefined };
252
253
type ReadableStreamBYOBReadResult<T extends ArrayBufferView> =
254
| { done: false; value: T }
255
| { done: true; value: T | undefined };
256
257
interface AbortSignal {
258
readonly aborted: boolean;
259
readonly reason?: any;
260
addEventListener(type: 'abort', listener: () => void): void;
261
removeEventListener(type: 'abort', listener: () => void): void;
262
}
263
```