web-utility-streams 0.1.1 → 0.2.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/README.md CHANGED
@@ -6,6 +6,8 @@ Various utility streams that are very useful for working with web streams.
6
6
 
7
7
  **Transform streams**
8
8
 
9
+ - [`AddPrefixStream`](#addprefixstream) - Emit some chunks before the rest of the stream.
10
+ - [`DebounceStream`](#debouncestream) - Emit at most one chunk per period, dropping the rest.
9
11
  - [`DebugStream`](#debugstream) - Call a function with each chunk as it passes through.
10
12
  - [`EventSourceDecoderStream`](#eventsourcedecoderstream) - Decode `text/event-stream` (Server-Sent Events) text into events.
11
13
  - [`EventSourceEncoderStream`](#eventsourceencoderstream) - Encode events as `text/event-stream` (Server-Sent Events) text.
@@ -53,6 +55,40 @@ try {
53
55
 
54
56
  ## Transform streams
55
57
 
58
+ ### AddPrefixStream
59
+
60
+ Emit the chunks of a prefix, then pass the rest of the stream through unchanged. The prefix can be an array (or any other iterable), an async iterable, a `ReadableStream`, or a promise for one of these.
61
+
62
+ ```ts
63
+ import AddPrefixStream from "web-utility-streams/AddPrefixStream";
64
+
65
+ const events = updates.pipeThrough(
66
+ new AddPrefixStream(getCurrentState().then((state) => [state])),
67
+ );
68
+ ```
69
+
70
+ The prefix is only read as the output is read, and written chunks wait until it's done. If the prefix errors, the stream errors. If the stream is cancelled or errors first, the prefix is closed, so a generator's `finally` blocks run and a `ReadableStream` is cancelled.
71
+
72
+ ### DebounceStream
73
+
74
+ Emit at most one chunk every `debounceMs` milliseconds, dropping the rest. This is useful for things like progress updates, where only the latest value matters.
75
+
76
+ ```ts
77
+ import DebounceStream from "web-utility-streams/DebounceStream";
78
+
79
+ const progress = progressEvents.pipeThrough(
80
+ new DebounceStream({ debounceMs: 100 }),
81
+ );
82
+ ```
83
+
84
+ A period starts when a chunk is written and nothing has been emitted in the last `debounceMs`. The `mode` option controls which chunks of each period are emitted:
85
+
86
+ - `"BOTH"` (the default): the first chunk straight away, and the most recent chunk at the end of the period, if there was another.
87
+ - `"LEADING"`: only the first chunk, straight away.
88
+ - `"TRAILING"`: only the most recent chunk, at the end of the period.
89
+
90
+ Emitting a trailing chunk starts a new period. Pass `restartTimerOnChunk: true` to extend the period each time a chunk is written, so it only ends after a gap of `debounceMs`. When the input closes, a waiting trailing chunk is emitted straight away. Writes never wait for the output to be read; if it falls behind, only the most recent chunk is kept.
91
+
56
92
  ### DebugStream
57
93
 
58
94
  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.
@@ -0,0 +1,19 @@
1
+ export type AddPrefixStreamPrefix<TChunk> = AsyncIterable<TChunk> | Iterable<TChunk> | ReadableStream<TChunk> | PromiseLike<AsyncIterable<TChunk> | Iterable<TChunk> | ReadableStream<TChunk>>;
2
+ /**
3
+ * Emit the chunks of `prefix`, then pass every chunk written to the stream
4
+ * through unchanged. The prefix can be an iterable, an async iterable, a
5
+ * `ReadableStream`, or a promise for any of these.
6
+ *
7
+ * - The prefix is read as the output is read. Written chunks wait until the
8
+ * prefix is done, and then up to 4 are read ahead of the output.
9
+ * - If the prefix errors, the stream is errored, cancelling the source.
10
+ * - If the writable side is aborted, the output is errored straight away.
11
+ * - If the stream is cancelled or errors before the prefix is done, the
12
+ * prefix is closed (by calling its iterator's `return` method, or by
13
+ * cancelling the `ReadableStream`).
14
+ */
15
+ export default class AddPrefixStream<TChunk> implements TransformStream<TChunk, TChunk> {
16
+ readonly readable: ReadableStream<TChunk>;
17
+ readonly writable: WritableStream<TChunk>;
18
+ constructor(prefix: AddPrefixStreamPrefix<TChunk>);
19
+ }
@@ -0,0 +1,139 @@
1
+ // src/AddPrefixStream.ts
2
+ const noop = () => {};
3
+ /**
4
+ * Emit the chunks of `prefix`, then pass every chunk written to the stream
5
+ * through unchanged. The prefix can be an iterable, an async iterable, a
6
+ * `ReadableStream`, or a promise for any of these.
7
+ *
8
+ * - The prefix is read as the output is read. Written chunks wait until the
9
+ * prefix is done, and then up to 4 are read ahead of the output.
10
+ * - If the prefix errors, the stream is errored, cancelling the source.
11
+ * - If the writable side is aborted, the output is errored straight away.
12
+ * - If the stream is cancelled or errors before the prefix is done, the
13
+ * prefix is closed (by calling its iterator's `return` method, or by
14
+ * cancelling the `ReadableStream`).
15
+ */
16
+ var AddPrefixStream = class {
17
+ readable;
18
+ writable;
19
+ constructor(prefix) {
20
+ let readableController;
21
+ let writableController;
22
+ let isFinished = false;
23
+ let finishReason;
24
+ let iterator;
25
+ let isAsyncIterator = false;
26
+ let isPrefixDone = false;
27
+ let pendingWrite;
28
+ let isWritableClosed = false;
29
+ const closePrefix = () => {
30
+ const it = iterator;
31
+ const reason = finishReason;
32
+ iterator = void 0;
33
+ if (it?.return) Promise.resolve().then(() => it.return(reason)).catch(noop);
34
+ };
35
+ const finish = (reason) => {
36
+ isFinished = true;
37
+ finishReason = reason;
38
+ pendingWrite?.reject(reason);
39
+ closePrefix();
40
+ };
41
+ const fail = (err) => {
42
+ if (isFinished) return;
43
+ readableController.error(err);
44
+ writableController.error(err);
45
+ finish(err);
46
+ };
47
+ const abort = (reason) => {
48
+ if (isFinished) return;
49
+ readableController.error(reason);
50
+ finish(reason);
51
+ };
52
+ const pullWritten = () => {
53
+ if (pendingWrite) {
54
+ const { chunk, resolve } = pendingWrite;
55
+ pendingWrite = void 0;
56
+ readableController.enqueue(chunk);
57
+ resolve();
58
+ } else if (isWritableClosed) {
59
+ isFinished = true;
60
+ readableController.close();
61
+ }
62
+ };
63
+ const onPrefixResult = (result) => {
64
+ if (isFinished) return;
65
+ if (!result.done) {
66
+ readableController.enqueue(result.value);
67
+ return;
68
+ }
69
+ iterator = void 0;
70
+ isPrefixDone = true;
71
+ pullWritten();
72
+ };
73
+ this.writable = new WritableStream({
74
+ start(controller) {
75
+ writableController = controller;
76
+ controller.signal?.addEventListener("abort", () => abort(controller.signal.reason));
77
+ },
78
+ write(chunk) {
79
+ if (isPrefixDone && readableController.desiredSize >= -2) {
80
+ readableController.enqueue(chunk);
81
+ return;
82
+ }
83
+ return new Promise((resolve, reject) => {
84
+ pendingWrite = {
85
+ chunk,
86
+ resolve,
87
+ reject
88
+ };
89
+ });
90
+ },
91
+ close() {
92
+ isWritableClosed = true;
93
+ if (isPrefixDone && !isFinished) {
94
+ isFinished = true;
95
+ readableController.close();
96
+ }
97
+ },
98
+ abort
99
+ });
100
+ this.readable = new ReadableStream({
101
+ async start(controller) {
102
+ readableController = controller;
103
+ try {
104
+ const iterable = await prefix;
105
+ if (typeof iterable.getReader === "function") {
106
+ const reader = iterable.getReader();
107
+ isAsyncIterator = true;
108
+ iterator = {
109
+ next: () => reader.read(),
110
+ return: (reason) => reader.cancel(reason)
111
+ };
112
+ } else {
113
+ isAsyncIterator = typeof iterable[Symbol.asyncIterator] === "function";
114
+ iterator = isAsyncIterator ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
115
+ }
116
+ if (isFinished) closePrefix();
117
+ } catch (ex) {
118
+ fail(ex);
119
+ }
120
+ },
121
+ pull() {
122
+ if (isPrefixDone) return pullWritten();
123
+ if (isAsyncIterator) return iterator.next().then(onPrefixResult, fail);
124
+ let result;
125
+ try {
126
+ result = iterator.next();
127
+ } catch (ex) {
128
+ return fail(ex);
129
+ }
130
+ onPrefixResult(result);
131
+ },
132
+ cancel(reason) {
133
+ writableController.error(reason);
134
+ finish(reason);
135
+ }
136
+ }, { highWaterMark: 0 });
137
+ }
138
+ };
139
+ export { AddPrefixStream as default };
@@ -0,0 +1,33 @@
1
+ export interface DebounceStreamOptions {
2
+ debounceMs: number;
3
+ /**
4
+ * Which chunks of each period to emit:
5
+ * - `"BOTH"` (the default): the first chunk straight away, and the most
6
+ * recent chunk at the end of the period, if there was another.
7
+ * - `"LEADING"`: only the first chunk, straight away.
8
+ * - `"TRAILING"`: only the most recent chunk, at the end of the period.
9
+ */
10
+ mode?: "LEADING" | "TRAILING" | "BOTH";
11
+ /**
12
+ * Extend the period each time a chunk is written, so it only ends once no
13
+ * chunks have been written for `debounceMs`.
14
+ *
15
+ * @default false
16
+ */
17
+ restartTimerOnChunk?: boolean;
18
+ }
19
+ /**
20
+ * Emit at most one chunk every `debounceMs` milliseconds, dropping the rest.
21
+ *
22
+ * - A period starts when a chunk is written and nothing has been emitted in
23
+ * the last `debounceMs`. Emitting a trailing chunk starts a new period.
24
+ * - When the writable side closes, a trailing chunk that is waiting is
25
+ * emitted straight away.
26
+ * - Writes never wait for the output to be read. If the output isn't read
27
+ * before the next chunk is emitted, only the most recent one is kept.
28
+ */
29
+ export default class DebounceStream<TChunk> implements TransformStream<TChunk, TChunk> {
30
+ readonly readable: ReadableStream<TChunk>;
31
+ readonly writable: WritableStream<TChunk>;
32
+ constructor({ debounceMs, mode, restartTimerOnChunk }: DebounceStreamOptions);
33
+ }
@@ -0,0 +1,102 @@
1
+ // src/DebounceStream.ts
2
+ /**
3
+ * Emit at most one chunk every `debounceMs` milliseconds, dropping the rest.
4
+ *
5
+ * - A period starts when a chunk is written and nothing has been emitted in
6
+ * the last `debounceMs`. Emitting a trailing chunk starts a new period.
7
+ * - When the writable side closes, a trailing chunk that is waiting is
8
+ * emitted straight away.
9
+ * - Writes never wait for the output to be read. If the output isn't read
10
+ * before the next chunk is emitted, only the most recent one is kept.
11
+ */
12
+ var DebounceStream = class {
13
+ readable;
14
+ writable;
15
+ constructor({ debounceMs, mode = "BOTH", restartTimerOnChunk = false }) {
16
+ if (!(debounceMs >= 0)) throw new RangeError(`debounceMs must be a number >= 0, but got ${debounceMs}`);
17
+ if (mode !== "LEADING" && mode !== "TRAILING" && mode !== "BOTH") throw new TypeError(`mode must be "LEADING", "TRAILING" or "BOTH", but got ${mode}`);
18
+ const leading = mode !== "TRAILING";
19
+ const trailing = mode !== "LEADING";
20
+ let readableController;
21
+ let writableController;
22
+ let timer;
23
+ let periodEnd = 0;
24
+ let hasTrailing = false;
25
+ let trailingChunk;
26
+ let hasOutput = false;
27
+ let outputChunk;
28
+ let isReadWaiting = false;
29
+ const emit = (chunk) => {
30
+ if (isReadWaiting) {
31
+ isReadWaiting = false;
32
+ readableController.enqueue(chunk);
33
+ } else {
34
+ hasOutput = true;
35
+ outputChunk = chunk;
36
+ }
37
+ };
38
+ const startPeriod = () => {
39
+ if (restartTimerOnChunk) periodEnd = performance.now() + debounceMs;
40
+ timer = setTimeout(endPeriod, debounceMs);
41
+ };
42
+ const endPeriod = () => {
43
+ if (restartTimerOnChunk) {
44
+ const remaining = periodEnd - performance.now();
45
+ if (remaining > 0) {
46
+ timer = setTimeout(endPeriod, remaining);
47
+ return;
48
+ }
49
+ }
50
+ timer = void 0;
51
+ if (!hasTrailing) return;
52
+ const chunk = trailingChunk;
53
+ hasTrailing = false;
54
+ trailingChunk = void 0;
55
+ emit(chunk);
56
+ startPeriod();
57
+ };
58
+ this.readable = new ReadableStream({
59
+ start(c) {
60
+ readableController = c;
61
+ },
62
+ pull() {
63
+ if (hasOutput) {
64
+ const chunk = outputChunk;
65
+ hasOutput = false;
66
+ outputChunk = void 0;
67
+ readableController.enqueue(chunk);
68
+ } else isReadWaiting = true;
69
+ },
70
+ cancel(reason) {
71
+ clearTimeout(timer);
72
+ writableController.error(reason);
73
+ }
74
+ }, { highWaterMark: 0 });
75
+ this.writable = new WritableStream({
76
+ start(c) {
77
+ writableController = c;
78
+ },
79
+ write(chunk) {
80
+ if (timer === void 0) {
81
+ startPeriod();
82
+ if (leading) return emit(chunk);
83
+ } else if (restartTimerOnChunk) periodEnd = performance.now() + debounceMs;
84
+ if (trailing) {
85
+ hasTrailing = true;
86
+ trailingChunk = chunk;
87
+ }
88
+ },
89
+ close() {
90
+ if (hasTrailing) emit(trailingChunk);
91
+ if (hasOutput) readableController.enqueue(outputChunk);
92
+ clearTimeout(timer);
93
+ readableController.close();
94
+ },
95
+ abort(reason) {
96
+ clearTimeout(timer);
97
+ readableController.error(reason);
98
+ }
99
+ });
100
+ }
101
+ };
102
+ export { DebounceStream as default };
package/package.json CHANGED
@@ -1,9 +1,13 @@
1
1
  {
2
2
  "name": "web-utility-streams",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Various utility streams that are very useful for working with web streams.",
5
5
  "type": "module",
6
6
  "exports": {
7
+ "./AddPrefixStream": {
8
+ "types": "./lib/AddPrefixStream.d.mts",
9
+ "default": "./lib/AddPrefixStream.mjs"
10
+ },
7
11
  "./ConcatStream": {
8
12
  "types": "./lib/ConcatStream.d.mts",
9
13
  "default": "./lib/ConcatStream.mjs"
@@ -12,6 +16,10 @@
12
16
  "types": "./lib/consumers.d.mts",
13
17
  "default": "./lib/consumers.mjs"
14
18
  },
19
+ "./DebounceStream": {
20
+ "types": "./lib/DebounceStream.d.mts",
21
+ "default": "./lib/DebounceStream.mjs"
22
+ },
15
23
  "./DebugStream": {
16
24
  "types": "./lib/DebugStream.d.mts",
17
25
  "default": "./lib/DebugStream.mjs"