create-web-stream 1.0.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.
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright © 2026 OkaYu
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 ADDED
@@ -0,0 +1,16 @@
1
+ Note: **I’m using a translation tool, so there may be some inappropriate expressions.**
2
+
3
+ # Overview
4
+ This library provides functions for creating Web API `ReadableStream` and `WritableStream` instances from simple handlers, with support for BYOB readers, buffered writers, AbortSignal integration, and guaranteed cleanup callbacks.
5
+
6
+ # API
7
+ - `createReadableStream`
8
+ - `createWriteableFileStream`
9
+
10
+ # License
11
+ This project is licensed under either of
12
+
13
+ * MIT license
14
+ * Apache License (Version 2.0)
15
+
16
+ at your option.
package/dist/index.cjs ADDED
@@ -0,0 +1,274 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Creates a `ReadableStream` that yields byte data using the provided custom handler.
5
+ *
6
+ * This function does not throw errors.
7
+ * If you need to throw an error early when the provided `options.signal` is already aborted,
8
+ * the caller must check and handle it manually.
9
+ * The resulting stream includes a BYOB (Bring Your Own Buffer) reader if supported by the runtime.
10
+ *
11
+ * @param handler The stream handler: `read`, `release`. See `CreateReadableStreamHandler` for details.
12
+ * @param options Optional settings: `signal`. See `CreateReadableStreamOptions` for details.
13
+ * @returns A `ReadableStream<Uint8Array<ArrayBuffer>>` configured with the provided handler and options.
14
+ */
15
+ function createReadableStream(handler, options) {
16
+ let abortListener = null;
17
+ let buffer = null;
18
+ let cleanupPromise = null;
19
+ function cleanup(type, reason) {
20
+ if (cleanupPromise === null) {
21
+ cleanupPromise = (async () => {
22
+ buffer = null;
23
+ if (options?.signal != null && abortListener != null) {
24
+ options.signal.removeEventListener("abort", abortListener);
25
+ abortListener = null;
26
+ }
27
+ if (handler.release != null) {
28
+ await handler.release(type, reason);
29
+ }
30
+ })();
31
+ }
32
+ return cleanupPromise;
33
+ }
34
+ if (!isReadableByteStreamAvailable()) {
35
+ return new ReadableStream({
36
+ start(controller) {
37
+ if (options?.signal != null) {
38
+ abortListener = () => {
39
+ const reason = options?.signal?.reason ?? newAbortSignalDefaultError();
40
+ cleanup("SignalAbort", reason).catch(() => { });
41
+ controller.error(reason);
42
+ };
43
+ options?.signal?.addEventListener("abort", abortListener);
44
+ }
45
+ },
46
+ async pull(controller) {
47
+ try {
48
+ throwIfAborted(options?.signal);
49
+ const data = await handler.read();
50
+ throwIfAborted(options?.signal);
51
+ if (data == null || data.byteLength === 0) {
52
+ await cleanup("Close");
53
+ controller.close();
54
+ return;
55
+ }
56
+ controller.enqueue(data);
57
+ }
58
+ catch (e) {
59
+ const isSignalAbort = isThrownByAbortSignal(e, options?.signal);
60
+ await cleanup(isSignalAbort ? "SignalAbort" : "Error", e).catch(() => { });
61
+ throw e;
62
+ }
63
+ },
64
+ async cancel(reason) {
65
+ await cleanup("Cancel", reason);
66
+ }
67
+ });
68
+ }
69
+ // autoAllocateChunkSize を指定すると stream.getReader() でも byob が使われるようになるが、
70
+ // この実装で byob を用いてもコピーが増えるだけで恩恵が少ないため指定しない。
71
+ // また type: "bytes" で strategy を指定すると (正確には size を定義すると) エラーになる点にも注意。
72
+ return new ReadableStream({
73
+ type: "bytes",
74
+ start(controller) {
75
+ if (options?.signal) {
76
+ abortListener = () => {
77
+ const reason = options?.signal?.reason ?? newAbortSignalDefaultError();
78
+ cleanup("SignalAbort", reason).catch(() => { });
79
+ controller.error(reason);
80
+ };
81
+ options?.signal.addEventListener("abort", abortListener);
82
+ }
83
+ },
84
+ async pull(controller) {
85
+ try {
86
+ throwIfAborted(options?.signal);
87
+ if (buffer == null || buffer.byteLength === 0) {
88
+ buffer = (await handler.read()) ?? null;
89
+ throwIfAborted(options?.signal);
90
+ }
91
+ if (buffer == null || buffer.byteLength === 0) {
92
+ await cleanup("Close");
93
+ // byobRequest がある場合、respond を呼ばないと promise が解決されない。
94
+ // controller.close() の後だと respond(0) を読んでもエラーにはならない。
95
+ // https://github.com/whatwg/streams/issues/1170
96
+ controller.close();
97
+ controller.byobRequest?.respond(0);
98
+ return;
99
+ }
100
+ const byob = controller.byobRequest;
101
+ // byobRequest がある場合、respond を呼ばないと promise が解決されないことに注意
102
+ if (byob != null) {
103
+ // respond する前なので null にならない
104
+ const v = byob.view;
105
+ const view = new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
106
+ const nread = Math.min(buffer.byteLength, view.byteLength);
107
+ view.set(buffer.subarray(0, nread));
108
+ buffer = buffer.subarray(nread);
109
+ throwIfAborted(options?.signal);
110
+ byob.respond(nread);
111
+ }
112
+ else {
113
+ throwIfAborted(options?.signal);
114
+ controller.enqueue(buffer);
115
+ buffer = null;
116
+ }
117
+ }
118
+ catch (e) {
119
+ const isSignalAbort = isThrownByAbortSignal(e, options?.signal);
120
+ await cleanup(isSignalAbort ? "SignalAbort" : "Error", e).catch(() => { });
121
+ // byobRequest が存在する場合、controller.close() を呼んだだけでは
122
+ // Promise は解決されず、respond() も呼ぶ必要がある。
123
+ // controller.error() も同様の挙動になる可能性がある。(要検証)
124
+ // 少なくとも throw すれば Promise は解決されるため、現状はこの実装とする。
125
+ throw e;
126
+ }
127
+ },
128
+ async cancel(reason) {
129
+ await cleanup("Cancel", reason);
130
+ }
131
+ });
132
+ }
133
+ /**
134
+ * Creates a `WritableStream` that writes byte data using the provided custom handler.
135
+ *
136
+ * This function itself does not throw errors.
137
+ * If you need to throw an error early when the provided `options.signal` is already aborted,
138
+ * the caller must check and handle it manually.
139
+ *
140
+ * @param handler - The stream handler: `write`, `release`. See `CreateWritableStreamHandler` for details.
141
+ * @param options - Optional settings: `signal`, `bufferSize`, `strictBufferSize`, `useBufferView`. See `CreateWritableStreamOptions` for details.
142
+ * @returns A `WritableStream<Uint8Array<ArrayBufferLike>>` instance configured with the provided handler and options.
143
+ */
144
+ function createWritableStream(handler, options) {
145
+ const bufferSize = Math.max(0, Math.ceil(options?.bufferSize ?? 0));
146
+ let abortListener = null;
147
+ let buffer = null;
148
+ let bufferOffset = 0;
149
+ let cleanupPromise = null;
150
+ function cleanup(type, reason) {
151
+ if (cleanupPromise === null) {
152
+ cleanupPromise = (async () => {
153
+ buffer = null;
154
+ if (options?.signal != null && abortListener != null) {
155
+ options?.signal?.removeEventListener("abort", abortListener);
156
+ abortListener = null;
157
+ }
158
+ if (handler.release != null) {
159
+ await handler.release(type, reason);
160
+ }
161
+ })();
162
+ }
163
+ return cleanupPromise;
164
+ }
165
+ return new WritableStream({
166
+ start(controller) {
167
+ if (options?.signal != null) {
168
+ abortListener = () => {
169
+ const reason = options?.signal?.reason ?? newAbortSignalDefaultError();
170
+ cleanup("SignalAbort", reason).catch(() => { });
171
+ controller.error(reason);
172
+ };
173
+ options?.signal.addEventListener("abort", abortListener);
174
+ }
175
+ },
176
+ async write(src) {
177
+ try {
178
+ throwIfAborted(options?.signal);
179
+ // bufferSize が 0 以下の場合や src が buffer より大きい場合は buffer を使わずに処理する。
180
+ if (bufferSize <= 0 ||
181
+ (bufferSize <= src.byteLength && options?.strictBufferSize !== true)) {
182
+ // buffer に既にデータがある場合、それを処理する。
183
+ if (buffer !== null && 0 < bufferOffset) {
184
+ const chunk = options?.useBufferView === true
185
+ ? buffer.subarray(0, bufferOffset)
186
+ : buffer.slice(0, bufferOffset);
187
+ throwIfAborted(options?.signal);
188
+ await handler.write(chunk);
189
+ bufferOffset = 0;
190
+ }
191
+ throwIfAborted(options?.signal);
192
+ await handler.write(mapToArrayBuffer(src));
193
+ return;
194
+ }
195
+ let srcOffset = 0;
196
+ while (srcOffset < src.byteLength) {
197
+ throwIfAborted(options?.signal);
198
+ if (buffer === null) {
199
+ buffer = new Uint8Array(bufferSize);
200
+ }
201
+ const n = Math.min(bufferSize - bufferOffset, src.byteLength - srcOffset);
202
+ buffer.set(src.subarray(srcOffset, srcOffset + n), bufferOffset);
203
+ bufferOffset += n;
204
+ srcOffset += n;
205
+ if (bufferOffset === bufferSize) {
206
+ throwIfAborted(options?.signal);
207
+ const chunk = buffer;
208
+ if (options?.useBufferView !== true) {
209
+ buffer = null;
210
+ }
211
+ await handler.write(chunk);
212
+ bufferOffset = 0;
213
+ }
214
+ }
215
+ }
216
+ catch (e) {
217
+ const isSignalAbort = isThrownByAbortSignal(e, options?.signal);
218
+ await cleanup(isSignalAbort ? "SignalAbort" : "Error", e).catch(() => { });
219
+ throw e;
220
+ }
221
+ },
222
+ async close() {
223
+ try {
224
+ if (0 < bufferOffset && buffer != null) {
225
+ const view = buffer.subarray(0, bufferOffset);
226
+ buffer = null;
227
+ await handler.write(view);
228
+ }
229
+ await cleanup("Close");
230
+ }
231
+ catch (e) {
232
+ await cleanup("Error", e).catch(() => { });
233
+ throw e;
234
+ }
235
+ },
236
+ async abort(reason) {
237
+ await cleanup("Abort", reason);
238
+ }
239
+ });
240
+ }
241
+ let _isReadableByteStreamAvailable = null;
242
+ function isReadableByteStreamAvailable() {
243
+ if (_isReadableByteStreamAvailable === null) {
244
+ try {
245
+ new ReadableStream({ type: "bytes" });
246
+ _isReadableByteStreamAvailable = true;
247
+ }
248
+ catch {
249
+ _isReadableByteStreamAvailable = false;
250
+ }
251
+ }
252
+ return _isReadableByteStreamAvailable;
253
+ }
254
+ function throwIfAborted(signal) {
255
+ if (signal?.aborted === true) {
256
+ throw (signal?.reason ?? newAbortSignalDefaultError());
257
+ }
258
+ }
259
+ function newAbortSignalDefaultError() {
260
+ return new DOMException("The operation was aborted.", "AbortError");
261
+ }
262
+ function isThrownByAbortSignal(err, signal) {
263
+ return (signal?.aborted === true) &&
264
+ (err === signal.reason || (err instanceof DOMException && err.name === "AbortError"));
265
+ }
266
+ function mapToArrayBuffer(buffer) {
267
+ return buffer.buffer instanceof ArrayBuffer
268
+ ? buffer
269
+ : new Uint8Array(buffer);
270
+ }
271
+
272
+ exports.createReadableStream = createReadableStream;
273
+ exports.createWritableStream = createWritableStream;
274
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["export type CreateReadableStreamHandlerSource = Uint8Array<ArrayBuffer> | null | undefined\n\nexport type CreateReadableStreamHandlerReleaseType = \"Close\" | \"Cancel\" | \"SignalAbort\" | \"Error\"\n\nexport type CreateReadableStreamHandler = {\n\n\t/**\n\t * A callback invoked when the stream's consumer requests more data.\n\t * \n\t * - **Yielding data**: Return a `Uint8Array` containing the next chunk of bytes.\n\t * - **Ending the stream**: Return `null`, `undefined`, or an empty `Uint8Array` (`byteLength === 0`) to signal that no more data is available. This will automatically close the stream.\n\t * - **Handling errors**: If an error is thrown inside this function, the stream will enter an error state and terminate.\n\t */\n\tread: () => PromiseLike<CreateReadableStreamHandlerSource> | CreateReadableStreamHandlerSource,\n\n\t/**\n\t * An optional callback for performing cleanup operations.\n\t * \n\t * This function is guaranteed to be invoked at most once. \n\t * It is automatically triggered when the stream terminates under any of the following conditions:\n\t * - The stream's reader is successfully read to the end. (type: `\"Close\"`)\n\t * - The stream or its reader is explicitly canceled. (type: `\"Cancel\"`)\n\t * - The provided `AbortSignal` fires an `abort` event. (type: `\"SignalAbort\"`)\n\t * - An error occurs during a read operation. (type: `\"Error\"`)\n\t */\n\trelease?: (type: CreateReadableStreamHandlerReleaseType, reason?: unknown) => PromiseLike<void> | void,\n}\n\nexport type CreateReadableStreamOptions = {\n\n\t/**\n\t * An `AbortSignal` to abort the stream.\n\t * \n\t * When the abort event is fired, the handler's `release` function will be called.\n\t */\n\tsignal?: AbortSignal\n}\n\n/**\n * Creates a `ReadableStream` that yields byte data using the provided custom handler.\n * \n * This function does not throw errors. \n * If you need to throw an error early when the provided `options.signal` is already aborted,\n * the caller must check and handle it manually.\n * The resulting stream includes a BYOB (Bring Your Own Buffer) reader if supported by the runtime.\n * \n * @param handler The stream handler: `read`, `release`. See `CreateReadableStreamHandler` for details.\n * @param options Optional settings: `signal`. See `CreateReadableStreamOptions` for details.\n * @returns A `ReadableStream<Uint8Array<ArrayBuffer>>` configured with the provided handler and options.\n */\nexport function createReadableStream(\n\thandler: CreateReadableStreamHandler,\n\toptions?: CreateReadableStreamOptions,\n): ReadableStream<Uint8Array<ArrayBuffer>> {\n\n\tlet abortListener: (() => void) | null = null\n\tlet buffer: Uint8Array<ArrayBuffer> | null = null\n\n\tlet cleanupPromise: Promise<void> | null = null\n\tfunction cleanup(\n\t\ttype: CreateReadableStreamHandlerReleaseType,\n\t\treason?: unknown\n\t): Promise<void> {\n\n\t\tif (cleanupPromise === null) {\n\t\t\tcleanupPromise = (async () => {\n\t\t\t\tbuffer = null\n\t\t\t\tif (options?.signal != null && abortListener != null) {\n\t\t\t\t\toptions.signal.removeEventListener(\"abort\", abortListener)\n\t\t\t\t\tabortListener = null\n\t\t\t\t}\n\t\t\t\tif (handler.release != null) {\n\t\t\t\t\tawait handler.release(type, reason)\n\t\t\t\t}\n\t\t\t})()\n\t\t}\n\t\treturn cleanupPromise\n\t}\n\n\tif (!isReadableByteStreamAvailable()) {\n\t\treturn new ReadableStream({\n\n\t\t\tstart(controller) {\n\t\t\t\tif (options?.signal != null) {\n\t\t\t\t\tabortListener = () => {\n\t\t\t\t\t\tconst reason = options?.signal?.reason ?? newAbortSignalDefaultError()\n\t\t\t\t\t\tcleanup(\"SignalAbort\", reason).catch(() => { })\n\t\t\t\t\t\tcontroller.error(reason)\n\t\t\t\t\t}\n\t\t\t\t\toptions?.signal?.addEventListener(\"abort\", abortListener);\n\t\t\t\t}\n\t\t\t},\n\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tconst data = await handler.read()\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tif (data == null || data.byteLength === 0) {\n\t\t\t\t\t\tawait cleanup(\"Close\")\n\t\t\t\t\t\tcontroller.close()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tcontroller.enqueue(data)\n\t\t\t\t}\n\t\t\t\tcatch (e) {\n\t\t\t\t\tconst isSignalAbort = isThrownByAbortSignal(e, options?.signal)\n\t\t\t\t\tawait cleanup(isSignalAbort ? \"SignalAbort\" : \"Error\", e).catch(() => { })\n\t\t\t\t\tthrow e\n\t\t\t\t}\n\t\t\t},\n\n\t\t\tasync cancel(reason) {\n\t\t\t\tawait cleanup(\"Cancel\", reason)\n\t\t\t}\n\t\t})\n\t}\n\n\t// autoAllocateChunkSize を指定すると stream.getReader() でも byob が使われるようになるが、\n\t// この実装で byob を用いてもコピーが増えるだけで恩恵が少ないため指定しない。\n\t// また type: \"bytes\" で strategy を指定すると (正確には size を定義すると) エラーになる点にも注意。\n\treturn new ReadableStream({\n\t\ttype: \"bytes\",\n\n\t\tstart(controller) {\n\t\t\tif (options?.signal) {\n\t\t\t\tabortListener = () => {\n\t\t\t\t\tconst reason = options?.signal?.reason ?? newAbortSignalDefaultError()\n\t\t\t\t\tcleanup(\"SignalAbort\", reason).catch(() => { })\n\t\t\t\t\tcontroller.error(reason)\n\t\t\t\t}\n\t\t\t\toptions?.signal.addEventListener(\"abort\", abortListener)\n\t\t\t}\n\t\t},\n\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\tif (buffer == null || buffer.byteLength === 0) {\n\t\t\t\t\tbuffer = (await handler.read()) ?? null\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t}\n\t\t\t\tif (buffer == null || buffer.byteLength === 0) {\n\t\t\t\t\tawait cleanup(\"Close\")\n\n\t\t\t\t\t// byobRequest がある場合、respond を呼ばないと promise が解決されない。\n\t\t\t\t\t// controller.close() の後だと respond(0) を読んでもエラーにはならない。\n\t\t\t\t\t// https://github.com/whatwg/streams/issues/1170\n\t\t\t\t\tcontroller.close()\n\t\t\t\t\tcontroller.byobRequest?.respond(0)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst byob = controller.byobRequest\n\t\t\t\t// byobRequest がある場合、respond を呼ばないと promise が解決されないことに注意\n\t\t\t\tif (byob != null) {\n\t\t\t\t\t// respond する前なので null にならない\n\t\t\t\t\tconst v = byob.view!!\n\t\t\t\t\tconst view = new Uint8Array(v.buffer, v.byteOffset, v.byteLength)\n\t\t\t\t\tconst nread = Math.min(buffer.byteLength, view.byteLength)\n\n\t\t\t\t\tview.set(buffer.subarray(0, nread))\n\t\t\t\t\tbuffer = buffer.subarray(nread)\n\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tbyob.respond(nread)\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tcontroller.enqueue(buffer)\n\t\t\t\t\tbuffer = null\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\tconst isSignalAbort = isThrownByAbortSignal(e, options?.signal)\n\t\t\t\tawait cleanup(isSignalAbort ? \"SignalAbort\" : \"Error\", e).catch(() => { })\n\n\t\t\t\t// byobRequest が存在する場合、controller.close() を呼んだだけでは\n\t\t\t\t// Promise は解決されず、respond() も呼ぶ必要がある。\n\t\t\t\t// controller.error() も同様の挙動になる可能性がある。(要検証)\n\t\t\t\t// 少なくとも throw すれば Promise は解決されるため、現状はこの実装とする。\n\t\t\t\tthrow e\n\t\t\t}\n\t\t},\n\n\t\tasync cancel(reason) {\n\t\t\tawait cleanup(\"Cancel\", reason)\n\t\t}\n\t})\n}\n\n\nexport type CreateWritableStreamHandlerReleaseType = \"Close\" | \"Abort\" | \"SignalAbort\" | \"Error\"\n\nexport type CreateWritableStreamHandler = {\n\n\t/**\n\t * A callback invoked when a new chunk of byte data is ready to be written.\n\t * \n\t * - **Data Chunk**: Receives a `Uint8Array` containing the data. The exact size and memory reference of this chunk depend on the stream's `bufferSize` and `strictBufferSize` options.\n\t * - **Data Safety**: If `options.useBufferView` is `true`, the `chunk` might be a direct view (subarray) of the internal buffer. To prevent data corruption, do not retain references to this view outside this callback.\n\t * - **Handling Errors**: If an error is thrown inside this function, the stream will enter an error state and terminate.\n\t */\n\twrite: (chunk: Uint8Array<ArrayBuffer>) => PromiseLike<void> | void,\n\n\t/**\n\t * A callback for performing cleanup operations.\n\t * \n\t * This function is guaranteed to be invoked at most once. \n\t * It is automatically triggered when the stream terminates under any of the following conditions:\n\t * - The stream or its writer is explicitly closed. (type: `\"Close\"`)\n\t * - The stream or its writer is explicitly aborted. (type: `\"Abort\"`)\n\t * - The provided `AbortSignal` fires an `abort` event. (type: `\"SignalAbort\"`)\n\t * - An error occurs during a write operation. (type: `\"Error\"`)\n\t */\n\trelease?: (\n\t\ttype: CreateWritableStreamHandlerReleaseType,\n\t\treason?: unknown\n\t) => PromiseLike<void> | void,\n}\n\nexport type CreateWritableStreamOptions = {\n\n\t/**\n\t * An `AbortSignal` to abort the stream.\n\t * \n\t * When the abort event is fired, the handler's `release` function will be called.\n\t */\n\tsignal?: AbortSignal,\n\n\t/**\n\t * The size of the internal buffer in bytes.\n\t * \n\t * Defaults to `0` (unbuffered).\n\t */\n\tbufferSize?: number,\n\n\t/**\n\t * If `true`, the stream strictly enforces the `bufferSize` for every chunk passed to the handler.\n\t * Only the final `write` call may receive a chunk smaller than the `bufferSize`.\n\t * \n\t * If `false`, chunks larger than the `bufferSize` will bypass the internal buffer and be processed directly.\n\t * \n\t * Defaults to `false`.\n\t */\n\tstrictBufferSize?: boolean,\n\n\t/**\n\t * If `true`, the handler's `write` method can receive a chunk as a view (subarray) of the internal buffer.\n\t * This reduces the number of memory copies, but the received chunk must not be referenced outside the `write` method.\n\t * If you need to retain the chunk data externally, you must make a copy of it within the `write` method.\n\t * \n\t * Defaults to `false`.\n\t */\n\tuseBufferView?: boolean,\n}\n\n/**\n * Creates a `WritableStream` that writes byte data using the provided custom handler.\n * \n * This function itself does not throw errors.\n * If you need to throw an error early when the provided `options.signal` is already aborted, \n * the caller must check and handle it manually.\n * \n * @param handler - The stream handler: `write`, `release`. See `CreateWritableStreamHandler` for details.\n * @param options - Optional settings: `signal`, `bufferSize`, `strictBufferSize`, `useBufferView`. See `CreateWritableStreamOptions` for details.\n * @returns A `WritableStream<Uint8Array<ArrayBufferLike>>` instance configured with the provided handler and options.\n */\nexport function createWritableStream(\n\thandler: CreateWritableStreamHandler,\n\toptions?: CreateWritableStreamOptions,\n): WritableStream<Uint8Array<ArrayBufferLike>> {\n\n\tconst bufferSize = Math.max(0, Math.ceil(options?.bufferSize ?? 0))\n\n\tlet abortListener: (() => void) | null = null;\n\tlet buffer: Uint8Array<ArrayBuffer> | null = null;\n\tlet bufferOffset = 0;\n\n\tlet cleanupPromise: Promise<void> | null = null;\n\tfunction cleanup(\n\t\ttype: CreateWritableStreamHandlerReleaseType,\n\t\treason?: unknown\n\t): Promise<void> {\n\n\t\tif (cleanupPromise === null) {\n\t\t\tcleanupPromise = (async () => {\n\t\t\t\tbuffer = null\n\t\t\t\tif (options?.signal != null && abortListener != null) {\n\t\t\t\t\toptions?.signal?.removeEventListener(\"abort\", abortListener)\n\t\t\t\t\tabortListener = null\n\t\t\t\t}\n\t\t\t\tif (handler.release != null) {\n\t\t\t\t\tawait handler.release(type, reason)\n\t\t\t\t}\n\t\t\t})()\n\t\t}\n\t\treturn cleanupPromise\n\t}\n\n\treturn new WritableStream<Uint8Array<ArrayBufferLike>>({\n\n\t\tstart(controller) {\n\t\t\tif (options?.signal != null) {\n\t\t\t\tabortListener = () => {\n\t\t\t\t\tconst reason = options?.signal?.reason ?? newAbortSignalDefaultError()\n\t\t\t\t\tcleanup(\"SignalAbort\", reason).catch(() => { })\n\t\t\t\t\tcontroller.error(reason)\n\t\t\t\t}\n\t\t\t\toptions?.signal.addEventListener(\"abort\", abortListener);\n\t\t\t}\n\t\t},\n\n\t\tasync write(src) {\n\t\t\ttry {\n\t\t\t\tthrowIfAborted(options?.signal)\n\n\t\t\t\t// bufferSize が 0 以下の場合や src が buffer より大きい場合は buffer を使わずに処理する。\n\t\t\t\tif (\n\t\t\t\t\tbufferSize <= 0 ||\n\t\t\t\t\t(bufferSize <= src.byteLength && options?.strictBufferSize !== true)\n\t\t\t\t) {\n\n\t\t\t\t\t// buffer に既にデータがある場合、それを処理する。\n\t\t\t\t\tif (buffer !== null && 0 < bufferOffset) {\n\t\t\t\t\t\tconst chunk = options?.useBufferView === true\n\t\t\t\t\t\t\t? buffer.subarray(0, bufferOffset)\n\t\t\t\t\t\t\t: buffer.slice(0, bufferOffset)\n\n\t\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\t\tawait handler.write(chunk)\n\t\t\t\t\t\tbufferOffset = 0\n\t\t\t\t\t}\n\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tawait handler.write(mapToArrayBuffer(src))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tlet srcOffset = 0;\n\t\t\t\twhile (srcOffset < src.byteLength) {\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tif (buffer === null) {\n\t\t\t\t\t\tbuffer = new Uint8Array(bufferSize)\n\t\t\t\t\t}\n\n\t\t\t\t\tconst n = Math.min(bufferSize - bufferOffset, src.byteLength - srcOffset)\n\t\t\t\t\tbuffer.set(src.subarray(srcOffset, srcOffset + n), bufferOffset)\n\t\t\t\t\tbufferOffset += n\n\t\t\t\t\tsrcOffset += n\n\n\t\t\t\t\tif (bufferOffset === bufferSize) {\n\t\t\t\t\t\tthrowIfAborted(options?.signal)\n\n\t\t\t\t\t\tconst chunk = buffer\n\t\t\t\t\t\tif (options?.useBufferView !== true) {\n\t\t\t\t\t\t\tbuffer = null\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait handler.write(chunk)\n\t\t\t\t\t\tbufferOffset = 0\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\tconst isSignalAbort = isThrownByAbortSignal(e, options?.signal)\n\t\t\t\tawait cleanup(isSignalAbort ? \"SignalAbort\" : \"Error\", e).catch(() => { })\n\t\t\t\tthrow e\n\t\t\t}\n\t\t},\n\n\t\tasync close() {\n\t\t\ttry {\n\t\t\t\tif (0 < bufferOffset && buffer != null) {\n\t\t\t\t\tconst view = buffer.subarray(0, bufferOffset)\n\t\t\t\t\tbuffer = null\n\t\t\t\t\tawait handler.write(view)\n\t\t\t\t}\n\t\t\t\tawait cleanup(\"Close\")\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\tawait cleanup(\"Error\", e).catch(() => { })\n\t\t\t\tthrow e\n\t\t\t}\n\t\t},\n\n\t\tasync abort(reason) {\n\t\t\tawait cleanup(\"Abort\", reason)\n\t\t}\n\t})\n}\n\n\nlet _isReadableByteStreamAvailable: boolean | null = null\nfunction isReadableByteStreamAvailable() {\n\tif (_isReadableByteStreamAvailable === null) {\n\t\ttry {\n\t\t\tnew ReadableStream({ type: \"bytes\" })\n\t\t\t_isReadableByteStreamAvailable = true\n\t\t}\n\t\tcatch {\n\t\t\t_isReadableByteStreamAvailable = false\n\t\t}\n\t}\n\n\treturn _isReadableByteStreamAvailable\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined | null) {\n\tif (signal?.aborted === true) {\n\t\tthrow (signal?.reason ?? newAbortSignalDefaultError())\n\t}\n}\n\nfunction newAbortSignalDefaultError(): Error {\n\treturn new DOMException(\"The operation was aborted.\", \"AbortError\")\n}\n\nfunction isThrownByAbortSignal(err: unknown, signal: AbortSignal | null | undefined): boolean {\n\treturn (signal?.aborted === true) &&\n\t\t(err === signal.reason || (err instanceof DOMException && err.name === \"AbortError\"));\n}\n\nfunction mapToArrayBuffer(\n\tbuffer: Uint8Array<ArrayBufferLike>\n): Uint8Array<ArrayBuffer> {\n\n\treturn buffer.buffer instanceof ArrayBuffer\n\t\t? buffer as Uint8Array<ArrayBuffer>\n\t\t: new Uint8Array(buffer)\n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AG,KAAK,MAAM,CAAC,MAAM,KAAK,GAAG,YAAY,YAAY,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC;AACvF;AAEA,SAAS,gBAAgB,CACxB,MAAmC,EAAA;AAGnC,IAAA,OAAO,MAAM,CAAC,MAAM,YAAY;AAC/B,UAAE;AACF,UAAE,IAAI,UAAU,CAAC,MAAM,CAAC;AAC1B;;;;;"}
@@ -0,0 +1,109 @@
1
+ export type CreateReadableStreamHandlerSource = Uint8Array<ArrayBuffer> | null | undefined;
2
+ export type CreateReadableStreamHandlerReleaseType = "Close" | "Cancel" | "SignalAbort" | "Error";
3
+ export type CreateReadableStreamHandler = {
4
+ /**
5
+ * A callback invoked when the stream's consumer requests more data.
6
+ *
7
+ * - **Yielding data**: Return a `Uint8Array` containing the next chunk of bytes.
8
+ * - **Ending the stream**: Return `null`, `undefined`, or an empty `Uint8Array` (`byteLength === 0`) to signal that no more data is available. This will automatically close the stream.
9
+ * - **Handling errors**: If an error is thrown inside this function, the stream will enter an error state and terminate.
10
+ */
11
+ read: () => PromiseLike<CreateReadableStreamHandlerSource> | CreateReadableStreamHandlerSource;
12
+ /**
13
+ * An optional callback for performing cleanup operations.
14
+ *
15
+ * This function is guaranteed to be invoked at most once.
16
+ * It is automatically triggered when the stream terminates under any of the following conditions:
17
+ * - The stream's reader is successfully read to the end. (type: `"Close"`)
18
+ * - The stream or its reader is explicitly canceled. (type: `"Cancel"`)
19
+ * - The provided `AbortSignal` fires an `abort` event. (type: `"SignalAbort"`)
20
+ * - An error occurs during a read operation. (type: `"Error"`)
21
+ */
22
+ release?: (type: CreateReadableStreamHandlerReleaseType, reason?: unknown) => PromiseLike<void> | void;
23
+ };
24
+ export type CreateReadableStreamOptions = {
25
+ /**
26
+ * An `AbortSignal` to abort the stream.
27
+ *
28
+ * When the abort event is fired, the handler's `release` function will be called.
29
+ */
30
+ signal?: AbortSignal;
31
+ };
32
+ /**
33
+ * Creates a `ReadableStream` that yields byte data using the provided custom handler.
34
+ *
35
+ * This function does not throw errors.
36
+ * If you need to throw an error early when the provided `options.signal` is already aborted,
37
+ * the caller must check and handle it manually.
38
+ * The resulting stream includes a BYOB (Bring Your Own Buffer) reader if supported by the runtime.
39
+ *
40
+ * @param handler The stream handler: `read`, `release`. See `CreateReadableStreamHandler` for details.
41
+ * @param options Optional settings: `signal`. See `CreateReadableStreamOptions` for details.
42
+ * @returns A `ReadableStream<Uint8Array<ArrayBuffer>>` configured with the provided handler and options.
43
+ */
44
+ export declare function createReadableStream(handler: CreateReadableStreamHandler, options?: CreateReadableStreamOptions): ReadableStream<Uint8Array<ArrayBuffer>>;
45
+ export type CreateWritableStreamHandlerReleaseType = "Close" | "Abort" | "SignalAbort" | "Error";
46
+ export type CreateWritableStreamHandler = {
47
+ /**
48
+ * A callback invoked when a new chunk of byte data is ready to be written.
49
+ *
50
+ * - **Data Chunk**: Receives a `Uint8Array` containing the data. The exact size and memory reference of this chunk depend on the stream's `bufferSize` and `strictBufferSize` options.
51
+ * - **Data Safety**: If `options.useBufferView` is `true`, the `chunk` might be a direct view (subarray) of the internal buffer. To prevent data corruption, do not retain references to this view outside this callback.
52
+ * - **Handling Errors**: If an error is thrown inside this function, the stream will enter an error state and terminate.
53
+ */
54
+ write: (chunk: Uint8Array<ArrayBuffer>) => PromiseLike<void> | void;
55
+ /**
56
+ * A callback for performing cleanup operations.
57
+ *
58
+ * This function is guaranteed to be invoked at most once.
59
+ * It is automatically triggered when the stream terminates under any of the following conditions:
60
+ * - The stream or its writer is explicitly closed. (type: `"Close"`)
61
+ * - The stream or its writer is explicitly aborted. (type: `"Abort"`)
62
+ * - The provided `AbortSignal` fires an `abort` event. (type: `"SignalAbort"`)
63
+ * - An error occurs during a write operation. (type: `"Error"`)
64
+ */
65
+ release?: (type: CreateWritableStreamHandlerReleaseType, reason?: unknown) => PromiseLike<void> | void;
66
+ };
67
+ export type CreateWritableStreamOptions = {
68
+ /**
69
+ * An `AbortSignal` to abort the stream.
70
+ *
71
+ * When the abort event is fired, the handler's `release` function will be called.
72
+ */
73
+ signal?: AbortSignal;
74
+ /**
75
+ * The size of the internal buffer in bytes.
76
+ *
77
+ * Defaults to `0` (unbuffered).
78
+ */
79
+ bufferSize?: number;
80
+ /**
81
+ * If `true`, the stream strictly enforces the `bufferSize` for every chunk passed to the handler.
82
+ * Only the final `write` call may receive a chunk smaller than the `bufferSize`.
83
+ *
84
+ * If `false`, chunks larger than the `bufferSize` will bypass the internal buffer and be processed directly.
85
+ *
86
+ * Defaults to `false`.
87
+ */
88
+ strictBufferSize?: boolean;
89
+ /**
90
+ * If `true`, the handler's `write` method can receive a chunk as a view (subarray) of the internal buffer.
91
+ * This reduces the number of memory copies, but the received chunk must not be referenced outside the `write` method.
92
+ * If you need to retain the chunk data externally, you must make a copy of it within the `write` method.
93
+ *
94
+ * Defaults to `false`.
95
+ */
96
+ useBufferView?: boolean;
97
+ };
98
+ /**
99
+ * Creates a `WritableStream` that writes byte data using the provided custom handler.
100
+ *
101
+ * This function itself does not throw errors.
102
+ * If you need to throw an error early when the provided `options.signal` is already aborted,
103
+ * the caller must check and handle it manually.
104
+ *
105
+ * @param handler - The stream handler: `write`, `release`. See `CreateWritableStreamHandler` for details.
106
+ * @param options - Optional settings: `signal`, `bufferSize`, `strictBufferSize`, `useBufferView`. See `CreateWritableStreamOptions` for details.
107
+ * @returns A `WritableStream<Uint8Array<ArrayBufferLike>>` instance configured with the provided handler and options.
108
+ */
109
+ export declare function createWritableStream(handler: CreateWritableStreamHandler, options?: CreateWritableStreamOptions): WritableStream<Uint8Array<ArrayBufferLike>>;
package/dist/index.js ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Creates a `ReadableStream` that yields byte data using the provided custom handler.
3
+ *
4
+ * This function does not throw errors.
5
+ * If you need to throw an error early when the provided `options.signal` is already aborted,
6
+ * the caller must check and handle it manually.
7
+ * The resulting stream includes a BYOB (Bring Your Own Buffer) reader if supported by the runtime.
8
+ *
9
+ * @param handler The stream handler: `read`, `release`. See `CreateReadableStreamHandler` for details.
10
+ * @param options Optional settings: `signal`. See `CreateReadableStreamOptions` for details.
11
+ * @returns A `ReadableStream<Uint8Array<ArrayBuffer>>` configured with the provided handler and options.
12
+ */
13
+ function createReadableStream(handler, options) {
14
+ let abortListener = null;
15
+ let buffer = null;
16
+ let cleanupPromise = null;
17
+ function cleanup(type, reason) {
18
+ if (cleanupPromise === null) {
19
+ cleanupPromise = (async () => {
20
+ buffer = null;
21
+ if (options?.signal != null && abortListener != null) {
22
+ options.signal.removeEventListener("abort", abortListener);
23
+ abortListener = null;
24
+ }
25
+ if (handler.release != null) {
26
+ await handler.release(type, reason);
27
+ }
28
+ })();
29
+ }
30
+ return cleanupPromise;
31
+ }
32
+ if (!isReadableByteStreamAvailable()) {
33
+ return new ReadableStream({
34
+ start(controller) {
35
+ if (options?.signal != null) {
36
+ abortListener = () => {
37
+ const reason = options?.signal?.reason ?? newAbortSignalDefaultError();
38
+ cleanup("SignalAbort", reason).catch(() => { });
39
+ controller.error(reason);
40
+ };
41
+ options?.signal?.addEventListener("abort", abortListener);
42
+ }
43
+ },
44
+ async pull(controller) {
45
+ try {
46
+ throwIfAborted(options?.signal);
47
+ const data = await handler.read();
48
+ throwIfAborted(options?.signal);
49
+ if (data == null || data.byteLength === 0) {
50
+ await cleanup("Close");
51
+ controller.close();
52
+ return;
53
+ }
54
+ controller.enqueue(data);
55
+ }
56
+ catch (e) {
57
+ const isSignalAbort = isThrownByAbortSignal(e, options?.signal);
58
+ await cleanup(isSignalAbort ? "SignalAbort" : "Error", e).catch(() => { });
59
+ throw e;
60
+ }
61
+ },
62
+ async cancel(reason) {
63
+ await cleanup("Cancel", reason);
64
+ }
65
+ });
66
+ }
67
+ // autoAllocateChunkSize を指定すると stream.getReader() でも byob が使われるようになるが、
68
+ // この実装で byob を用いてもコピーが増えるだけで恩恵が少ないため指定しない。
69
+ // また type: "bytes" で strategy を指定すると (正確には size を定義すると) エラーになる点にも注意。
70
+ return new ReadableStream({
71
+ type: "bytes",
72
+ start(controller) {
73
+ if (options?.signal) {
74
+ abortListener = () => {
75
+ const reason = options?.signal?.reason ?? newAbortSignalDefaultError();
76
+ cleanup("SignalAbort", reason).catch(() => { });
77
+ controller.error(reason);
78
+ };
79
+ options?.signal.addEventListener("abort", abortListener);
80
+ }
81
+ },
82
+ async pull(controller) {
83
+ try {
84
+ throwIfAborted(options?.signal);
85
+ if (buffer == null || buffer.byteLength === 0) {
86
+ buffer = (await handler.read()) ?? null;
87
+ throwIfAborted(options?.signal);
88
+ }
89
+ if (buffer == null || buffer.byteLength === 0) {
90
+ await cleanup("Close");
91
+ // byobRequest がある場合、respond を呼ばないと promise が解決されない。
92
+ // controller.close() の後だと respond(0) を読んでもエラーにはならない。
93
+ // https://github.com/whatwg/streams/issues/1170
94
+ controller.close();
95
+ controller.byobRequest?.respond(0);
96
+ return;
97
+ }
98
+ const byob = controller.byobRequest;
99
+ // byobRequest がある場合、respond を呼ばないと promise が解決されないことに注意
100
+ if (byob != null) {
101
+ // respond する前なので null にならない
102
+ const v = byob.view;
103
+ const view = new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
104
+ const nread = Math.min(buffer.byteLength, view.byteLength);
105
+ view.set(buffer.subarray(0, nread));
106
+ buffer = buffer.subarray(nread);
107
+ throwIfAborted(options?.signal);
108
+ byob.respond(nread);
109
+ }
110
+ else {
111
+ throwIfAborted(options?.signal);
112
+ controller.enqueue(buffer);
113
+ buffer = null;
114
+ }
115
+ }
116
+ catch (e) {
117
+ const isSignalAbort = isThrownByAbortSignal(e, options?.signal);
118
+ await cleanup(isSignalAbort ? "SignalAbort" : "Error", e).catch(() => { });
119
+ // byobRequest が存在する場合、controller.close() を呼んだだけでは
120
+ // Promise は解決されず、respond() も呼ぶ必要がある。
121
+ // controller.error() も同様の挙動になる可能性がある。(要検証)
122
+ // 少なくとも throw すれば Promise は解決されるため、現状はこの実装とする。
123
+ throw e;
124
+ }
125
+ },
126
+ async cancel(reason) {
127
+ await cleanup("Cancel", reason);
128
+ }
129
+ });
130
+ }
131
+ /**
132
+ * Creates a `WritableStream` that writes byte data using the provided custom handler.
133
+ *
134
+ * This function itself does not throw errors.
135
+ * If you need to throw an error early when the provided `options.signal` is already aborted,
136
+ * the caller must check and handle it manually.
137
+ *
138
+ * @param handler - The stream handler: `write`, `release`. See `CreateWritableStreamHandler` for details.
139
+ * @param options - Optional settings: `signal`, `bufferSize`, `strictBufferSize`, `useBufferView`. See `CreateWritableStreamOptions` for details.
140
+ * @returns A `WritableStream<Uint8Array<ArrayBufferLike>>` instance configured with the provided handler and options.
141
+ */
142
+ function createWritableStream(handler, options) {
143
+ const bufferSize = Math.max(0, Math.ceil(options?.bufferSize ?? 0));
144
+ let abortListener = null;
145
+ let buffer = null;
146
+ let bufferOffset = 0;
147
+ let cleanupPromise = null;
148
+ function cleanup(type, reason) {
149
+ if (cleanupPromise === null) {
150
+ cleanupPromise = (async () => {
151
+ buffer = null;
152
+ if (options?.signal != null && abortListener != null) {
153
+ options?.signal?.removeEventListener("abort", abortListener);
154
+ abortListener = null;
155
+ }
156
+ if (handler.release != null) {
157
+ await handler.release(type, reason);
158
+ }
159
+ })();
160
+ }
161
+ return cleanupPromise;
162
+ }
163
+ return new WritableStream({
164
+ start(controller) {
165
+ if (options?.signal != null) {
166
+ abortListener = () => {
167
+ const reason = options?.signal?.reason ?? newAbortSignalDefaultError();
168
+ cleanup("SignalAbort", reason).catch(() => { });
169
+ controller.error(reason);
170
+ };
171
+ options?.signal.addEventListener("abort", abortListener);
172
+ }
173
+ },
174
+ async write(src) {
175
+ try {
176
+ throwIfAborted(options?.signal);
177
+ // bufferSize が 0 以下の場合や src が buffer より大きい場合は buffer を使わずに処理する。
178
+ if (bufferSize <= 0 ||
179
+ (bufferSize <= src.byteLength && options?.strictBufferSize !== true)) {
180
+ // buffer に既にデータがある場合、それを処理する。
181
+ if (buffer !== null && 0 < bufferOffset) {
182
+ const chunk = options?.useBufferView === true
183
+ ? buffer.subarray(0, bufferOffset)
184
+ : buffer.slice(0, bufferOffset);
185
+ throwIfAborted(options?.signal);
186
+ await handler.write(chunk);
187
+ bufferOffset = 0;
188
+ }
189
+ throwIfAborted(options?.signal);
190
+ await handler.write(mapToArrayBuffer(src));
191
+ return;
192
+ }
193
+ let srcOffset = 0;
194
+ while (srcOffset < src.byteLength) {
195
+ throwIfAborted(options?.signal);
196
+ if (buffer === null) {
197
+ buffer = new Uint8Array(bufferSize);
198
+ }
199
+ const n = Math.min(bufferSize - bufferOffset, src.byteLength - srcOffset);
200
+ buffer.set(src.subarray(srcOffset, srcOffset + n), bufferOffset);
201
+ bufferOffset += n;
202
+ srcOffset += n;
203
+ if (bufferOffset === bufferSize) {
204
+ throwIfAborted(options?.signal);
205
+ const chunk = buffer;
206
+ if (options?.useBufferView !== true) {
207
+ buffer = null;
208
+ }
209
+ await handler.write(chunk);
210
+ bufferOffset = 0;
211
+ }
212
+ }
213
+ }
214
+ catch (e) {
215
+ const isSignalAbort = isThrownByAbortSignal(e, options?.signal);
216
+ await cleanup(isSignalAbort ? "SignalAbort" : "Error", e).catch(() => { });
217
+ throw e;
218
+ }
219
+ },
220
+ async close() {
221
+ try {
222
+ if (0 < bufferOffset && buffer != null) {
223
+ const view = buffer.subarray(0, bufferOffset);
224
+ buffer = null;
225
+ await handler.write(view);
226
+ }
227
+ await cleanup("Close");
228
+ }
229
+ catch (e) {
230
+ await cleanup("Error", e).catch(() => { });
231
+ throw e;
232
+ }
233
+ },
234
+ async abort(reason) {
235
+ await cleanup("Abort", reason);
236
+ }
237
+ });
238
+ }
239
+ let _isReadableByteStreamAvailable = null;
240
+ function isReadableByteStreamAvailable() {
241
+ if (_isReadableByteStreamAvailable === null) {
242
+ try {
243
+ new ReadableStream({ type: "bytes" });
244
+ _isReadableByteStreamAvailable = true;
245
+ }
246
+ catch {
247
+ _isReadableByteStreamAvailable = false;
248
+ }
249
+ }
250
+ return _isReadableByteStreamAvailable;
251
+ }
252
+ function throwIfAborted(signal) {
253
+ if (signal?.aborted === true) {
254
+ throw (signal?.reason ?? newAbortSignalDefaultError());
255
+ }
256
+ }
257
+ function newAbortSignalDefaultError() {
258
+ return new DOMException("The operation was aborted.", "AbortError");
259
+ }
260
+ function isThrownByAbortSignal(err, signal) {
261
+ return (signal?.aborted === true) &&
262
+ (err === signal.reason || (err instanceof DOMException && err.name === "AbortError"));
263
+ }
264
+ function mapToArrayBuffer(buffer) {
265
+ return buffer.buffer instanceof ArrayBuffer
266
+ ? buffer
267
+ : new Uint8Array(buffer);
268
+ }
269
+
270
+ export { createReadableStream, createWritableStream };
271
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["export type CreateReadableStreamHandlerSource = Uint8Array<ArrayBuffer> | null | undefined\n\nexport type CreateReadableStreamHandlerReleaseType = \"Close\" | \"Cancel\" | \"SignalAbort\" | \"Error\"\n\nexport type CreateReadableStreamHandler = {\n\n\t/**\n\t * A callback invoked when the stream's consumer requests more data.\n\t * \n\t * - **Yielding data**: Return a `Uint8Array` containing the next chunk of bytes.\n\t * - **Ending the stream**: Return `null`, `undefined`, or an empty `Uint8Array` (`byteLength === 0`) to signal that no more data is available. This will automatically close the stream.\n\t * - **Handling errors**: If an error is thrown inside this function, the stream will enter an error state and terminate.\n\t */\n\tread: () => PromiseLike<CreateReadableStreamHandlerSource> | CreateReadableStreamHandlerSource,\n\n\t/**\n\t * An optional callback for performing cleanup operations.\n\t * \n\t * This function is guaranteed to be invoked at most once. \n\t * It is automatically triggered when the stream terminates under any of the following conditions:\n\t * - The stream's reader is successfully read to the end. (type: `\"Close\"`)\n\t * - The stream or its reader is explicitly canceled. (type: `\"Cancel\"`)\n\t * - The provided `AbortSignal` fires an `abort` event. (type: `\"SignalAbort\"`)\n\t * - An error occurs during a read operation. (type: `\"Error\"`)\n\t */\n\trelease?: (type: CreateReadableStreamHandlerReleaseType, reason?: unknown) => PromiseLike<void> | void,\n}\n\nexport type CreateReadableStreamOptions = {\n\n\t/**\n\t * An `AbortSignal` to abort the stream.\n\t * \n\t * When the abort event is fired, the handler's `release` function will be called.\n\t */\n\tsignal?: AbortSignal\n}\n\n/**\n * Creates a `ReadableStream` that yields byte data using the provided custom handler.\n * \n * This function does not throw errors. \n * If you need to throw an error early when the provided `options.signal` is already aborted,\n * the caller must check and handle it manually.\n * The resulting stream includes a BYOB (Bring Your Own Buffer) reader if supported by the runtime.\n * \n * @param handler The stream handler: `read`, `release`. See `CreateReadableStreamHandler` for details.\n * @param options Optional settings: `signal`. See `CreateReadableStreamOptions` for details.\n * @returns A `ReadableStream<Uint8Array<ArrayBuffer>>` configured with the provided handler and options.\n */\nexport function createReadableStream(\n\thandler: CreateReadableStreamHandler,\n\toptions?: CreateReadableStreamOptions,\n): ReadableStream<Uint8Array<ArrayBuffer>> {\n\n\tlet abortListener: (() => void) | null = null\n\tlet buffer: Uint8Array<ArrayBuffer> | null = null\n\n\tlet cleanupPromise: Promise<void> | null = null\n\tfunction cleanup(\n\t\ttype: CreateReadableStreamHandlerReleaseType,\n\t\treason?: unknown\n\t): Promise<void> {\n\n\t\tif (cleanupPromise === null) {\n\t\t\tcleanupPromise = (async () => {\n\t\t\t\tbuffer = null\n\t\t\t\tif (options?.signal != null && abortListener != null) {\n\t\t\t\t\toptions.signal.removeEventListener(\"abort\", abortListener)\n\t\t\t\t\tabortListener = null\n\t\t\t\t}\n\t\t\t\tif (handler.release != null) {\n\t\t\t\t\tawait handler.release(type, reason)\n\t\t\t\t}\n\t\t\t})()\n\t\t}\n\t\treturn cleanupPromise\n\t}\n\n\tif (!isReadableByteStreamAvailable()) {\n\t\treturn new ReadableStream({\n\n\t\t\tstart(controller) {\n\t\t\t\tif (options?.signal != null) {\n\t\t\t\t\tabortListener = () => {\n\t\t\t\t\t\tconst reason = options?.signal?.reason ?? newAbortSignalDefaultError()\n\t\t\t\t\t\tcleanup(\"SignalAbort\", reason).catch(() => { })\n\t\t\t\t\t\tcontroller.error(reason)\n\t\t\t\t\t}\n\t\t\t\t\toptions?.signal?.addEventListener(\"abort\", abortListener);\n\t\t\t\t}\n\t\t\t},\n\n\t\t\tasync pull(controller) {\n\t\t\t\ttry {\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tconst data = await handler.read()\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tif (data == null || data.byteLength === 0) {\n\t\t\t\t\t\tawait cleanup(\"Close\")\n\t\t\t\t\t\tcontroller.close()\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tcontroller.enqueue(data)\n\t\t\t\t}\n\t\t\t\tcatch (e) {\n\t\t\t\t\tconst isSignalAbort = isThrownByAbortSignal(e, options?.signal)\n\t\t\t\t\tawait cleanup(isSignalAbort ? \"SignalAbort\" : \"Error\", e).catch(() => { })\n\t\t\t\t\tthrow e\n\t\t\t\t}\n\t\t\t},\n\n\t\t\tasync cancel(reason) {\n\t\t\t\tawait cleanup(\"Cancel\", reason)\n\t\t\t}\n\t\t})\n\t}\n\n\t// autoAllocateChunkSize を指定すると stream.getReader() でも byob が使われるようになるが、\n\t// この実装で byob を用いてもコピーが増えるだけで恩恵が少ないため指定しない。\n\t// また type: \"bytes\" で strategy を指定すると (正確には size を定義すると) エラーになる点にも注意。\n\treturn new ReadableStream({\n\t\ttype: \"bytes\",\n\n\t\tstart(controller) {\n\t\t\tif (options?.signal) {\n\t\t\t\tabortListener = () => {\n\t\t\t\t\tconst reason = options?.signal?.reason ?? newAbortSignalDefaultError()\n\t\t\t\t\tcleanup(\"SignalAbort\", reason).catch(() => { })\n\t\t\t\t\tcontroller.error(reason)\n\t\t\t\t}\n\t\t\t\toptions?.signal.addEventListener(\"abort\", abortListener)\n\t\t\t}\n\t\t},\n\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\tif (buffer == null || buffer.byteLength === 0) {\n\t\t\t\t\tbuffer = (await handler.read()) ?? null\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t}\n\t\t\t\tif (buffer == null || buffer.byteLength === 0) {\n\t\t\t\t\tawait cleanup(\"Close\")\n\n\t\t\t\t\t// byobRequest がある場合、respond を呼ばないと promise が解決されない。\n\t\t\t\t\t// controller.close() の後だと respond(0) を読んでもエラーにはならない。\n\t\t\t\t\t// https://github.com/whatwg/streams/issues/1170\n\t\t\t\t\tcontroller.close()\n\t\t\t\t\tcontroller.byobRequest?.respond(0)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst byob = controller.byobRequest\n\t\t\t\t// byobRequest がある場合、respond を呼ばないと promise が解決されないことに注意\n\t\t\t\tif (byob != null) {\n\t\t\t\t\t// respond する前なので null にならない\n\t\t\t\t\tconst v = byob.view!!\n\t\t\t\t\tconst view = new Uint8Array(v.buffer, v.byteOffset, v.byteLength)\n\t\t\t\t\tconst nread = Math.min(buffer.byteLength, view.byteLength)\n\n\t\t\t\t\tview.set(buffer.subarray(0, nread))\n\t\t\t\t\tbuffer = buffer.subarray(nread)\n\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tbyob.respond(nread)\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tcontroller.enqueue(buffer)\n\t\t\t\t\tbuffer = null\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\tconst isSignalAbort = isThrownByAbortSignal(e, options?.signal)\n\t\t\t\tawait cleanup(isSignalAbort ? \"SignalAbort\" : \"Error\", e).catch(() => { })\n\n\t\t\t\t// byobRequest が存在する場合、controller.close() を呼んだだけでは\n\t\t\t\t// Promise は解決されず、respond() も呼ぶ必要がある。\n\t\t\t\t// controller.error() も同様の挙動になる可能性がある。(要検証)\n\t\t\t\t// 少なくとも throw すれば Promise は解決されるため、現状はこの実装とする。\n\t\t\t\tthrow e\n\t\t\t}\n\t\t},\n\n\t\tasync cancel(reason) {\n\t\t\tawait cleanup(\"Cancel\", reason)\n\t\t}\n\t})\n}\n\n\nexport type CreateWritableStreamHandlerReleaseType = \"Close\" | \"Abort\" | \"SignalAbort\" | \"Error\"\n\nexport type CreateWritableStreamHandler = {\n\n\t/**\n\t * A callback invoked when a new chunk of byte data is ready to be written.\n\t * \n\t * - **Data Chunk**: Receives a `Uint8Array` containing the data. The exact size and memory reference of this chunk depend on the stream's `bufferSize` and `strictBufferSize` options.\n\t * - **Data Safety**: If `options.useBufferView` is `true`, the `chunk` might be a direct view (subarray) of the internal buffer. To prevent data corruption, do not retain references to this view outside this callback.\n\t * - **Handling Errors**: If an error is thrown inside this function, the stream will enter an error state and terminate.\n\t */\n\twrite: (chunk: Uint8Array<ArrayBuffer>) => PromiseLike<void> | void,\n\n\t/**\n\t * A callback for performing cleanup operations.\n\t * \n\t * This function is guaranteed to be invoked at most once. \n\t * It is automatically triggered when the stream terminates under any of the following conditions:\n\t * - The stream or its writer is explicitly closed. (type: `\"Close\"`)\n\t * - The stream or its writer is explicitly aborted. (type: `\"Abort\"`)\n\t * - The provided `AbortSignal` fires an `abort` event. (type: `\"SignalAbort\"`)\n\t * - An error occurs during a write operation. (type: `\"Error\"`)\n\t */\n\trelease?: (\n\t\ttype: CreateWritableStreamHandlerReleaseType,\n\t\treason?: unknown\n\t) => PromiseLike<void> | void,\n}\n\nexport type CreateWritableStreamOptions = {\n\n\t/**\n\t * An `AbortSignal` to abort the stream.\n\t * \n\t * When the abort event is fired, the handler's `release` function will be called.\n\t */\n\tsignal?: AbortSignal,\n\n\t/**\n\t * The size of the internal buffer in bytes.\n\t * \n\t * Defaults to `0` (unbuffered).\n\t */\n\tbufferSize?: number,\n\n\t/**\n\t * If `true`, the stream strictly enforces the `bufferSize` for every chunk passed to the handler.\n\t * Only the final `write` call may receive a chunk smaller than the `bufferSize`.\n\t * \n\t * If `false`, chunks larger than the `bufferSize` will bypass the internal buffer and be processed directly.\n\t * \n\t * Defaults to `false`.\n\t */\n\tstrictBufferSize?: boolean,\n\n\t/**\n\t * If `true`, the handler's `write` method can receive a chunk as a view (subarray) of the internal buffer.\n\t * This reduces the number of memory copies, but the received chunk must not be referenced outside the `write` method.\n\t * If you need to retain the chunk data externally, you must make a copy of it within the `write` method.\n\t * \n\t * Defaults to `false`.\n\t */\n\tuseBufferView?: boolean,\n}\n\n/**\n * Creates a `WritableStream` that writes byte data using the provided custom handler.\n * \n * This function itself does not throw errors.\n * If you need to throw an error early when the provided `options.signal` is already aborted, \n * the caller must check and handle it manually.\n * \n * @param handler - The stream handler: `write`, `release`. See `CreateWritableStreamHandler` for details.\n * @param options - Optional settings: `signal`, `bufferSize`, `strictBufferSize`, `useBufferView`. See `CreateWritableStreamOptions` for details.\n * @returns A `WritableStream<Uint8Array<ArrayBufferLike>>` instance configured with the provided handler and options.\n */\nexport function createWritableStream(\n\thandler: CreateWritableStreamHandler,\n\toptions?: CreateWritableStreamOptions,\n): WritableStream<Uint8Array<ArrayBufferLike>> {\n\n\tconst bufferSize = Math.max(0, Math.ceil(options?.bufferSize ?? 0))\n\n\tlet abortListener: (() => void) | null = null;\n\tlet buffer: Uint8Array<ArrayBuffer> | null = null;\n\tlet bufferOffset = 0;\n\n\tlet cleanupPromise: Promise<void> | null = null;\n\tfunction cleanup(\n\t\ttype: CreateWritableStreamHandlerReleaseType,\n\t\treason?: unknown\n\t): Promise<void> {\n\n\t\tif (cleanupPromise === null) {\n\t\t\tcleanupPromise = (async () => {\n\t\t\t\tbuffer = null\n\t\t\t\tif (options?.signal != null && abortListener != null) {\n\t\t\t\t\toptions?.signal?.removeEventListener(\"abort\", abortListener)\n\t\t\t\t\tabortListener = null\n\t\t\t\t}\n\t\t\t\tif (handler.release != null) {\n\t\t\t\t\tawait handler.release(type, reason)\n\t\t\t\t}\n\t\t\t})()\n\t\t}\n\t\treturn cleanupPromise\n\t}\n\n\treturn new WritableStream<Uint8Array<ArrayBufferLike>>({\n\n\t\tstart(controller) {\n\t\t\tif (options?.signal != null) {\n\t\t\t\tabortListener = () => {\n\t\t\t\t\tconst reason = options?.signal?.reason ?? newAbortSignalDefaultError()\n\t\t\t\t\tcleanup(\"SignalAbort\", reason).catch(() => { })\n\t\t\t\t\tcontroller.error(reason)\n\t\t\t\t}\n\t\t\t\toptions?.signal.addEventListener(\"abort\", abortListener);\n\t\t\t}\n\t\t},\n\n\t\tasync write(src) {\n\t\t\ttry {\n\t\t\t\tthrowIfAborted(options?.signal)\n\n\t\t\t\t// bufferSize が 0 以下の場合や src が buffer より大きい場合は buffer を使わずに処理する。\n\t\t\t\tif (\n\t\t\t\t\tbufferSize <= 0 ||\n\t\t\t\t\t(bufferSize <= src.byteLength && options?.strictBufferSize !== true)\n\t\t\t\t) {\n\n\t\t\t\t\t// buffer に既にデータがある場合、それを処理する。\n\t\t\t\t\tif (buffer !== null && 0 < bufferOffset) {\n\t\t\t\t\t\tconst chunk = options?.useBufferView === true\n\t\t\t\t\t\t\t? buffer.subarray(0, bufferOffset)\n\t\t\t\t\t\t\t: buffer.slice(0, bufferOffset)\n\n\t\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\t\tawait handler.write(chunk)\n\t\t\t\t\t\tbufferOffset = 0\n\t\t\t\t\t}\n\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tawait handler.write(mapToArrayBuffer(src))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tlet srcOffset = 0;\n\t\t\t\twhile (srcOffset < src.byteLength) {\n\t\t\t\t\tthrowIfAborted(options?.signal)\n\t\t\t\t\tif (buffer === null) {\n\t\t\t\t\t\tbuffer = new Uint8Array(bufferSize)\n\t\t\t\t\t}\n\n\t\t\t\t\tconst n = Math.min(bufferSize - bufferOffset, src.byteLength - srcOffset)\n\t\t\t\t\tbuffer.set(src.subarray(srcOffset, srcOffset + n), bufferOffset)\n\t\t\t\t\tbufferOffset += n\n\t\t\t\t\tsrcOffset += n\n\n\t\t\t\t\tif (bufferOffset === bufferSize) {\n\t\t\t\t\t\tthrowIfAborted(options?.signal)\n\n\t\t\t\t\t\tconst chunk = buffer\n\t\t\t\t\t\tif (options?.useBufferView !== true) {\n\t\t\t\t\t\t\tbuffer = null\n\t\t\t\t\t\t}\n\t\t\t\t\t\tawait handler.write(chunk)\n\t\t\t\t\t\tbufferOffset = 0\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\tconst isSignalAbort = isThrownByAbortSignal(e, options?.signal)\n\t\t\t\tawait cleanup(isSignalAbort ? \"SignalAbort\" : \"Error\", e).catch(() => { })\n\t\t\t\tthrow e\n\t\t\t}\n\t\t},\n\n\t\tasync close() {\n\t\t\ttry {\n\t\t\t\tif (0 < bufferOffset && buffer != null) {\n\t\t\t\t\tconst view = buffer.subarray(0, bufferOffset)\n\t\t\t\t\tbuffer = null\n\t\t\t\t\tawait handler.write(view)\n\t\t\t\t}\n\t\t\t\tawait cleanup(\"Close\")\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\tawait cleanup(\"Error\", e).catch(() => { })\n\t\t\t\tthrow e\n\t\t\t}\n\t\t},\n\n\t\tasync abort(reason) {\n\t\t\tawait cleanup(\"Abort\", reason)\n\t\t}\n\t})\n}\n\n\nlet _isReadableByteStreamAvailable: boolean | null = null\nfunction isReadableByteStreamAvailable() {\n\tif (_isReadableByteStreamAvailable === null) {\n\t\ttry {\n\t\t\tnew ReadableStream({ type: \"bytes\" })\n\t\t\t_isReadableByteStreamAvailable = true\n\t\t}\n\t\tcatch {\n\t\t\t_isReadableByteStreamAvailable = false\n\t\t}\n\t}\n\n\treturn _isReadableByteStreamAvailable\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined | null) {\n\tif (signal?.aborted === true) {\n\t\tthrow (signal?.reason ?? newAbortSignalDefaultError())\n\t}\n}\n\nfunction newAbortSignalDefaultError(): Error {\n\treturn new DOMException(\"The operation was aborted.\", \"AbortError\")\n}\n\nfunction isThrownByAbortSignal(err: unknown, signal: AbortSignal | null | undefined): boolean {\n\treturn (signal?.aborted === true) &&\n\t\t(err === signal.reason || (err instanceof DOMException && err.name === \"AbortError\"));\n}\n\nfunction mapToArrayBuffer(\n\tbuffer: Uint8Array<ArrayBufferLike>\n): Uint8Array<ArrayBuffer> {\n\n\treturn buffer.buffer instanceof ArrayBuffer\n\t\t? buffer as Uint8Array<ArrayBuffer>\n\t\t: new Uint8Array(buffer)\n}\n"],"names":[],"mappings":"AAsCA;;;;;;;;;;;AAWG;AACG,SAAU,oBAAoB,CACnC,OAAoC,EACpC,OAAqC,EAAA;IAGrC,IAAI,aAAa,GAAwB,IAAI;IAC7C,IAAI,MAAM,GAAmC,IAAI;IAEjD,IAAI,cAAc,GAAyB,IAAI;AAC/C,IAAA,SAAS,OAAO,CACf,IAA4C,EAC5C,MAAgB,EAAA;AAGhB,QAAA,IAAI,cAAc,KAAK,IAAI,EAAE;AAC5B,YAAA,cAAc,GAAG,CAAC,YAAW;gBAC5B,MAAM,GAAG,IAAI;gBACb,IAAI,OAAO,EAAE,MAAM,IAAI,IAAI,IAAI,aAAa,IAAI,IAAI,EAAE;oBACrD,OAAO,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,aAAa,CAAC;oBAC1D,aAAa,GAAG,IAAI;gBACrB;AACA,gBAAA,IAAI,OAAO,CAAC,OAAO,IAAI,IAAI,EAAE;oBAC5B,MAAM,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;gBACpC;YACD,CAAC,GAAG;QACL;AACA,QAAA,OAAO,cAAc;IACtB;AAEA,IAAA,IAAI,CAAC,6BAA6B,EAAE,EAAE;QACrC,OAAO,IAAI,cAAc,CAAC;AAEzB,YAAA,KAAK,CAAC,UAAU,EAAA;AACf,gBAAA,IAAI,OAAO,EAAE,MAAM,IAAI,IAAI,EAAE;oBAC5B,aAAa,GAAG,MAAK;wBACpB,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,EAAE,MAAM,IAAI,0BAA0B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,EAAE,MAAM,IAAI,0BAA0B,EAAE;IACtD;AACD;AAEA,SAAS,0BAA0B,GAAA;AAClC,IAAA,OAAO,IAAI,YAAY,CAAC,4BAA4B,EAAE,YAAY,CAAC;AACpE;AAEA,SAAS,qBAAqB,CAAC,GAAY,EAAE,MAAsC,EAAA;AAClF,IAAA,OAAO,CAAC,MAAM,EAAE,OAAO,KAAK,IAAI;AAC/B,SAAC,GAAG,KAAK,MAAM,CAAC,MAAM,KAAK,GAAG,YAAY,YAAY,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC;AACvF;AAEA,SAAS,gBAAgB,CACxB,MAAmC,EAAA;AAGnC,IAAA,OAAO,MAAM,CAAC,MAAM,YAAY;AAC/B,UAAE;AACF,UAAE,IAAI,UAAU,CAAC,MAAM,CAAC;AAC1B;;;;"}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "create-web-stream",
3
+ "version": "1.0.0",
4
+ "author": "OkaYu",
5
+ "license": "(MIT OR Apache-2.0)",
6
+ "description": "Create Web Readable/Writable streams from simple handlers and options.",
7
+ "keywords": [
8
+ "web-streams",
9
+ "stream",
10
+ "readable-stream",
11
+ "writable-stream"
12
+ ],
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/aiueo13/create-web-stream.git"
16
+ },
17
+ "type": "module",
18
+ "main": "./dist/index.cjs",
19
+ "module": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js",
25
+ "require": "./dist/index.cjs"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "LICENSE-APACHE.txt",
32
+ "LICENSE-MIT.txt"
33
+ ],
34
+ "scripts": {
35
+ "build": "rollup -c",
36
+ "pretest": "pnpm build",
37
+ "prepublishOnly": "pnpm run build"
38
+ },
39
+ "devDependencies": {
40
+ "rollup": "^4.0.0",
41
+ "@rollup/plugin-typescript": "^12.0.0",
42
+ "tslib": "^2.0.0",
43
+ "typescript": "^5.0.0"
44
+ },
45
+ "engines": {
46
+ "node": ">=18.0.0"
47
+ },
48
+ "sideEffects": false
49
+ }