web-utility-streams 0.2.0 → 1.0.0-canary-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/README.md +76 -0
- package/lib/TimeoutStream.d.mts +44 -0
- package/lib/TimeoutStream.mjs +94 -0
- package/lib/TransformStreamWithCancel.d.mts +48 -0
- package/lib/TransformStreamWithCancel.mjs +197 -0
- package/package.json +9 -1
package/README.md
CHANGED
|
@@ -20,7 +20,9 @@ Various utility streams that are very useful for working with web streams.
|
|
|
20
20
|
- [`NewlineDelimitedJsonDecoderStream`](#newlinedelimitedjsondecoderstream) - Parse each line of NDJSON text into a value.
|
|
21
21
|
- [`NewlineDelimitedJsonEncoderStream`](#newlinedelimitedjsonencoderstream) - Encode each value as a line of NDJSON.
|
|
22
22
|
- [`SplitLinesStream`](#splitlinesstream) - Split text into lines.
|
|
23
|
+
- [`TimeoutStream`](#timeoutstream) - Error the stream if no chunk arrives for too long.
|
|
23
24
|
- [`TransformPipelineStream`](#transformpipelinestream) - Combine several transform streams into one.
|
|
25
|
+
- [`TransformStreamWithCancel`](#transformstreamwithcancel) - A `TransformStream` that calls the transformer's `cancel` method, in any runtime.
|
|
24
26
|
|
|
25
27
|
**Readable streams**
|
|
26
28
|
|
|
@@ -352,6 +354,55 @@ for await (const line of lines) {
|
|
|
352
354
|
}
|
|
353
355
|
```
|
|
354
356
|
|
|
357
|
+
### TimeoutStream
|
|
358
|
+
|
|
359
|
+
Pass chunks through unchanged, but error the stream if no chunk is written for `timeoutMs` milliseconds. This is useful for detecting a connection that has stalled, such as a streaming API response that stops sending data without closing. When the timeout is reached, the stream is errored with a `TimeoutStreamError` (which has `code: "TIMEOUT_STREAM_TIMEOUT"`), so in a pipeline the source is cancelled and the error is thrown from `pipeTo`.
|
|
360
|
+
|
|
361
|
+
```ts
|
|
362
|
+
import TimeoutStream, {
|
|
363
|
+
TimeoutStreamError,
|
|
364
|
+
} from "web-utility-streams/TimeoutStream";
|
|
365
|
+
|
|
366
|
+
try {
|
|
367
|
+
await response
|
|
368
|
+
.body!.pipeThrough(new TimeoutStream({ timeoutMs: 30_000 }))
|
|
369
|
+
.pipeTo(destination);
|
|
370
|
+
} catch (ex) {
|
|
371
|
+
if (ex instanceof TimeoutStreamError) {
|
|
372
|
+
// No data was received for 30 seconds
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
The timeout starts when the stream is created, and is stopped when the input closes, or the stream is cancelled or errored.
|
|
378
|
+
|
|
379
|
+
Chunks are only written to a `TimeoutStream` when its output has room for them (it reads one chunk ahead of the output), so if the output is read slowly, for example because the destination of a pipeline is slow, the input is held back by backpressure, and that can cause a timeout too. Choose a timeout that allows for the slowest reader you expect, or put the `TimeoutStream` before any slow steps in the pipeline.
|
|
380
|
+
|
|
381
|
+
`timeoutMs` can also be a function, which is called to choose the first timeout (with `remainingMs` of `0` and no chunk), and then each time a chunk is written, with the time that was left of the previous timeout and the chunk. For example, when streaming audio to a player that reads it in real time, each chunk gives the input longer before the next one is needed:
|
|
382
|
+
|
|
383
|
+
```ts
|
|
384
|
+
await audioStream
|
|
385
|
+
.pipeThrough(
|
|
386
|
+
new TimeoutStream<AudioChunk>({
|
|
387
|
+
// Allow 5 seconds for the first chunk. After that, add the length of
|
|
388
|
+
// each chunk to the time that was left, as the player won't ask for
|
|
389
|
+
// more until it has played it.
|
|
390
|
+
timeoutMs: (remainingMs, chunk) =>
|
|
391
|
+
chunk === undefined ? 5_000 : remainingMs + getAudioDuration(chunk),
|
|
392
|
+
}),
|
|
393
|
+
)
|
|
394
|
+
.pipeTo(audioPlayer);
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
Pass `onTimeout` to choose what happens when the timeout is reached. It's called with the stream's `TransformStreamDefaultController`, so it can error the stream with your own error, end it cleanly with `controller.terminate()`, or enqueue a chunk. If it doesn't error or terminate the stream, the timeout starts again when the next chunk is written. If it throws, the stream is errored.
|
|
398
|
+
|
|
399
|
+
```ts
|
|
400
|
+
const stream = new TimeoutStream({
|
|
401
|
+
timeoutMs: 10_000,
|
|
402
|
+
onTimeout: (controller) => controller.error(new MyTimeoutError()),
|
|
403
|
+
});
|
|
404
|
+
```
|
|
405
|
+
|
|
355
406
|
### TransformPipelineStream
|
|
356
407
|
|
|
357
408
|
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.
|
|
@@ -378,6 +429,31 @@ class BytesToEventsStream extends TransformPipelineStream<
|
|
|
378
429
|
const events = response.body!.pipeThrough(new BytesToEventsStream());
|
|
379
430
|
```
|
|
380
431
|
|
|
432
|
+
### TransformStreamWithCancel
|
|
433
|
+
|
|
434
|
+
`TransformStream`, with support for the transformer's `cancel` method in every runtime. `cancel` is called with the reason when the readable side is cancelled or the writable side is aborted (e.g. because another part of a pipeline errored), which makes it the place to clean up resources such as timers or connections. It was added to the Streams standard in 2023, but isn't supported everywhere yet.
|
|
435
|
+
|
|
436
|
+
In runtimes that support `cancel` (such as Node.js), `TransformStreamWithCancel` is just `TransformStream`. Elsewhere it's `TransformStreamWithCancelPolyfill`, which implements the standard's `TransformStream` with a `ReadableStream` and a `WritableStream`. It supports everything `TransformStream` does, including queuing strategies and backpressure, but `instanceof TransformStream` is `false`.
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
import TransformStreamWithCancel from "web-utility-streams/TransformStreamWithCancel";
|
|
440
|
+
|
|
441
|
+
const subscription = subscribe();
|
|
442
|
+
const stream = new TransformStreamWithCancel<Message, Message>({
|
|
443
|
+
transform(message, controller) {
|
|
444
|
+
if (subscription.isWanted(message)) controller.enqueue(message);
|
|
445
|
+
},
|
|
446
|
+
flush() {
|
|
447
|
+
subscription.unsubscribe();
|
|
448
|
+
},
|
|
449
|
+
cancel(reason) {
|
|
450
|
+
subscription.unsubscribe();
|
|
451
|
+
},
|
|
452
|
+
});
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
You can extend it like `TransformStream`, e.g. `class MyStream extends TransformStreamWithCancel<In, Out>`. The module also exports `supportsTransformerCancel`, which is `true` if the native `TransformStream` supports `cancel`, the `TransformStreamWithCancelPolyfill` class (if you want to use it regardless), and the `TransformerWithCancel` type (TypeScript's own `Transformer` type doesn't include `cancel` yet).
|
|
456
|
+
|
|
381
457
|
## Readable streams
|
|
382
458
|
|
|
383
459
|
### ConcatStream
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import TransformStreamWithCancel from "./TransformStreamWithCancel.mjs";
|
|
2
|
+
/**
|
|
3
|
+
* Choose the timeout, in milliseconds, each time a chunk is written.
|
|
4
|
+
*
|
|
5
|
+
* @param remainingMs - How long was left of the previous timeout, or 0 when
|
|
6
|
+
* choosing the first timeout, which starts when the stream is created.
|
|
7
|
+
* @param chunk - The chunk that was just written, or `undefined` when choosing
|
|
8
|
+
* the first timeout.
|
|
9
|
+
*/
|
|
10
|
+
export type TimeoutGetter<TChunk> = (remainingMs: number, chunk?: TChunk) => number;
|
|
11
|
+
export interface TimeoutStreamOptions<TChunk> {
|
|
12
|
+
/**
|
|
13
|
+
* How long to wait for the next chunk, in milliseconds, or a function that
|
|
14
|
+
* chooses it each time a chunk is written.
|
|
15
|
+
*/
|
|
16
|
+
timeoutMs: number | TimeoutGetter<TChunk>;
|
|
17
|
+
/**
|
|
18
|
+
* Called when the timeout is reached. By default, the stream is errored with
|
|
19
|
+
* a `TimeoutStreamError`. You could instead error it with your own error,
|
|
20
|
+
* end it with `controller.terminate()`, or even enqueue a chunk. If the
|
|
21
|
+
* stream isn't errored or terminated, the timeout starts again when the
|
|
22
|
+
* next chunk is written. If this function throws, the stream is errored.
|
|
23
|
+
*/
|
|
24
|
+
onTimeout?: (controller: TransformStreamDefaultController<TChunk>) => void;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The error a `TimeoutStream` is errored with by default
|
|
28
|
+
*/
|
|
29
|
+
export declare class TimeoutStreamError extends Error {
|
|
30
|
+
readonly code = "TIMEOUT_STREAM_TIMEOUT";
|
|
31
|
+
constructor(timeoutMs: number);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Pass chunks through unchanged, erroring the stream if no chunk is written
|
|
35
|
+
* for `timeoutMs` milliseconds. The timeout starts when the stream is created,
|
|
36
|
+
* and is stopped when the stream finishes.
|
|
37
|
+
*
|
|
38
|
+
* Chunks are only written when the output has room for them, so if the output
|
|
39
|
+
* is read slowly (e.g. a slow destination in a pipeline), that can cause a
|
|
40
|
+
* timeout too.
|
|
41
|
+
*/
|
|
42
|
+
export default class TimeoutStream<TChunk> extends TransformStreamWithCancel<TChunk, TChunk> {
|
|
43
|
+
constructor({ timeoutMs, onTimeout }: TimeoutStreamOptions<TChunk>);
|
|
44
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import TransformStreamWithCancel from "./TransformStreamWithCancel.mjs";
|
|
2
|
+
// src/TimeoutStream.ts
|
|
3
|
+
/**
|
|
4
|
+
* The error a `TimeoutStream` is errored with by default
|
|
5
|
+
*/
|
|
6
|
+
var TimeoutStreamError = class extends Error {
|
|
7
|
+
code = "TIMEOUT_STREAM_TIMEOUT";
|
|
8
|
+
constructor(timeoutMs) {
|
|
9
|
+
super(`TimeoutStream: no chunk was received for ${Math.round(timeoutMs)}ms.`);
|
|
10
|
+
this.name = "TimeoutStreamError";
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Pass chunks through unchanged, erroring the stream if no chunk is written
|
|
15
|
+
* for `timeoutMs` milliseconds. The timeout starts when the stream is created,
|
|
16
|
+
* and is stopped when the stream finishes.
|
|
17
|
+
*
|
|
18
|
+
* Chunks are only written when the output has room for them, so if the output
|
|
19
|
+
* is read slowly (e.g. a slow destination in a pipeline), that can cause a
|
|
20
|
+
* timeout too.
|
|
21
|
+
*/
|
|
22
|
+
var TimeoutStream = class extends TransformStreamWithCancel {
|
|
23
|
+
constructor({ timeoutMs, onTimeout }) {
|
|
24
|
+
const getTimeout = typeof timeoutMs === "function" ? timeoutMs : void 0;
|
|
25
|
+
const fixedTimeoutMs = getTimeout ? 0 : timeoutMs;
|
|
26
|
+
if (!getTimeout) checkTimeout(fixedTimeoutMs);
|
|
27
|
+
let controller;
|
|
28
|
+
let timer;
|
|
29
|
+
let deadline = 0;
|
|
30
|
+
let timerDue = 0;
|
|
31
|
+
let currentTimeoutMs = 0;
|
|
32
|
+
const startTimer = (now) => {
|
|
33
|
+
timerDue = deadline;
|
|
34
|
+
timer = setTimeout(onTimer, deadline - now);
|
|
35
|
+
};
|
|
36
|
+
const onTimer = () => {
|
|
37
|
+
const now = performance.now();
|
|
38
|
+
if (deadline > now) return startTimer(now);
|
|
39
|
+
timer = void 0;
|
|
40
|
+
try {
|
|
41
|
+
if (onTimeout) onTimeout(controller);
|
|
42
|
+
else controller.error(new TimeoutStreamError(currentTimeoutMs));
|
|
43
|
+
} catch (err) {
|
|
44
|
+
controller.error(err);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const stopTimer = () => {
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
timer = void 0;
|
|
50
|
+
deadline = 1e400;
|
|
51
|
+
};
|
|
52
|
+
super({
|
|
53
|
+
start(c) {
|
|
54
|
+
controller = c;
|
|
55
|
+
const now = performance.now();
|
|
56
|
+
currentTimeoutMs = getTimeout ? checkTimeout(getTimeout(0)) : fixedTimeoutMs;
|
|
57
|
+
deadline = now + currentTimeoutMs;
|
|
58
|
+
startTimer(now);
|
|
59
|
+
},
|
|
60
|
+
transform: getTimeout ? (chunk, controller) => {
|
|
61
|
+
if (deadline !== 1e400) {
|
|
62
|
+
const now = performance.now();
|
|
63
|
+
try {
|
|
64
|
+
currentTimeoutMs = checkTimeout(getTimeout(Math.max(0, deadline - now), chunk));
|
|
65
|
+
} catch (err) {
|
|
66
|
+
stopTimer();
|
|
67
|
+
throw err;
|
|
68
|
+
}
|
|
69
|
+
deadline = now + currentTimeoutMs;
|
|
70
|
+
if (timer === void 0) startTimer(now);
|
|
71
|
+
else if (deadline < timerDue) {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
startTimer(now);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
controller.enqueue(chunk);
|
|
77
|
+
} : (chunk, controller) => {
|
|
78
|
+
if (deadline !== 1e400) {
|
|
79
|
+
const now = performance.now();
|
|
80
|
+
deadline = now + fixedTimeoutMs;
|
|
81
|
+
if (timer === void 0) startTimer(now);
|
|
82
|
+
}
|
|
83
|
+
controller.enqueue(chunk);
|
|
84
|
+
},
|
|
85
|
+
flush: stopTimer,
|
|
86
|
+
cancel: stopTimer
|
|
87
|
+
}, void 0, { highWaterMark: 1 });
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
function checkTimeout(timeoutMs) {
|
|
91
|
+
if (!(timeoutMs >= 0)) throw new RangeError(`TimeoutStream: timeoutMs must be a number >= 0, but got ${timeoutMs}`);
|
|
92
|
+
return timeoutMs;
|
|
93
|
+
}
|
|
94
|
+
export { TimeoutStreamError, TimeoutStream as default };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A `Transformer`, as passed to `new TransformStream()`, including the
|
|
3
|
+
* `cancel` method, which TypeScript's DOM types don't include yet.
|
|
4
|
+
*/
|
|
5
|
+
export interface TransformerWithCancel<I = any, O = any> {
|
|
6
|
+
start?: (controller: TransformStreamDefaultController<O>) => any;
|
|
7
|
+
transform?: (chunk: I, controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
|
|
8
|
+
flush?: (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
|
|
9
|
+
/**
|
|
10
|
+
* Called when the readable side is cancelled, or the writable side is
|
|
11
|
+
* aborted, with the reason.
|
|
12
|
+
*/
|
|
13
|
+
cancel?: (reason: any) => void | PromiseLike<void>;
|
|
14
|
+
readableType?: undefined;
|
|
15
|
+
writableType?: undefined;
|
|
16
|
+
}
|
|
17
|
+
export interface TransformStreamWithCancelConstructor {
|
|
18
|
+
new <I = any, O = any>(transformer?: TransformerWithCancel<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>): TransformStream<I, O>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Whether this runtime's `TransformStream` calls the transformer's `cancel`
|
|
22
|
+
* method. The constructor only reads the transformer properties it knows
|
|
23
|
+
* about, so we can check without creating any streams other than this one.
|
|
24
|
+
*/
|
|
25
|
+
export declare const supportsTransformerCancel: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* A `TransformStream` that calls the transformer's `cancel` method, built
|
|
28
|
+
* from a `ReadableStream` and a `WritableStream`, following the algorithms in
|
|
29
|
+
* the Streams standard. `TransformStreamWithCancel` is this class in runtimes
|
|
30
|
+
* whose `TransformStream` doesn't call `cancel`. Prefer using
|
|
31
|
+
* `TransformStreamWithCancel`, unless you specifically need the polyfill.
|
|
32
|
+
*
|
|
33
|
+
* Unlike a native `TransformStream`, `instanceof TransformStream` is false.
|
|
34
|
+
*/
|
|
35
|
+
export declare class TransformStreamWithCancelPolyfill<I = any, O = any> implements TransformStream<I, O> {
|
|
36
|
+
readonly readable: ReadableStream<O>;
|
|
37
|
+
readonly writable: WritableStream<I>;
|
|
38
|
+
constructor(transformer?: TransformerWithCancel<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* A `TransformStream` that calls the transformer's `cancel` method when the
|
|
42
|
+
* readable side is cancelled or the writable side is aborted, even in
|
|
43
|
+
* runtimes whose `TransformStream` doesn't support `cancel` yet. In runtimes
|
|
44
|
+
* that do, this is just `TransformStream`.
|
|
45
|
+
*/
|
|
46
|
+
declare const TransformStreamWithCancel: TransformStreamWithCancelConstructor;
|
|
47
|
+
type TransformStreamWithCancel<I = any, O = any> = TransformStream<I, O>;
|
|
48
|
+
export { TransformStreamWithCancel as default };
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { t as isPromiseLike } from "./isPromiseLike-SjGgF7zP.mjs";
|
|
2
|
+
// src/TransformStreamWithCancel.ts
|
|
3
|
+
/**
|
|
4
|
+
* Whether this runtime's `TransformStream` calls the transformer's `cancel`
|
|
5
|
+
* method. The constructor only reads the transformer properties it knows
|
|
6
|
+
* about, so we can check without creating any streams other than this one.
|
|
7
|
+
*/
|
|
8
|
+
const supportsTransformerCancel = (() => {
|
|
9
|
+
let supported = false;
|
|
10
|
+
try {
|
|
11
|
+
new TransformStream({ get cancel() {
|
|
12
|
+
supported = true;
|
|
13
|
+
} });
|
|
14
|
+
} catch {}
|
|
15
|
+
return supported;
|
|
16
|
+
})();
|
|
17
|
+
const resolved = Promise.resolve();
|
|
18
|
+
/**
|
|
19
|
+
* A `TransformStream` that calls the transformer's `cancel` method, built
|
|
20
|
+
* from a `ReadableStream` and a `WritableStream`, following the algorithms in
|
|
21
|
+
* the Streams standard. `TransformStreamWithCancel` is this class in runtimes
|
|
22
|
+
* whose `TransformStream` doesn't call `cancel`. Prefer using
|
|
23
|
+
* `TransformStreamWithCancel`, unless you specifically need the polyfill.
|
|
24
|
+
*
|
|
25
|
+
* Unlike a native `TransformStream`, `instanceof TransformStream` is false.
|
|
26
|
+
*/
|
|
27
|
+
var TransformStreamWithCancelPolyfill = class {
|
|
28
|
+
readable;
|
|
29
|
+
writable;
|
|
30
|
+
constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) {
|
|
31
|
+
if (transformer.readableType !== void 0) throw new RangeError("Invalid readableType specified");
|
|
32
|
+
if (transformer.writableType !== void 0) throw new RangeError("Invalid writableType specified");
|
|
33
|
+
const { start, transform, flush, cancel } = transformer;
|
|
34
|
+
let readableController;
|
|
35
|
+
let writableController;
|
|
36
|
+
let readableOpen = true;
|
|
37
|
+
let readableCancelled = false;
|
|
38
|
+
let readableErrored = false;
|
|
39
|
+
let readableError;
|
|
40
|
+
let writableErrored = false;
|
|
41
|
+
let writableError;
|
|
42
|
+
let backpressure = true;
|
|
43
|
+
let releaseWrite;
|
|
44
|
+
const releaseBackpressure = () => {
|
|
45
|
+
backpressure = false;
|
|
46
|
+
if (releaseWrite !== void 0) {
|
|
47
|
+
const release = releaseWrite;
|
|
48
|
+
releaseWrite = void 0;
|
|
49
|
+
release();
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
let finishPromise;
|
|
53
|
+
const errorReadable = (reason) => {
|
|
54
|
+
if (readableErrored || readableCancelled) return;
|
|
55
|
+
readableOpen = false;
|
|
56
|
+
readableController.error(reason);
|
|
57
|
+
if (readableController.desiredSize === null) {
|
|
58
|
+
readableErrored = true;
|
|
59
|
+
readableError = reason;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const errorWritableAndUnblockWrite = (reason) => {
|
|
63
|
+
if (!writableErrored) {
|
|
64
|
+
writableErrored = true;
|
|
65
|
+
writableError = reason;
|
|
66
|
+
writableController.error(reason);
|
|
67
|
+
}
|
|
68
|
+
if (backpressure) releaseBackpressure();
|
|
69
|
+
};
|
|
70
|
+
const errorStream = (reason) => {
|
|
71
|
+
errorReadable(reason);
|
|
72
|
+
errorWritableAndUnblockWrite(reason);
|
|
73
|
+
};
|
|
74
|
+
const controller = {
|
|
75
|
+
get desiredSize() {
|
|
76
|
+
return readableController.desiredSize;
|
|
77
|
+
},
|
|
78
|
+
enqueue(chunk) {
|
|
79
|
+
if (!readableOpen) throw new TypeError("Readable side is not in a state that permits enqueue");
|
|
80
|
+
try {
|
|
81
|
+
readableController.enqueue(chunk);
|
|
82
|
+
} catch (err) {
|
|
83
|
+
errorWritableAndUnblockWrite(err);
|
|
84
|
+
throw err;
|
|
85
|
+
}
|
|
86
|
+
if (!(readableController.desiredSize > 0)) backpressure = true;
|
|
87
|
+
},
|
|
88
|
+
error(reason) {
|
|
89
|
+
errorStream(reason);
|
|
90
|
+
},
|
|
91
|
+
terminate() {
|
|
92
|
+
if (readableOpen) {
|
|
93
|
+
readableOpen = false;
|
|
94
|
+
readableController.close();
|
|
95
|
+
}
|
|
96
|
+
errorWritableAndUnblockWrite(/* @__PURE__ */ new TypeError("TransformStream terminated"));
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
const performTransform = transform ? (chunk) => {
|
|
100
|
+
try {
|
|
101
|
+
const result = transform.call(transformer, chunk, controller);
|
|
102
|
+
if (isPromiseLike(result)) return Promise.resolve(result).then(void 0, (err) => {
|
|
103
|
+
errorStream(err);
|
|
104
|
+
throw err;
|
|
105
|
+
});
|
|
106
|
+
} catch (err) {
|
|
107
|
+
errorStream(err);
|
|
108
|
+
throw err;
|
|
109
|
+
}
|
|
110
|
+
} : (chunk) => {
|
|
111
|
+
controller.enqueue(chunk);
|
|
112
|
+
};
|
|
113
|
+
const call = (fn, arg) => {
|
|
114
|
+
if (fn === void 0) return resolved;
|
|
115
|
+
try {
|
|
116
|
+
return Promise.resolve(fn.call(transformer, arg));
|
|
117
|
+
} catch (err) {
|
|
118
|
+
return Promise.reject(err);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
let resolveStart;
|
|
122
|
+
const startPromise = new Promise((resolve) => resolveStart = resolve);
|
|
123
|
+
this.writable = new WritableStream({
|
|
124
|
+
start(c) {
|
|
125
|
+
writableController = c;
|
|
126
|
+
return startPromise;
|
|
127
|
+
},
|
|
128
|
+
write(chunk) {
|
|
129
|
+
if (!backpressure) return performTransform(chunk);
|
|
130
|
+
return new Promise((resolve) => releaseWrite = resolve).then(() => {
|
|
131
|
+
if (writableErrored) throw writableError;
|
|
132
|
+
const signal = writableController.signal;
|
|
133
|
+
if (signal?.aborted) throw signal.reason;
|
|
134
|
+
return performTransform(chunk);
|
|
135
|
+
});
|
|
136
|
+
},
|
|
137
|
+
close() {
|
|
138
|
+
if (finishPromise) return finishPromise;
|
|
139
|
+
return finishPromise = call(flush, controller).then(() => {
|
|
140
|
+
if (readableErrored) throw readableError;
|
|
141
|
+
if (readableOpen) {
|
|
142
|
+
readableOpen = false;
|
|
143
|
+
readableController.close();
|
|
144
|
+
}
|
|
145
|
+
}, (err) => {
|
|
146
|
+
errorReadable(err);
|
|
147
|
+
throw err;
|
|
148
|
+
});
|
|
149
|
+
},
|
|
150
|
+
abort(reason) {
|
|
151
|
+
if (finishPromise) return finishPromise;
|
|
152
|
+
writableErrored = true;
|
|
153
|
+
writableError = reason;
|
|
154
|
+
return finishPromise = call(cancel, reason).then(() => {
|
|
155
|
+
if (readableErrored) throw readableError;
|
|
156
|
+
errorReadable(reason);
|
|
157
|
+
}, (err) => {
|
|
158
|
+
errorReadable(err);
|
|
159
|
+
throw err;
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
}, writableStrategy);
|
|
163
|
+
this.readable = new ReadableStream({
|
|
164
|
+
start(c) {
|
|
165
|
+
readableController = c;
|
|
166
|
+
return startPromise;
|
|
167
|
+
},
|
|
168
|
+
pull() {
|
|
169
|
+
releaseBackpressure();
|
|
170
|
+
},
|
|
171
|
+
cancel(reason) {
|
|
172
|
+
readableOpen = false;
|
|
173
|
+
readableCancelled = true;
|
|
174
|
+
if (finishPromise) return finishPromise;
|
|
175
|
+
return finishPromise = call(cancel, reason).then(() => {
|
|
176
|
+
if (writableErrored) throw writableError;
|
|
177
|
+
errorWritableAndUnblockWrite(reason);
|
|
178
|
+
}, (err) => {
|
|
179
|
+
errorWritableAndUnblockWrite(err);
|
|
180
|
+
throw err;
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}, {
|
|
184
|
+
highWaterMark: readableStrategy.highWaterMark ?? 0,
|
|
185
|
+
size: readableStrategy.size
|
|
186
|
+
});
|
|
187
|
+
resolveStart(start?.call(transformer, controller));
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
/**
|
|
191
|
+
* A `TransformStream` that calls the transformer's `cancel` method when the
|
|
192
|
+
* readable side is cancelled or the writable side is aborted, even in
|
|
193
|
+
* runtimes whose `TransformStream` doesn't support `cancel` yet. In runtimes
|
|
194
|
+
* that do, this is just `TransformStream`.
|
|
195
|
+
*/
|
|
196
|
+
const TransformStreamWithCancel = supportsTransformerCancel ? TransformStream : TransformStreamWithCancelPolyfill;
|
|
197
|
+
export { TransformStreamWithCancelPolyfill, TransformStreamWithCancel as default, supportsTransformerCancel };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "web-utility-streams",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0-canary-1",
|
|
4
4
|
"description": "Various utility streams that are very useful for working with web streams.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -84,10 +84,18 @@
|
|
|
84
84
|
"types": "./lib/SplitLinesStream.d.mts",
|
|
85
85
|
"default": "./lib/SplitLinesStream.mjs"
|
|
86
86
|
},
|
|
87
|
+
"./TimeoutStream": {
|
|
88
|
+
"types": "./lib/TimeoutStream.d.mts",
|
|
89
|
+
"default": "./lib/TimeoutStream.mjs"
|
|
90
|
+
},
|
|
87
91
|
"./TransformPipelineStream": {
|
|
88
92
|
"types": "./lib/TransformPipelineStream.d.mts",
|
|
89
93
|
"default": "./lib/TransformPipelineStream.mjs"
|
|
90
94
|
},
|
|
95
|
+
"./TransformStreamWithCancel": {
|
|
96
|
+
"types": "./lib/TransformStreamWithCancel.d.mts",
|
|
97
|
+
"default": "./lib/TransformStreamWithCancel.mjs"
|
|
98
|
+
},
|
|
91
99
|
"./UnionStream": {
|
|
92
100
|
"types": "./lib/UnionStream.d.mts",
|
|
93
101
|
"default": "./lib/UnionStream.mjs"
|