web-utility-streams 0.1.0 → 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 +37 -1
- package/lib/AddPrefixStream.d.mts +19 -0
- package/lib/AddPrefixStream.mjs +139 -0
- package/lib/DebounceStream.d.mts +33 -0
- package/lib/DebounceStream.mjs +102 -0
- package/lib/JsonDecoderStream.d.mts +10 -2
- package/lib/JsonDecoderStream.mjs +5 -4
- package/lib/JsonTokenDecoderStream.d.mts +6 -0
- package/lib/JsonTokenDecoderStream.mjs +1 -1
- package/lib/{JsonTokenizer-BFV5P0dO.mjs → JsonTokenizer-BtRpnxKn.mjs} +2 -1
- package/lib/consumers.d.mts +3 -2
- package/lib/consumers.mjs +17 -7
- package/package.json +9 -1
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.
|
|
@@ -163,7 +199,7 @@ const strings = values.pipeThrough(
|
|
|
163
199
|
|
|
164
200
|
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
201
|
|
|
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
|
|
202
|
+
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. Any single value longer than `maxValueLength` characters (default 100 MiB) errors the stream as soon as that length is exceeded, so a huge or never-ending value can't use unlimited memory. 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
203
|
|
|
168
204
|
```ts
|
|
169
205
|
import JsonDecoderStream from "web-utility-streams/JsonDecoderStream";
|
|
@@ -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 };
|
|
@@ -20,6 +20,13 @@ export interface JsonDecoderStreamOptions {
|
|
|
20
20
|
* in memory until the end of the document, rather than being discarded.
|
|
21
21
|
*/
|
|
22
22
|
readonly onExtraData?: (extraData: unknown) => void;
|
|
23
|
+
/**
|
|
24
|
+
* The maximum length, in characters, of any single value in the document
|
|
25
|
+
* (each emitted element, each discarded object/array, and each string or
|
|
26
|
+
* number). If a value is longer than this, the stream is errored, so that
|
|
27
|
+
* an unexpectedly large (or never-ending) value can't use unlimited memory.
|
|
28
|
+
* Defaults to 100 MiB (`100 * 2 ** 20` characters).
|
|
29
|
+
*/
|
|
23
30
|
readonly maxValueLength?: number;
|
|
24
31
|
}
|
|
25
32
|
/**
|
|
@@ -39,8 +46,9 @@ export interface JsonDecoderStreamOptions {
|
|
|
39
46
|
* `onExtraData` callback. If the document is not valid JSON, the stream is
|
|
40
47
|
* errored when the problem is found. For speed, each element (and each
|
|
41
48
|
* object/array that is being discarded) is parsed in one go when its end is
|
|
42
|
-
* reached, so a problem inside one is found when its end is reached
|
|
43
|
-
*
|
|
49
|
+
* reached, so a problem inside one is found when its end is reached. A value
|
|
50
|
+
* longer than `maxValueLength` errors the stream as soon as that length is
|
|
51
|
+
* exceeded. If there is no array/object at `path`, the
|
|
44
52
|
* stream is errored once the whole document has been parsed. Because elements
|
|
45
53
|
* are emitted as soon as they are parsed, some elements may be emitted before
|
|
46
54
|
* an error is found later in the document.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as JsonTokenizer } from "./JsonTokenizer-
|
|
1
|
+
import { t as JsonTokenizer } from "./JsonTokenizer-BtRpnxKn.mjs";
|
|
2
2
|
// src/JsonDecoderStream.ts
|
|
3
3
|
/**
|
|
4
4
|
* Decode a JSON array or object from a stream of text, emitting each element
|
|
@@ -17,8 +17,9 @@ import { t as JsonTokenizer } from "./JsonTokenizer-BFV5P0dO.mjs";
|
|
|
17
17
|
* `onExtraData` callback. If the document is not valid JSON, the stream is
|
|
18
18
|
* errored when the problem is found. For speed, each element (and each
|
|
19
19
|
* object/array that is being discarded) is parsed in one go when its end is
|
|
20
|
-
* reached, so a problem inside one is found when its end is reached
|
|
21
|
-
*
|
|
20
|
+
* reached, so a problem inside one is found when its end is reached. A value
|
|
21
|
+
* longer than `maxValueLength` errors the stream as soon as that length is
|
|
22
|
+
* exceeded. If there is no array/object at `path`, the
|
|
22
23
|
* stream is errored once the whole document has been parsed. Because elements
|
|
23
24
|
* are emitted as soon as they are parsed, some elements may be emitted before
|
|
24
25
|
* an error is found later in the document.
|
|
@@ -29,7 +30,7 @@ import { t as JsonTokenizer } from "./JsonTokenizer-BFV5P0dO.mjs";
|
|
|
29
30
|
* `JSON.parse`, which keeps only the last value).
|
|
30
31
|
*/
|
|
31
32
|
var JsonDecoderStream = class extends TransformStream {
|
|
32
|
-
constructor({ path = [], maxValueLength = 100 *
|
|
33
|
+
constructor({ path = [], maxValueLength = 100 * 2 ** 20, onExtraData } = {}) {
|
|
33
34
|
const stack = [];
|
|
34
35
|
let foundTarget = false;
|
|
35
36
|
let extraData;
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
export interface JsonTokenDecoderStreamOptions {
|
|
2
|
+
/**
|
|
3
|
+
* The maximum length, in characters, of any single string, number or
|
|
4
|
+
* literal token. If a token is longer than this, the stream is errored, so
|
|
5
|
+
* that an unexpectedly large (or never-ending) token can't use unlimited
|
|
6
|
+
* memory. Defaults to 100 MiB (`100 * 2 ** 20` characters).
|
|
7
|
+
*/
|
|
2
8
|
readonly maxValueLength?: number;
|
|
3
9
|
}
|
|
4
10
|
/**
|
|
@@ -206,6 +206,7 @@ var JsonTokenizer = class {
|
|
|
206
206
|
this._state = isEscaped ? this._state | STATE_ESCAPED : this._state & -1025;
|
|
207
207
|
if (end === chunk.length) {
|
|
208
208
|
this._tokenText += chunk.slice(i);
|
|
209
|
+
if (this._tokenText.length > this._maxValueLength) this._valueExceedsMaxLength(this._tokenPosition);
|
|
209
210
|
i = end;
|
|
210
211
|
} else {
|
|
211
212
|
this._tokenText += chunk.slice(i, end + 1);
|
|
@@ -225,7 +226,7 @@ var JsonTokenizer = class {
|
|
|
225
226
|
if (end < chunk.length) {
|
|
226
227
|
if (isNumber) this._endNumber();
|
|
227
228
|
else this._endLiteral();
|
|
228
|
-
}
|
|
229
|
+
} else if (this._tokenText.length > this._maxValueLength) this._valueExceedsMaxLength(this._tokenPosition);
|
|
229
230
|
continue;
|
|
230
231
|
}
|
|
231
232
|
const code = chunk.charCodeAt(i);
|
package/lib/consumers.d.mts
CHANGED
|
@@ -9,8 +9,9 @@ export type ConsumableChunk = string | ArrayBuffer | ArrayBufferView;
|
|
|
9
9
|
*/
|
|
10
10
|
export type ConsumableStream = ReadableStream<ConsumableChunk> | AsyncIterable<ConsumableChunk>;
|
|
11
11
|
/**
|
|
12
|
-
* Read the entire stream, and decode its contents as UTF-8 text.
|
|
13
|
-
* byte order mark is removed
|
|
12
|
+
* Read the entire stream, and decode its contents as UTF-8 text. If the stream
|
|
13
|
+
* starts with bytes, a leading UTF-8 byte order mark is removed (string chunks
|
|
14
|
+
* are used as they are). Rejects if the stream errors.
|
|
14
15
|
*/
|
|
15
16
|
export declare function textFromStream(stream: ConsumableStream): Promise<string>;
|
|
16
17
|
/**
|
package/lib/consumers.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// src/consumers.ts
|
|
2
2
|
const encoder = new TextEncoder();
|
|
3
3
|
/**
|
|
4
|
-
* Read the entire stream, and decode its contents as UTF-8 text.
|
|
5
|
-
* byte order mark is removed
|
|
4
|
+
* Read the entire stream, and decode its contents as UTF-8 text. If the stream
|
|
5
|
+
* starts with bytes, a leading UTF-8 byte order mark is removed (string chunks
|
|
6
|
+
* are used as they are). Rejects if the stream errors.
|
|
6
7
|
*/
|
|
7
8
|
async function textFromStream(stream) {
|
|
8
9
|
const chunks = stream[Symbol.asyncIterator]();
|
|
@@ -12,23 +13,32 @@ async function textFromStream(stream) {
|
|
|
12
13
|
if (typeof firstChunk.value === "string") return await textFromStreamOfStrings(chunks, firstChunk.value);
|
|
13
14
|
return await textFromStreamOfBytes(chunks, toUint8Array(firstChunk.value));
|
|
14
15
|
} catch (ex) {
|
|
15
|
-
|
|
16
|
+
try {
|
|
17
|
+
await chunks.return?.();
|
|
18
|
+
} catch {}
|
|
16
19
|
throw ex;
|
|
17
20
|
}
|
|
18
21
|
}
|
|
19
22
|
async function textFromStreamOfStrings(stream, firstChunk) {
|
|
20
23
|
let decoder;
|
|
24
|
+
let decoderHasBytes = false;
|
|
21
25
|
let result = firstChunk;
|
|
22
26
|
let next = await stream.next();
|
|
23
27
|
while (!next.done) {
|
|
24
|
-
if (typeof next.value === "string")
|
|
25
|
-
|
|
26
|
-
|
|
28
|
+
if (typeof next.value === "string") {
|
|
29
|
+
if (decoderHasBytes) {
|
|
30
|
+
result += decoder.decode();
|
|
31
|
+
decoderHasBytes = false;
|
|
32
|
+
}
|
|
33
|
+
result += next.value;
|
|
34
|
+
} else {
|
|
35
|
+
decoder ??= new TextDecoder("utf-8", { ignoreBOM: true });
|
|
27
36
|
result += decoder.decode(toUint8Array(next.value), { stream: true });
|
|
37
|
+
decoderHasBytes = true;
|
|
28
38
|
}
|
|
29
39
|
next = await stream.next();
|
|
30
40
|
}
|
|
31
|
-
if (!
|
|
41
|
+
if (!decoderHasBytes) return result;
|
|
32
42
|
return result + decoder.decode();
|
|
33
43
|
}
|
|
34
44
|
async function textFromStreamOfBytes(stream, firstChunk) {
|
package/package.json
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "web-utility-streams",
|
|
3
|
-
"version": "0.
|
|
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"
|