perstack 0.0.95 → 0.0.97

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,3886 @@
1
+ import { i as __require, n as __esmMin, o as __toESM, t as __commonJSMin } from "./chunk-D_gEzPfs.js";
2
+ import { createReadStream, promises, statSync } from "node:fs";
3
+
4
+ //#region ../../node_modules/.bun/web-streams-polyfill@3.3.3/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js
5
+ var require_ponyfill_es2018 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
6
+ /**
7
+ * @license
8
+ * web-streams-polyfill v3.3.3
9
+ * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
10
+ * This code is released under the MIT license.
11
+ * SPDX-License-Identifier: MIT
12
+ */
13
+ (function(global, factory) {
14
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.WebStreamsPolyfill = {}));
15
+ })(exports, (function(exports$1) {
16
+ "use strict";
17
+ function noop() {}
18
+ function typeIsObject(x) {
19
+ return typeof x === "object" && x !== null || typeof x === "function";
20
+ }
21
+ const rethrowAssertionErrorRejection = noop;
22
+ function setFunctionName(fn, name) {
23
+ try {
24
+ Object.defineProperty(fn, "name", {
25
+ value: name,
26
+ configurable: true
27
+ });
28
+ } catch (_a) {}
29
+ }
30
+ const originalPromise = Promise;
31
+ const originalPromiseThen = Promise.prototype.then;
32
+ const originalPromiseReject = Promise.reject.bind(originalPromise);
33
+ function newPromise(executor) {
34
+ return new originalPromise(executor);
35
+ }
36
+ function promiseResolvedWith(value) {
37
+ return newPromise((resolve) => resolve(value));
38
+ }
39
+ function promiseRejectedWith(reason) {
40
+ return originalPromiseReject(reason);
41
+ }
42
+ function PerformPromiseThen(promise, onFulfilled, onRejected) {
43
+ return originalPromiseThen.call(promise, onFulfilled, onRejected);
44
+ }
45
+ function uponPromise(promise, onFulfilled, onRejected) {
46
+ PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection);
47
+ }
48
+ function uponFulfillment(promise, onFulfilled) {
49
+ uponPromise(promise, onFulfilled);
50
+ }
51
+ function uponRejection(promise, onRejected) {
52
+ uponPromise(promise, void 0, onRejected);
53
+ }
54
+ function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
55
+ return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
56
+ }
57
+ function setPromiseIsHandledToTrue(promise) {
58
+ PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection);
59
+ }
60
+ let _queueMicrotask = (callback) => {
61
+ if (typeof queueMicrotask === "function") _queueMicrotask = queueMicrotask;
62
+ else {
63
+ const resolvedPromise = promiseResolvedWith(void 0);
64
+ _queueMicrotask = (cb) => PerformPromiseThen(resolvedPromise, cb);
65
+ }
66
+ return _queueMicrotask(callback);
67
+ };
68
+ function reflectCall(F, V, args) {
69
+ if (typeof F !== "function") throw new TypeError("Argument is not a function");
70
+ return Function.prototype.apply.call(F, V, args);
71
+ }
72
+ function promiseCall(F, V, args) {
73
+ try {
74
+ return promiseResolvedWith(reflectCall(F, V, args));
75
+ } catch (value) {
76
+ return promiseRejectedWith(value);
77
+ }
78
+ }
79
+ const QUEUE_MAX_ARRAY_SIZE = 16384;
80
+ /**
81
+ * Simple queue structure.
82
+ *
83
+ * Avoids scalability issues with using a packed array directly by using
84
+ * multiple arrays in a linked list and keeping the array size bounded.
85
+ */
86
+ class SimpleQueue {
87
+ constructor() {
88
+ this._cursor = 0;
89
+ this._size = 0;
90
+ this._front = {
91
+ _elements: [],
92
+ _next: void 0
93
+ };
94
+ this._back = this._front;
95
+ this._cursor = 0;
96
+ this._size = 0;
97
+ }
98
+ get length() {
99
+ return this._size;
100
+ }
101
+ push(element) {
102
+ const oldBack = this._back;
103
+ let newBack = oldBack;
104
+ if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) newBack = {
105
+ _elements: [],
106
+ _next: void 0
107
+ };
108
+ oldBack._elements.push(element);
109
+ if (newBack !== oldBack) {
110
+ this._back = newBack;
111
+ oldBack._next = newBack;
112
+ }
113
+ ++this._size;
114
+ }
115
+ shift() {
116
+ const oldFront = this._front;
117
+ let newFront = oldFront;
118
+ const oldCursor = this._cursor;
119
+ let newCursor = oldCursor + 1;
120
+ const elements = oldFront._elements;
121
+ const element = elements[oldCursor];
122
+ if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
123
+ newFront = oldFront._next;
124
+ newCursor = 0;
125
+ }
126
+ --this._size;
127
+ this._cursor = newCursor;
128
+ if (oldFront !== newFront) this._front = newFront;
129
+ elements[oldCursor] = void 0;
130
+ return element;
131
+ }
132
+ forEach(callback) {
133
+ let i = this._cursor;
134
+ let node = this._front;
135
+ let elements = node._elements;
136
+ while (i !== elements.length || node._next !== void 0) {
137
+ if (i === elements.length) {
138
+ node = node._next;
139
+ elements = node._elements;
140
+ i = 0;
141
+ if (elements.length === 0) break;
142
+ }
143
+ callback(elements[i]);
144
+ ++i;
145
+ }
146
+ }
147
+ peek() {
148
+ const front = this._front;
149
+ const cursor = this._cursor;
150
+ return front._elements[cursor];
151
+ }
152
+ }
153
+ const AbortSteps = Symbol("[[AbortSteps]]");
154
+ const ErrorSteps = Symbol("[[ErrorSteps]]");
155
+ const CancelSteps = Symbol("[[CancelSteps]]");
156
+ const PullSteps = Symbol("[[PullSteps]]");
157
+ const ReleaseSteps = Symbol("[[ReleaseSteps]]");
158
+ function ReadableStreamReaderGenericInitialize(reader, stream) {
159
+ reader._ownerReadableStream = stream;
160
+ stream._reader = reader;
161
+ if (stream._state === "readable") defaultReaderClosedPromiseInitialize(reader);
162
+ else if (stream._state === "closed") defaultReaderClosedPromiseInitializeAsResolved(reader);
163
+ else defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
164
+ }
165
+ function ReadableStreamReaderGenericCancel(reader, reason) {
166
+ const stream = reader._ownerReadableStream;
167
+ return ReadableStreamCancel(stream, reason);
168
+ }
169
+ function ReadableStreamReaderGenericRelease(reader) {
170
+ const stream = reader._ownerReadableStream;
171
+ if (stream._state === "readable") defaultReaderClosedPromiseReject(reader, /* @__PURE__ */ new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
172
+ else defaultReaderClosedPromiseResetToRejected(reader, /* @__PURE__ */ new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
173
+ stream._readableStreamController[ReleaseSteps]();
174
+ stream._reader = void 0;
175
+ reader._ownerReadableStream = void 0;
176
+ }
177
+ function readerLockException(name) {
178
+ return /* @__PURE__ */ new TypeError("Cannot " + name + " a stream using a released reader");
179
+ }
180
+ function defaultReaderClosedPromiseInitialize(reader) {
181
+ reader._closedPromise = newPromise((resolve, reject) => {
182
+ reader._closedPromise_resolve = resolve;
183
+ reader._closedPromise_reject = reject;
184
+ });
185
+ }
186
+ function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
187
+ defaultReaderClosedPromiseInitialize(reader);
188
+ defaultReaderClosedPromiseReject(reader, reason);
189
+ }
190
+ function defaultReaderClosedPromiseInitializeAsResolved(reader) {
191
+ defaultReaderClosedPromiseInitialize(reader);
192
+ defaultReaderClosedPromiseResolve(reader);
193
+ }
194
+ function defaultReaderClosedPromiseReject(reader, reason) {
195
+ if (reader._closedPromise_reject === void 0) return;
196
+ setPromiseIsHandledToTrue(reader._closedPromise);
197
+ reader._closedPromise_reject(reason);
198
+ reader._closedPromise_resolve = void 0;
199
+ reader._closedPromise_reject = void 0;
200
+ }
201
+ function defaultReaderClosedPromiseResetToRejected(reader, reason) {
202
+ defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
203
+ }
204
+ function defaultReaderClosedPromiseResolve(reader) {
205
+ if (reader._closedPromise_resolve === void 0) return;
206
+ reader._closedPromise_resolve(void 0);
207
+ reader._closedPromise_resolve = void 0;
208
+ reader._closedPromise_reject = void 0;
209
+ }
210
+ const NumberIsFinite = Number.isFinite || function(x) {
211
+ return typeof x === "number" && isFinite(x);
212
+ };
213
+ const MathTrunc = Math.trunc || function(v) {
214
+ return v < 0 ? Math.ceil(v) : Math.floor(v);
215
+ };
216
+ function isDictionary(x) {
217
+ return typeof x === "object" || typeof x === "function";
218
+ }
219
+ function assertDictionary(obj, context) {
220
+ if (obj !== void 0 && !isDictionary(obj)) throw new TypeError(`${context} is not an object.`);
221
+ }
222
+ function assertFunction(x, context) {
223
+ if (typeof x !== "function") throw new TypeError(`${context} is not a function.`);
224
+ }
225
+ function isObject(x) {
226
+ return typeof x === "object" && x !== null || typeof x === "function";
227
+ }
228
+ function assertObject(x, context) {
229
+ if (!isObject(x)) throw new TypeError(`${context} is not an object.`);
230
+ }
231
+ function assertRequiredArgument(x, position, context) {
232
+ if (x === void 0) throw new TypeError(`Parameter ${position} is required in '${context}'.`);
233
+ }
234
+ function assertRequiredField(x, field, context) {
235
+ if (x === void 0) throw new TypeError(`${field} is required in '${context}'.`);
236
+ }
237
+ function convertUnrestrictedDouble(value) {
238
+ return Number(value);
239
+ }
240
+ function censorNegativeZero(x) {
241
+ return x === 0 ? 0 : x;
242
+ }
243
+ function integerPart(x) {
244
+ return censorNegativeZero(MathTrunc(x));
245
+ }
246
+ function convertUnsignedLongLongWithEnforceRange(value, context) {
247
+ const lowerBound = 0;
248
+ const upperBound = Number.MAX_SAFE_INTEGER;
249
+ let x = Number(value);
250
+ x = censorNegativeZero(x);
251
+ if (!NumberIsFinite(x)) throw new TypeError(`${context} is not a finite number`);
252
+ x = integerPart(x);
253
+ if (x < lowerBound || x > upperBound) throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
254
+ if (!NumberIsFinite(x) || x === 0) return 0;
255
+ return x;
256
+ }
257
+ function assertReadableStream(x, context) {
258
+ if (!IsReadableStream(x)) throw new TypeError(`${context} is not a ReadableStream.`);
259
+ }
260
+ function AcquireReadableStreamDefaultReader(stream) {
261
+ return new ReadableStreamDefaultReader(stream);
262
+ }
263
+ function ReadableStreamAddReadRequest(stream, readRequest) {
264
+ stream._reader._readRequests.push(readRequest);
265
+ }
266
+ function ReadableStreamFulfillReadRequest(stream, chunk, done) {
267
+ const readRequest = stream._reader._readRequests.shift();
268
+ if (done) readRequest._closeSteps();
269
+ else readRequest._chunkSteps(chunk);
270
+ }
271
+ function ReadableStreamGetNumReadRequests(stream) {
272
+ return stream._reader._readRequests.length;
273
+ }
274
+ function ReadableStreamHasDefaultReader(stream) {
275
+ const reader = stream._reader;
276
+ if (reader === void 0) return false;
277
+ if (!IsReadableStreamDefaultReader(reader)) return false;
278
+ return true;
279
+ }
280
+ /**
281
+ * A default reader vended by a {@link ReadableStream}.
282
+ *
283
+ * @public
284
+ */
285
+ class ReadableStreamDefaultReader {
286
+ constructor(stream) {
287
+ assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader");
288
+ assertReadableStream(stream, "First parameter");
289
+ if (IsReadableStreamLocked(stream)) throw new TypeError("This stream has already been locked for exclusive reading by another reader");
290
+ ReadableStreamReaderGenericInitialize(this, stream);
291
+ this._readRequests = new SimpleQueue();
292
+ }
293
+ /**
294
+ * Returns a promise that will be fulfilled when the stream becomes closed,
295
+ * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
296
+ */
297
+ get closed() {
298
+ if (!IsReadableStreamDefaultReader(this)) return promiseRejectedWith(defaultReaderBrandCheckException("closed"));
299
+ return this._closedPromise;
300
+ }
301
+ /**
302
+ * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
303
+ */
304
+ cancel(reason = void 0) {
305
+ if (!IsReadableStreamDefaultReader(this)) return promiseRejectedWith(defaultReaderBrandCheckException("cancel"));
306
+ if (this._ownerReadableStream === void 0) return promiseRejectedWith(readerLockException("cancel"));
307
+ return ReadableStreamReaderGenericCancel(this, reason);
308
+ }
309
+ /**
310
+ * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
311
+ *
312
+ * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
313
+ */
314
+ read() {
315
+ if (!IsReadableStreamDefaultReader(this)) return promiseRejectedWith(defaultReaderBrandCheckException("read"));
316
+ if (this._ownerReadableStream === void 0) return promiseRejectedWith(readerLockException("read from"));
317
+ let resolvePromise;
318
+ let rejectPromise;
319
+ const promise = newPromise((resolve, reject) => {
320
+ resolvePromise = resolve;
321
+ rejectPromise = reject;
322
+ });
323
+ ReadableStreamDefaultReaderRead(this, {
324
+ _chunkSteps: (chunk) => resolvePromise({
325
+ value: chunk,
326
+ done: false
327
+ }),
328
+ _closeSteps: () => resolvePromise({
329
+ value: void 0,
330
+ done: true
331
+ }),
332
+ _errorSteps: (e) => rejectPromise(e)
333
+ });
334
+ return promise;
335
+ }
336
+ /**
337
+ * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
338
+ * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
339
+ * from now on; otherwise, the reader will appear closed.
340
+ *
341
+ * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
342
+ * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
343
+ * do so will throw a `TypeError` and leave the reader locked to the stream.
344
+ */
345
+ releaseLock() {
346
+ if (!IsReadableStreamDefaultReader(this)) throw defaultReaderBrandCheckException("releaseLock");
347
+ if (this._ownerReadableStream === void 0) return;
348
+ ReadableStreamDefaultReaderRelease(this);
349
+ }
350
+ }
351
+ Object.defineProperties(ReadableStreamDefaultReader.prototype, {
352
+ cancel: { enumerable: true },
353
+ read: { enumerable: true },
354
+ releaseLock: { enumerable: true },
355
+ closed: { enumerable: true }
356
+ });
357
+ setFunctionName(ReadableStreamDefaultReader.prototype.cancel, "cancel");
358
+ setFunctionName(ReadableStreamDefaultReader.prototype.read, "read");
359
+ setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, "releaseLock");
360
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {
361
+ value: "ReadableStreamDefaultReader",
362
+ configurable: true
363
+ });
364
+ function IsReadableStreamDefaultReader(x) {
365
+ if (!typeIsObject(x)) return false;
366
+ if (!Object.prototype.hasOwnProperty.call(x, "_readRequests")) return false;
367
+ return x instanceof ReadableStreamDefaultReader;
368
+ }
369
+ function ReadableStreamDefaultReaderRead(reader, readRequest) {
370
+ const stream = reader._ownerReadableStream;
371
+ stream._disturbed = true;
372
+ if (stream._state === "closed") readRequest._closeSteps();
373
+ else if (stream._state === "errored") readRequest._errorSteps(stream._storedError);
374
+ else stream._readableStreamController[PullSteps](readRequest);
375
+ }
376
+ function ReadableStreamDefaultReaderRelease(reader) {
377
+ ReadableStreamReaderGenericRelease(reader);
378
+ ReadableStreamDefaultReaderErrorReadRequests(reader, /* @__PURE__ */ new TypeError("Reader was released"));
379
+ }
380
+ function ReadableStreamDefaultReaderErrorReadRequests(reader, e) {
381
+ const readRequests = reader._readRequests;
382
+ reader._readRequests = new SimpleQueue();
383
+ readRequests.forEach((readRequest) => {
384
+ readRequest._errorSteps(e);
385
+ });
386
+ }
387
+ function defaultReaderBrandCheckException(name) {
388
+ return /* @__PURE__ */ new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
389
+ }
390
+ const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () {}).prototype);
391
+ class ReadableStreamAsyncIteratorImpl {
392
+ constructor(reader, preventCancel) {
393
+ this._ongoingPromise = void 0;
394
+ this._isFinished = false;
395
+ this._reader = reader;
396
+ this._preventCancel = preventCancel;
397
+ }
398
+ next() {
399
+ const nextSteps = () => this._nextSteps();
400
+ this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps();
401
+ return this._ongoingPromise;
402
+ }
403
+ return(value) {
404
+ const returnSteps = () => this._returnSteps(value);
405
+ return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps();
406
+ }
407
+ _nextSteps() {
408
+ if (this._isFinished) return Promise.resolve({
409
+ value: void 0,
410
+ done: true
411
+ });
412
+ const reader = this._reader;
413
+ let resolvePromise;
414
+ let rejectPromise;
415
+ const promise = newPromise((resolve, reject) => {
416
+ resolvePromise = resolve;
417
+ rejectPromise = reject;
418
+ });
419
+ ReadableStreamDefaultReaderRead(reader, {
420
+ _chunkSteps: (chunk) => {
421
+ this._ongoingPromise = void 0;
422
+ _queueMicrotask(() => resolvePromise({
423
+ value: chunk,
424
+ done: false
425
+ }));
426
+ },
427
+ _closeSteps: () => {
428
+ this._ongoingPromise = void 0;
429
+ this._isFinished = true;
430
+ ReadableStreamReaderGenericRelease(reader);
431
+ resolvePromise({
432
+ value: void 0,
433
+ done: true
434
+ });
435
+ },
436
+ _errorSteps: (reason) => {
437
+ this._ongoingPromise = void 0;
438
+ this._isFinished = true;
439
+ ReadableStreamReaderGenericRelease(reader);
440
+ rejectPromise(reason);
441
+ }
442
+ });
443
+ return promise;
444
+ }
445
+ _returnSteps(value) {
446
+ if (this._isFinished) return Promise.resolve({
447
+ value,
448
+ done: true
449
+ });
450
+ this._isFinished = true;
451
+ const reader = this._reader;
452
+ if (!this._preventCancel) {
453
+ const result = ReadableStreamReaderGenericCancel(reader, value);
454
+ ReadableStreamReaderGenericRelease(reader);
455
+ return transformPromiseWith(result, () => ({
456
+ value,
457
+ done: true
458
+ }));
459
+ }
460
+ ReadableStreamReaderGenericRelease(reader);
461
+ return promiseResolvedWith({
462
+ value,
463
+ done: true
464
+ });
465
+ }
466
+ }
467
+ const ReadableStreamAsyncIteratorPrototype = {
468
+ next() {
469
+ if (!IsReadableStreamAsyncIterator(this)) return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next"));
470
+ return this._asyncIteratorImpl.next();
471
+ },
472
+ return(value) {
473
+ if (!IsReadableStreamAsyncIterator(this)) return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return"));
474
+ return this._asyncIteratorImpl.return(value);
475
+ }
476
+ };
477
+ Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
478
+ function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
479
+ const impl = new ReadableStreamAsyncIteratorImpl(AcquireReadableStreamDefaultReader(stream), preventCancel);
480
+ const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
481
+ iterator._asyncIteratorImpl = impl;
482
+ return iterator;
483
+ }
484
+ function IsReadableStreamAsyncIterator(x) {
485
+ if (!typeIsObject(x)) return false;
486
+ if (!Object.prototype.hasOwnProperty.call(x, "_asyncIteratorImpl")) return false;
487
+ try {
488
+ return x._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl;
489
+ } catch (_a) {
490
+ return false;
491
+ }
492
+ }
493
+ function streamAsyncIteratorBrandCheckException(name) {
494
+ return /* @__PURE__ */ new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
495
+ }
496
+ const NumberIsNaN = Number.isNaN || function(x) {
497
+ return x !== x;
498
+ };
499
+ var _a, _b, _c;
500
+ function CreateArrayFromList(elements) {
501
+ return elements.slice();
502
+ }
503
+ function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
504
+ new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
505
+ }
506
+ let TransferArrayBuffer = (O) => {
507
+ if (typeof O.transfer === "function") TransferArrayBuffer = (buffer) => buffer.transfer();
508
+ else if (typeof structuredClone === "function") TransferArrayBuffer = (buffer) => structuredClone(buffer, { transfer: [buffer] });
509
+ else TransferArrayBuffer = (buffer) => buffer;
510
+ return TransferArrayBuffer(O);
511
+ };
512
+ let IsDetachedBuffer = (O) => {
513
+ if (typeof O.detached === "boolean") IsDetachedBuffer = (buffer) => buffer.detached;
514
+ else IsDetachedBuffer = (buffer) => buffer.byteLength === 0;
515
+ return IsDetachedBuffer(O);
516
+ };
517
+ function ArrayBufferSlice(buffer, begin, end) {
518
+ if (buffer.slice) return buffer.slice(begin, end);
519
+ const length = end - begin;
520
+ const slice = new ArrayBuffer(length);
521
+ CopyDataBlockBytes(slice, 0, buffer, begin, length);
522
+ return slice;
523
+ }
524
+ function GetMethod(receiver, prop) {
525
+ const func = receiver[prop];
526
+ if (func === void 0 || func === null) return;
527
+ if (typeof func !== "function") throw new TypeError(`${String(prop)} is not a function`);
528
+ return func;
529
+ }
530
+ function CreateAsyncFromSyncIterator(syncIteratorRecord) {
531
+ const syncIterable = { [Symbol.iterator]: () => syncIteratorRecord.iterator };
532
+ const asyncIterator = async function* () {
533
+ return yield* syncIterable;
534
+ }();
535
+ return {
536
+ iterator: asyncIterator,
537
+ nextMethod: asyncIterator.next,
538
+ done: false
539
+ };
540
+ }
541
+ const SymbolAsyncIterator = (_c = (_a = Symbol.asyncIterator) !== null && _a !== void 0 ? _a : (_b = Symbol.for) === null || _b === void 0 ? void 0 : _b.call(Symbol, "Symbol.asyncIterator")) !== null && _c !== void 0 ? _c : "@@asyncIterator";
542
+ function GetIterator(obj, hint = "sync", method) {
543
+ if (method === void 0) if (hint === "async") {
544
+ method = GetMethod(obj, SymbolAsyncIterator);
545
+ if (method === void 0) return CreateAsyncFromSyncIterator(GetIterator(obj, "sync", GetMethod(obj, Symbol.iterator)));
546
+ } else method = GetMethod(obj, Symbol.iterator);
547
+ if (method === void 0) throw new TypeError("The object is not iterable");
548
+ const iterator = reflectCall(method, obj, []);
549
+ if (!typeIsObject(iterator)) throw new TypeError("The iterator method must return an object");
550
+ return {
551
+ iterator,
552
+ nextMethod: iterator.next,
553
+ done: false
554
+ };
555
+ }
556
+ function IteratorNext(iteratorRecord) {
557
+ const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
558
+ if (!typeIsObject(result)) throw new TypeError("The iterator.next() method must return an object");
559
+ return result;
560
+ }
561
+ function IteratorComplete(iterResult) {
562
+ return Boolean(iterResult.done);
563
+ }
564
+ function IteratorValue(iterResult) {
565
+ return iterResult.value;
566
+ }
567
+ function IsNonNegativeNumber(v) {
568
+ if (typeof v !== "number") return false;
569
+ if (NumberIsNaN(v)) return false;
570
+ if (v < 0) return false;
571
+ return true;
572
+ }
573
+ function CloneAsUint8Array(O) {
574
+ const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);
575
+ return new Uint8Array(buffer);
576
+ }
577
+ function DequeueValue(container) {
578
+ const pair = container._queue.shift();
579
+ container._queueTotalSize -= pair.size;
580
+ if (container._queueTotalSize < 0) container._queueTotalSize = 0;
581
+ return pair.value;
582
+ }
583
+ function EnqueueValueWithSize(container, value, size) {
584
+ if (!IsNonNegativeNumber(size) || size === Infinity) throw new RangeError("Size must be a finite, non-NaN, non-negative number.");
585
+ container._queue.push({
586
+ value,
587
+ size
588
+ });
589
+ container._queueTotalSize += size;
590
+ }
591
+ function PeekQueueValue(container) {
592
+ return container._queue.peek().value;
593
+ }
594
+ function ResetQueue(container) {
595
+ container._queue = new SimpleQueue();
596
+ container._queueTotalSize = 0;
597
+ }
598
+ function isDataViewConstructor(ctor) {
599
+ return ctor === DataView;
600
+ }
601
+ function isDataView(view) {
602
+ return isDataViewConstructor(view.constructor);
603
+ }
604
+ function arrayBufferViewElementSize(ctor) {
605
+ if (isDataViewConstructor(ctor)) return 1;
606
+ return ctor.BYTES_PER_ELEMENT;
607
+ }
608
+ /**
609
+ * A pull-into request in a {@link ReadableByteStreamController}.
610
+ *
611
+ * @public
612
+ */
613
+ class ReadableStreamBYOBRequest {
614
+ constructor() {
615
+ throw new TypeError("Illegal constructor");
616
+ }
617
+ /**
618
+ * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
619
+ */
620
+ get view() {
621
+ if (!IsReadableStreamBYOBRequest(this)) throw byobRequestBrandCheckException("view");
622
+ return this._view;
623
+ }
624
+ respond(bytesWritten) {
625
+ if (!IsReadableStreamBYOBRequest(this)) throw byobRequestBrandCheckException("respond");
626
+ assertRequiredArgument(bytesWritten, 1, "respond");
627
+ bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter");
628
+ if (this._associatedReadableByteStreamController === void 0) throw new TypeError("This BYOB request has been invalidated");
629
+ if (IsDetachedBuffer(this._view.buffer)) throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
630
+ ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
631
+ }
632
+ respondWithNewView(view) {
633
+ if (!IsReadableStreamBYOBRequest(this)) throw byobRequestBrandCheckException("respondWithNewView");
634
+ assertRequiredArgument(view, 1, "respondWithNewView");
635
+ if (!ArrayBuffer.isView(view)) throw new TypeError("You can only respond with array buffer views");
636
+ if (this._associatedReadableByteStreamController === void 0) throw new TypeError("This BYOB request has been invalidated");
637
+ if (IsDetachedBuffer(view.buffer)) throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");
638
+ ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
639
+ }
640
+ }
641
+ Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
642
+ respond: { enumerable: true },
643
+ respondWithNewView: { enumerable: true },
644
+ view: { enumerable: true }
645
+ });
646
+ setFunctionName(ReadableStreamBYOBRequest.prototype.respond, "respond");
647
+ setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, "respondWithNewView");
648
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {
649
+ value: "ReadableStreamBYOBRequest",
650
+ configurable: true
651
+ });
652
+ /**
653
+ * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
654
+ *
655
+ * @public
656
+ */
657
+ class ReadableByteStreamController {
658
+ constructor() {
659
+ throw new TypeError("Illegal constructor");
660
+ }
661
+ /**
662
+ * Returns the current BYOB pull request, or `null` if there isn't one.
663
+ */
664
+ get byobRequest() {
665
+ if (!IsReadableByteStreamController(this)) throw byteStreamControllerBrandCheckException("byobRequest");
666
+ return ReadableByteStreamControllerGetBYOBRequest(this);
667
+ }
668
+ /**
669
+ * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
670
+ * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
671
+ */
672
+ get desiredSize() {
673
+ if (!IsReadableByteStreamController(this)) throw byteStreamControllerBrandCheckException("desiredSize");
674
+ return ReadableByteStreamControllerGetDesiredSize(this);
675
+ }
676
+ /**
677
+ * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
678
+ * the stream, but once those are read, the stream will become closed.
679
+ */
680
+ close() {
681
+ if (!IsReadableByteStreamController(this)) throw byteStreamControllerBrandCheckException("close");
682
+ if (this._closeRequested) throw new TypeError("The stream has already been closed; do not close it again!");
683
+ const state = this._controlledReadableByteStream._state;
684
+ if (state !== "readable") throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
685
+ ReadableByteStreamControllerClose(this);
686
+ }
687
+ enqueue(chunk) {
688
+ if (!IsReadableByteStreamController(this)) throw byteStreamControllerBrandCheckException("enqueue");
689
+ assertRequiredArgument(chunk, 1, "enqueue");
690
+ if (!ArrayBuffer.isView(chunk)) throw new TypeError("chunk must be an array buffer view");
691
+ if (chunk.byteLength === 0) throw new TypeError("chunk must have non-zero byteLength");
692
+ if (chunk.buffer.byteLength === 0) throw new TypeError(`chunk's buffer must have non-zero byteLength`);
693
+ if (this._closeRequested) throw new TypeError("stream is closed or draining");
694
+ const state = this._controlledReadableByteStream._state;
695
+ if (state !== "readable") throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
696
+ ReadableByteStreamControllerEnqueue(this, chunk);
697
+ }
698
+ /**
699
+ * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
700
+ */
701
+ error(e = void 0) {
702
+ if (!IsReadableByteStreamController(this)) throw byteStreamControllerBrandCheckException("error");
703
+ ReadableByteStreamControllerError(this, e);
704
+ }
705
+ /** @internal */
706
+ [CancelSteps](reason) {
707
+ ReadableByteStreamControllerClearPendingPullIntos(this);
708
+ ResetQueue(this);
709
+ const result = this._cancelAlgorithm(reason);
710
+ ReadableByteStreamControllerClearAlgorithms(this);
711
+ return result;
712
+ }
713
+ /** @internal */
714
+ [PullSteps](readRequest) {
715
+ const stream = this._controlledReadableByteStream;
716
+ if (this._queueTotalSize > 0) {
717
+ ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
718
+ return;
719
+ }
720
+ const autoAllocateChunkSize = this._autoAllocateChunkSize;
721
+ if (autoAllocateChunkSize !== void 0) {
722
+ let buffer;
723
+ try {
724
+ buffer = new ArrayBuffer(autoAllocateChunkSize);
725
+ } catch (bufferE) {
726
+ readRequest._errorSteps(bufferE);
727
+ return;
728
+ }
729
+ const pullIntoDescriptor = {
730
+ buffer,
731
+ bufferByteLength: autoAllocateChunkSize,
732
+ byteOffset: 0,
733
+ byteLength: autoAllocateChunkSize,
734
+ bytesFilled: 0,
735
+ minimumFill: 1,
736
+ elementSize: 1,
737
+ viewConstructor: Uint8Array,
738
+ readerType: "default"
739
+ };
740
+ this._pendingPullIntos.push(pullIntoDescriptor);
741
+ }
742
+ ReadableStreamAddReadRequest(stream, readRequest);
743
+ ReadableByteStreamControllerCallPullIfNeeded(this);
744
+ }
745
+ /** @internal */
746
+ [ReleaseSteps]() {
747
+ if (this._pendingPullIntos.length > 0) {
748
+ const firstPullInto = this._pendingPullIntos.peek();
749
+ firstPullInto.readerType = "none";
750
+ this._pendingPullIntos = new SimpleQueue();
751
+ this._pendingPullIntos.push(firstPullInto);
752
+ }
753
+ }
754
+ }
755
+ Object.defineProperties(ReadableByteStreamController.prototype, {
756
+ close: { enumerable: true },
757
+ enqueue: { enumerable: true },
758
+ error: { enumerable: true },
759
+ byobRequest: { enumerable: true },
760
+ desiredSize: { enumerable: true }
761
+ });
762
+ setFunctionName(ReadableByteStreamController.prototype.close, "close");
763
+ setFunctionName(ReadableByteStreamController.prototype.enqueue, "enqueue");
764
+ setFunctionName(ReadableByteStreamController.prototype.error, "error");
765
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {
766
+ value: "ReadableByteStreamController",
767
+ configurable: true
768
+ });
769
+ function IsReadableByteStreamController(x) {
770
+ if (!typeIsObject(x)) return false;
771
+ if (!Object.prototype.hasOwnProperty.call(x, "_controlledReadableByteStream")) return false;
772
+ return x instanceof ReadableByteStreamController;
773
+ }
774
+ function IsReadableStreamBYOBRequest(x) {
775
+ if (!typeIsObject(x)) return false;
776
+ if (!Object.prototype.hasOwnProperty.call(x, "_associatedReadableByteStreamController")) return false;
777
+ return x instanceof ReadableStreamBYOBRequest;
778
+ }
779
+ function ReadableByteStreamControllerCallPullIfNeeded(controller) {
780
+ if (!ReadableByteStreamControllerShouldCallPull(controller)) return;
781
+ if (controller._pulling) {
782
+ controller._pullAgain = true;
783
+ return;
784
+ }
785
+ controller._pulling = true;
786
+ uponPromise(controller._pullAlgorithm(), () => {
787
+ controller._pulling = false;
788
+ if (controller._pullAgain) {
789
+ controller._pullAgain = false;
790
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
791
+ }
792
+ return null;
793
+ }, (e) => {
794
+ ReadableByteStreamControllerError(controller, e);
795
+ return null;
796
+ });
797
+ }
798
+ function ReadableByteStreamControllerClearPendingPullIntos(controller) {
799
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
800
+ controller._pendingPullIntos = new SimpleQueue();
801
+ }
802
+ function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
803
+ let done = false;
804
+ if (stream._state === "closed") done = true;
805
+ const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
806
+ if (pullIntoDescriptor.readerType === "default") ReadableStreamFulfillReadRequest(stream, filledView, done);
807
+ else ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
808
+ }
809
+ function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
810
+ const bytesFilled = pullIntoDescriptor.bytesFilled;
811
+ const elementSize = pullIntoDescriptor.elementSize;
812
+ return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
813
+ }
814
+ function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
815
+ controller._queue.push({
816
+ buffer,
817
+ byteOffset,
818
+ byteLength
819
+ });
820
+ controller._queueTotalSize += byteLength;
821
+ }
822
+ function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
823
+ let clonedChunk;
824
+ try {
825
+ clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
826
+ } catch (cloneE) {
827
+ ReadableByteStreamControllerError(controller, cloneE);
828
+ throw cloneE;
829
+ }
830
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
831
+ }
832
+ function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
833
+ if (firstDescriptor.bytesFilled > 0) ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
834
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
835
+ }
836
+ function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
837
+ const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
838
+ const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
839
+ let totalBytesToCopyRemaining = maxBytesToCopy;
840
+ let ready = false;
841
+ const maxAlignedBytes = maxBytesFilled - maxBytesFilled % pullIntoDescriptor.elementSize;
842
+ if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
843
+ totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
844
+ ready = true;
845
+ }
846
+ const queue = controller._queue;
847
+ while (totalBytesToCopyRemaining > 0) {
848
+ const headOfQueue = queue.peek();
849
+ const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
850
+ const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
851
+ CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
852
+ if (headOfQueue.byteLength === bytesToCopy) queue.shift();
853
+ else {
854
+ headOfQueue.byteOffset += bytesToCopy;
855
+ headOfQueue.byteLength -= bytesToCopy;
856
+ }
857
+ controller._queueTotalSize -= bytesToCopy;
858
+ ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
859
+ totalBytesToCopyRemaining -= bytesToCopy;
860
+ }
861
+ return ready;
862
+ }
863
+ function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
864
+ pullIntoDescriptor.bytesFilled += size;
865
+ }
866
+ function ReadableByteStreamControllerHandleQueueDrain(controller) {
867
+ if (controller._queueTotalSize === 0 && controller._closeRequested) {
868
+ ReadableByteStreamControllerClearAlgorithms(controller);
869
+ ReadableStreamClose(controller._controlledReadableByteStream);
870
+ } else ReadableByteStreamControllerCallPullIfNeeded(controller);
871
+ }
872
+ function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
873
+ if (controller._byobRequest === null) return;
874
+ controller._byobRequest._associatedReadableByteStreamController = void 0;
875
+ controller._byobRequest._view = null;
876
+ controller._byobRequest = null;
877
+ }
878
+ function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
879
+ while (controller._pendingPullIntos.length > 0) {
880
+ if (controller._queueTotalSize === 0) return;
881
+ const pullIntoDescriptor = controller._pendingPullIntos.peek();
882
+ if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
883
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
884
+ ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
885
+ }
886
+ }
887
+ }
888
+ function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
889
+ const reader = controller._controlledReadableByteStream._reader;
890
+ while (reader._readRequests.length > 0) {
891
+ if (controller._queueTotalSize === 0) return;
892
+ ReadableByteStreamControllerFillReadRequestFromQueue(controller, reader._readRequests.shift());
893
+ }
894
+ }
895
+ function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) {
896
+ const stream = controller._controlledReadableByteStream;
897
+ const ctor = view.constructor;
898
+ const elementSize = arrayBufferViewElementSize(ctor);
899
+ const { byteOffset, byteLength } = view;
900
+ const minimumFill = min * elementSize;
901
+ let buffer;
902
+ try {
903
+ buffer = TransferArrayBuffer(view.buffer);
904
+ } catch (e) {
905
+ readIntoRequest._errorSteps(e);
906
+ return;
907
+ }
908
+ const pullIntoDescriptor = {
909
+ buffer,
910
+ bufferByteLength: buffer.byteLength,
911
+ byteOffset,
912
+ byteLength,
913
+ bytesFilled: 0,
914
+ minimumFill,
915
+ elementSize,
916
+ viewConstructor: ctor,
917
+ readerType: "byob"
918
+ };
919
+ if (controller._pendingPullIntos.length > 0) {
920
+ controller._pendingPullIntos.push(pullIntoDescriptor);
921
+ ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
922
+ return;
923
+ }
924
+ if (stream._state === "closed") {
925
+ const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
926
+ readIntoRequest._closeSteps(emptyView);
927
+ return;
928
+ }
929
+ if (controller._queueTotalSize > 0) {
930
+ if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
931
+ const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
932
+ ReadableByteStreamControllerHandleQueueDrain(controller);
933
+ readIntoRequest._chunkSteps(filledView);
934
+ return;
935
+ }
936
+ if (controller._closeRequested) {
937
+ const e = /* @__PURE__ */ new TypeError("Insufficient bytes to fill elements in the given buffer");
938
+ ReadableByteStreamControllerError(controller, e);
939
+ readIntoRequest._errorSteps(e);
940
+ return;
941
+ }
942
+ }
943
+ controller._pendingPullIntos.push(pullIntoDescriptor);
944
+ ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
945
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
946
+ }
947
+ function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
948
+ if (firstDescriptor.readerType === "none") ReadableByteStreamControllerShiftPendingPullInto(controller);
949
+ const stream = controller._controlledReadableByteStream;
950
+ if (ReadableStreamHasBYOBReader(stream)) while (ReadableStreamGetNumReadIntoRequests(stream) > 0) ReadableByteStreamControllerCommitPullIntoDescriptor(stream, ReadableByteStreamControllerShiftPendingPullInto(controller));
951
+ }
952
+ function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
953
+ ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
954
+ if (pullIntoDescriptor.readerType === "none") {
955
+ ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
956
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
957
+ return;
958
+ }
959
+ if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) return;
960
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
961
+ const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
962
+ if (remainderSize > 0) {
963
+ const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
964
+ ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
965
+ }
966
+ pullIntoDescriptor.bytesFilled -= remainderSize;
967
+ ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
968
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
969
+ }
970
+ function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
971
+ const firstDescriptor = controller._pendingPullIntos.peek();
972
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
973
+ if (controller._controlledReadableByteStream._state === "closed") ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
974
+ else ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
975
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
976
+ }
977
+ function ReadableByteStreamControllerShiftPendingPullInto(controller) {
978
+ return controller._pendingPullIntos.shift();
979
+ }
980
+ function ReadableByteStreamControllerShouldCallPull(controller) {
981
+ const stream = controller._controlledReadableByteStream;
982
+ if (stream._state !== "readable") return false;
983
+ if (controller._closeRequested) return false;
984
+ if (!controller._started) return false;
985
+ if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) return true;
986
+ if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) return true;
987
+ if (ReadableByteStreamControllerGetDesiredSize(controller) > 0) return true;
988
+ return false;
989
+ }
990
+ function ReadableByteStreamControllerClearAlgorithms(controller) {
991
+ controller._pullAlgorithm = void 0;
992
+ controller._cancelAlgorithm = void 0;
993
+ }
994
+ function ReadableByteStreamControllerClose(controller) {
995
+ const stream = controller._controlledReadableByteStream;
996
+ if (controller._closeRequested || stream._state !== "readable") return;
997
+ if (controller._queueTotalSize > 0) {
998
+ controller._closeRequested = true;
999
+ return;
1000
+ }
1001
+ if (controller._pendingPullIntos.length > 0) {
1002
+ const firstPendingPullInto = controller._pendingPullIntos.peek();
1003
+ if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
1004
+ const e = /* @__PURE__ */ new TypeError("Insufficient bytes to fill elements in the given buffer");
1005
+ ReadableByteStreamControllerError(controller, e);
1006
+ throw e;
1007
+ }
1008
+ }
1009
+ ReadableByteStreamControllerClearAlgorithms(controller);
1010
+ ReadableStreamClose(stream);
1011
+ }
1012
+ function ReadableByteStreamControllerEnqueue(controller, chunk) {
1013
+ const stream = controller._controlledReadableByteStream;
1014
+ if (controller._closeRequested || stream._state !== "readable") return;
1015
+ const { buffer, byteOffset, byteLength } = chunk;
1016
+ if (IsDetachedBuffer(buffer)) throw new TypeError("chunk's buffer is detached and so cannot be enqueued");
1017
+ const transferredBuffer = TransferArrayBuffer(buffer);
1018
+ if (controller._pendingPullIntos.length > 0) {
1019
+ const firstPendingPullInto = controller._pendingPullIntos.peek();
1020
+ if (IsDetachedBuffer(firstPendingPullInto.buffer)) throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");
1021
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1022
+ firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
1023
+ if (firstPendingPullInto.readerType === "none") ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
1024
+ }
1025
+ if (ReadableStreamHasDefaultReader(stream)) {
1026
+ ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
1027
+ if (ReadableStreamGetNumReadRequests(stream) === 0) ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1028
+ else {
1029
+ if (controller._pendingPullIntos.length > 0) ReadableByteStreamControllerShiftPendingPullInto(controller);
1030
+ ReadableStreamFulfillReadRequest(stream, new Uint8Array(transferredBuffer, byteOffset, byteLength), false);
1031
+ }
1032
+ } else if (ReadableStreamHasBYOBReader(stream)) {
1033
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1034
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1035
+ } else ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1036
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
1037
+ }
1038
+ function ReadableByteStreamControllerError(controller, e) {
1039
+ const stream = controller._controlledReadableByteStream;
1040
+ if (stream._state !== "readable") return;
1041
+ ReadableByteStreamControllerClearPendingPullIntos(controller);
1042
+ ResetQueue(controller);
1043
+ ReadableByteStreamControllerClearAlgorithms(controller);
1044
+ ReadableStreamError(stream, e);
1045
+ }
1046
+ function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
1047
+ const entry = controller._queue.shift();
1048
+ controller._queueTotalSize -= entry.byteLength;
1049
+ ReadableByteStreamControllerHandleQueueDrain(controller);
1050
+ const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
1051
+ readRequest._chunkSteps(view);
1052
+ }
1053
+ function ReadableByteStreamControllerGetBYOBRequest(controller) {
1054
+ if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
1055
+ const firstDescriptor = controller._pendingPullIntos.peek();
1056
+ const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
1057
+ const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
1058
+ SetUpReadableStreamBYOBRequest(byobRequest, controller, view);
1059
+ controller._byobRequest = byobRequest;
1060
+ }
1061
+ return controller._byobRequest;
1062
+ }
1063
+ function ReadableByteStreamControllerGetDesiredSize(controller) {
1064
+ const state = controller._controlledReadableByteStream._state;
1065
+ if (state === "errored") return null;
1066
+ if (state === "closed") return 0;
1067
+ return controller._strategyHWM - controller._queueTotalSize;
1068
+ }
1069
+ function ReadableByteStreamControllerRespond(controller, bytesWritten) {
1070
+ const firstDescriptor = controller._pendingPullIntos.peek();
1071
+ if (controller._controlledReadableByteStream._state === "closed") {
1072
+ if (bytesWritten !== 0) throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");
1073
+ } else {
1074
+ if (bytesWritten === 0) throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");
1075
+ if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) throw new RangeError("bytesWritten out of range");
1076
+ }
1077
+ firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
1078
+ ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
1079
+ }
1080
+ function ReadableByteStreamControllerRespondWithNewView(controller, view) {
1081
+ const firstDescriptor = controller._pendingPullIntos.peek();
1082
+ if (controller._controlledReadableByteStream._state === "closed") {
1083
+ if (view.byteLength !== 0) throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream");
1084
+ } else if (view.byteLength === 0) throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");
1085
+ if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) throw new RangeError("The region specified by view does not match byobRequest");
1086
+ if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) throw new RangeError("The buffer of view has different capacity than byobRequest");
1087
+ if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) throw new RangeError("The region specified by view is larger than byobRequest");
1088
+ const viewByteLength = view.byteLength;
1089
+ firstDescriptor.buffer = TransferArrayBuffer(view.buffer);
1090
+ ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
1091
+ }
1092
+ function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
1093
+ controller._controlledReadableByteStream = stream;
1094
+ controller._pullAgain = false;
1095
+ controller._pulling = false;
1096
+ controller._byobRequest = null;
1097
+ controller._queue = controller._queueTotalSize = void 0;
1098
+ ResetQueue(controller);
1099
+ controller._closeRequested = false;
1100
+ controller._started = false;
1101
+ controller._strategyHWM = highWaterMark;
1102
+ controller._pullAlgorithm = pullAlgorithm;
1103
+ controller._cancelAlgorithm = cancelAlgorithm;
1104
+ controller._autoAllocateChunkSize = autoAllocateChunkSize;
1105
+ controller._pendingPullIntos = new SimpleQueue();
1106
+ stream._readableStreamController = controller;
1107
+ uponPromise(promiseResolvedWith(startAlgorithm()), () => {
1108
+ controller._started = true;
1109
+ ReadableByteStreamControllerCallPullIfNeeded(controller);
1110
+ return null;
1111
+ }, (r) => {
1112
+ ReadableByteStreamControllerError(controller, r);
1113
+ return null;
1114
+ });
1115
+ }
1116
+ function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
1117
+ const controller = Object.create(ReadableByteStreamController.prototype);
1118
+ let startAlgorithm;
1119
+ let pullAlgorithm;
1120
+ let cancelAlgorithm;
1121
+ if (underlyingByteSource.start !== void 0) startAlgorithm = () => underlyingByteSource.start(controller);
1122
+ else startAlgorithm = () => void 0;
1123
+ if (underlyingByteSource.pull !== void 0) pullAlgorithm = () => underlyingByteSource.pull(controller);
1124
+ else pullAlgorithm = () => promiseResolvedWith(void 0);
1125
+ if (underlyingByteSource.cancel !== void 0) cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason);
1126
+ else cancelAlgorithm = () => promiseResolvedWith(void 0);
1127
+ const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
1128
+ if (autoAllocateChunkSize === 0) throw new TypeError("autoAllocateChunkSize must be greater than 0");
1129
+ SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
1130
+ }
1131
+ function SetUpReadableStreamBYOBRequest(request, controller, view) {
1132
+ request._associatedReadableByteStreamController = controller;
1133
+ request._view = view;
1134
+ }
1135
+ function byobRequestBrandCheckException(name) {
1136
+ return /* @__PURE__ */ new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
1137
+ }
1138
+ function byteStreamControllerBrandCheckException(name) {
1139
+ return /* @__PURE__ */ new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
1140
+ }
1141
+ function convertReaderOptions(options, context) {
1142
+ assertDictionary(options, context);
1143
+ const mode = options === null || options === void 0 ? void 0 : options.mode;
1144
+ return { mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) };
1145
+ }
1146
+ function convertReadableStreamReaderMode(mode, context) {
1147
+ mode = `${mode}`;
1148
+ if (mode !== "byob") throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
1149
+ return mode;
1150
+ }
1151
+ function convertByobReadOptions(options, context) {
1152
+ var _a;
1153
+ assertDictionary(options, context);
1154
+ return { min: convertUnsignedLongLongWithEnforceRange((_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1, `${context} has member 'min' that`) };
1155
+ }
1156
+ function AcquireReadableStreamBYOBReader(stream) {
1157
+ return new ReadableStreamBYOBReader(stream);
1158
+ }
1159
+ function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
1160
+ stream._reader._readIntoRequests.push(readIntoRequest);
1161
+ }
1162
+ function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
1163
+ const readIntoRequest = stream._reader._readIntoRequests.shift();
1164
+ if (done) readIntoRequest._closeSteps(chunk);
1165
+ else readIntoRequest._chunkSteps(chunk);
1166
+ }
1167
+ function ReadableStreamGetNumReadIntoRequests(stream) {
1168
+ return stream._reader._readIntoRequests.length;
1169
+ }
1170
+ function ReadableStreamHasBYOBReader(stream) {
1171
+ const reader = stream._reader;
1172
+ if (reader === void 0) return false;
1173
+ if (!IsReadableStreamBYOBReader(reader)) return false;
1174
+ return true;
1175
+ }
1176
+ /**
1177
+ * A BYOB reader vended by a {@link ReadableStream}.
1178
+ *
1179
+ * @public
1180
+ */
1181
+ class ReadableStreamBYOBReader {
1182
+ constructor(stream) {
1183
+ assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader");
1184
+ assertReadableStream(stream, "First parameter");
1185
+ if (IsReadableStreamLocked(stream)) throw new TypeError("This stream has already been locked for exclusive reading by another reader");
1186
+ if (!IsReadableByteStreamController(stream._readableStreamController)) throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");
1187
+ ReadableStreamReaderGenericInitialize(this, stream);
1188
+ this._readIntoRequests = new SimpleQueue();
1189
+ }
1190
+ /**
1191
+ * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
1192
+ * the reader's lock is released before the stream finishes closing.
1193
+ */
1194
+ get closed() {
1195
+ if (!IsReadableStreamBYOBReader(this)) return promiseRejectedWith(byobReaderBrandCheckException("closed"));
1196
+ return this._closedPromise;
1197
+ }
1198
+ /**
1199
+ * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
1200
+ */
1201
+ cancel(reason = void 0) {
1202
+ if (!IsReadableStreamBYOBReader(this)) return promiseRejectedWith(byobReaderBrandCheckException("cancel"));
1203
+ if (this._ownerReadableStream === void 0) return promiseRejectedWith(readerLockException("cancel"));
1204
+ return ReadableStreamReaderGenericCancel(this, reason);
1205
+ }
1206
+ read(view, rawOptions = {}) {
1207
+ if (!IsReadableStreamBYOBReader(this)) return promiseRejectedWith(byobReaderBrandCheckException("read"));
1208
+ if (!ArrayBuffer.isView(view)) return promiseRejectedWith(/* @__PURE__ */ new TypeError("view must be an array buffer view"));
1209
+ if (view.byteLength === 0) return promiseRejectedWith(/* @__PURE__ */ new TypeError("view must have non-zero byteLength"));
1210
+ if (view.buffer.byteLength === 0) return promiseRejectedWith(/* @__PURE__ */ new TypeError(`view's buffer must have non-zero byteLength`));
1211
+ if (IsDetachedBuffer(view.buffer)) return promiseRejectedWith(/* @__PURE__ */ new TypeError("view's buffer has been detached"));
1212
+ let options;
1213
+ try {
1214
+ options = convertByobReadOptions(rawOptions, "options");
1215
+ } catch (e) {
1216
+ return promiseRejectedWith(e);
1217
+ }
1218
+ const min = options.min;
1219
+ if (min === 0) return promiseRejectedWith(/* @__PURE__ */ new TypeError("options.min must be greater than 0"));
1220
+ if (!isDataView(view)) {
1221
+ if (min > view.length) return promiseRejectedWith(/* @__PURE__ */ new RangeError("options.min must be less than or equal to view's length"));
1222
+ } else if (min > view.byteLength) return promiseRejectedWith(/* @__PURE__ */ new RangeError("options.min must be less than or equal to view's byteLength"));
1223
+ if (this._ownerReadableStream === void 0) return promiseRejectedWith(readerLockException("read from"));
1224
+ let resolvePromise;
1225
+ let rejectPromise;
1226
+ const promise = newPromise((resolve, reject) => {
1227
+ resolvePromise = resolve;
1228
+ rejectPromise = reject;
1229
+ });
1230
+ ReadableStreamBYOBReaderRead(this, view, min, {
1231
+ _chunkSteps: (chunk) => resolvePromise({
1232
+ value: chunk,
1233
+ done: false
1234
+ }),
1235
+ _closeSteps: (chunk) => resolvePromise({
1236
+ value: chunk,
1237
+ done: true
1238
+ }),
1239
+ _errorSteps: (e) => rejectPromise(e)
1240
+ });
1241
+ return promise;
1242
+ }
1243
+ /**
1244
+ * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
1245
+ * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
1246
+ * from now on; otherwise, the reader will appear closed.
1247
+ *
1248
+ * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
1249
+ * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
1250
+ * do so will throw a `TypeError` and leave the reader locked to the stream.
1251
+ */
1252
+ releaseLock() {
1253
+ if (!IsReadableStreamBYOBReader(this)) throw byobReaderBrandCheckException("releaseLock");
1254
+ if (this._ownerReadableStream === void 0) return;
1255
+ ReadableStreamBYOBReaderRelease(this);
1256
+ }
1257
+ }
1258
+ Object.defineProperties(ReadableStreamBYOBReader.prototype, {
1259
+ cancel: { enumerable: true },
1260
+ read: { enumerable: true },
1261
+ releaseLock: { enumerable: true },
1262
+ closed: { enumerable: true }
1263
+ });
1264
+ setFunctionName(ReadableStreamBYOBReader.prototype.cancel, "cancel");
1265
+ setFunctionName(ReadableStreamBYOBReader.prototype.read, "read");
1266
+ setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, "releaseLock");
1267
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {
1268
+ value: "ReadableStreamBYOBReader",
1269
+ configurable: true
1270
+ });
1271
+ function IsReadableStreamBYOBReader(x) {
1272
+ if (!typeIsObject(x)) return false;
1273
+ if (!Object.prototype.hasOwnProperty.call(x, "_readIntoRequests")) return false;
1274
+ return x instanceof ReadableStreamBYOBReader;
1275
+ }
1276
+ function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) {
1277
+ const stream = reader._ownerReadableStream;
1278
+ stream._disturbed = true;
1279
+ if (stream._state === "errored") readIntoRequest._errorSteps(stream._storedError);
1280
+ else ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest);
1281
+ }
1282
+ function ReadableStreamBYOBReaderRelease(reader) {
1283
+ ReadableStreamReaderGenericRelease(reader);
1284
+ ReadableStreamBYOBReaderErrorReadIntoRequests(reader, /* @__PURE__ */ new TypeError("Reader was released"));
1285
+ }
1286
+ function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) {
1287
+ const readIntoRequests = reader._readIntoRequests;
1288
+ reader._readIntoRequests = new SimpleQueue();
1289
+ readIntoRequests.forEach((readIntoRequest) => {
1290
+ readIntoRequest._errorSteps(e);
1291
+ });
1292
+ }
1293
+ function byobReaderBrandCheckException(name) {
1294
+ return /* @__PURE__ */ new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
1295
+ }
1296
+ function ExtractHighWaterMark(strategy, defaultHWM) {
1297
+ const { highWaterMark } = strategy;
1298
+ if (highWaterMark === void 0) return defaultHWM;
1299
+ if (NumberIsNaN(highWaterMark) || highWaterMark < 0) throw new RangeError("Invalid highWaterMark");
1300
+ return highWaterMark;
1301
+ }
1302
+ function ExtractSizeAlgorithm(strategy) {
1303
+ const { size } = strategy;
1304
+ if (!size) return () => 1;
1305
+ return size;
1306
+ }
1307
+ function convertQueuingStrategy(init, context) {
1308
+ assertDictionary(init, context);
1309
+ const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
1310
+ const size = init === null || init === void 0 ? void 0 : init.size;
1311
+ return {
1312
+ highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark),
1313
+ size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${context} has member 'size' that`)
1314
+ };
1315
+ }
1316
+ function convertQueuingStrategySize(fn, context) {
1317
+ assertFunction(fn, context);
1318
+ return (chunk) => convertUnrestrictedDouble(fn(chunk));
1319
+ }
1320
+ function convertUnderlyingSink(original, context) {
1321
+ assertDictionary(original, context);
1322
+ const abort = original === null || original === void 0 ? void 0 : original.abort;
1323
+ const close = original === null || original === void 0 ? void 0 : original.close;
1324
+ const start = original === null || original === void 0 ? void 0 : original.start;
1325
+ const type = original === null || original === void 0 ? void 0 : original.type;
1326
+ const write = original === null || original === void 0 ? void 0 : original.write;
1327
+ return {
1328
+ abort: abort === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
1329
+ close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
1330
+ start: start === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
1331
+ write: write === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
1332
+ type
1333
+ };
1334
+ }
1335
+ function convertUnderlyingSinkAbortCallback(fn, original, context) {
1336
+ assertFunction(fn, context);
1337
+ return (reason) => promiseCall(fn, original, [reason]);
1338
+ }
1339
+ function convertUnderlyingSinkCloseCallback(fn, original, context) {
1340
+ assertFunction(fn, context);
1341
+ return () => promiseCall(fn, original, []);
1342
+ }
1343
+ function convertUnderlyingSinkStartCallback(fn, original, context) {
1344
+ assertFunction(fn, context);
1345
+ return (controller) => reflectCall(fn, original, [controller]);
1346
+ }
1347
+ function convertUnderlyingSinkWriteCallback(fn, original, context) {
1348
+ assertFunction(fn, context);
1349
+ return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
1350
+ }
1351
+ function assertWritableStream(x, context) {
1352
+ if (!IsWritableStream(x)) throw new TypeError(`${context} is not a WritableStream.`);
1353
+ }
1354
+ function isAbortSignal(value) {
1355
+ if (typeof value !== "object" || value === null) return false;
1356
+ try {
1357
+ return typeof value.aborted === "boolean";
1358
+ } catch (_a) {
1359
+ return false;
1360
+ }
1361
+ }
1362
+ const supportsAbortController = typeof AbortController === "function";
1363
+ /**
1364
+ * Construct a new AbortController, if supported by the platform.
1365
+ *
1366
+ * @internal
1367
+ */
1368
+ function createAbortController() {
1369
+ if (supportsAbortController) return new AbortController();
1370
+ }
1371
+ /**
1372
+ * A writable stream represents a destination for data, into which you can write.
1373
+ *
1374
+ * @public
1375
+ */
1376
+ class WritableStream {
1377
+ constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
1378
+ if (rawUnderlyingSink === void 0) rawUnderlyingSink = null;
1379
+ else assertObject(rawUnderlyingSink, "First parameter");
1380
+ const strategy = convertQueuingStrategy(rawStrategy, "Second parameter");
1381
+ const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter");
1382
+ InitializeWritableStream(this);
1383
+ if (underlyingSink.type !== void 0) throw new RangeError("Invalid type is specified");
1384
+ const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
1385
+ const highWaterMark = ExtractHighWaterMark(strategy, 1);
1386
+ SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
1387
+ }
1388
+ /**
1389
+ * Returns whether or not the writable stream is locked to a writer.
1390
+ */
1391
+ get locked() {
1392
+ if (!IsWritableStream(this)) throw streamBrandCheckException$2("locked");
1393
+ return IsWritableStreamLocked(this);
1394
+ }
1395
+ /**
1396
+ * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
1397
+ * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
1398
+ * mechanism of the underlying sink.
1399
+ *
1400
+ * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
1401
+ * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
1402
+ * the stream) if the stream is currently locked.
1403
+ */
1404
+ abort(reason = void 0) {
1405
+ if (!IsWritableStream(this)) return promiseRejectedWith(streamBrandCheckException$2("abort"));
1406
+ if (IsWritableStreamLocked(this)) return promiseRejectedWith(/* @__PURE__ */ new TypeError("Cannot abort a stream that already has a writer"));
1407
+ return WritableStreamAbort(this, reason);
1408
+ }
1409
+ /**
1410
+ * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
1411
+ * close behavior. During this time any further attempts to write will fail (without erroring the stream).
1412
+ *
1413
+ * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
1414
+ * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
1415
+ * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
1416
+ */
1417
+ close() {
1418
+ if (!IsWritableStream(this)) return promiseRejectedWith(streamBrandCheckException$2("close"));
1419
+ if (IsWritableStreamLocked(this)) return promiseRejectedWith(/* @__PURE__ */ new TypeError("Cannot close a stream that already has a writer"));
1420
+ if (WritableStreamCloseQueuedOrInFlight(this)) return promiseRejectedWith(/* @__PURE__ */ new TypeError("Cannot close an already-closing stream"));
1421
+ return WritableStreamClose(this);
1422
+ }
1423
+ /**
1424
+ * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
1425
+ * is locked, no other writer can be acquired until this one is released.
1426
+ *
1427
+ * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
1428
+ * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
1429
+ * the same time, which would cause the resulting written data to be unpredictable and probably useless.
1430
+ */
1431
+ getWriter() {
1432
+ if (!IsWritableStream(this)) throw streamBrandCheckException$2("getWriter");
1433
+ return AcquireWritableStreamDefaultWriter(this);
1434
+ }
1435
+ }
1436
+ Object.defineProperties(WritableStream.prototype, {
1437
+ abort: { enumerable: true },
1438
+ close: { enumerable: true },
1439
+ getWriter: { enumerable: true },
1440
+ locked: { enumerable: true }
1441
+ });
1442
+ setFunctionName(WritableStream.prototype.abort, "abort");
1443
+ setFunctionName(WritableStream.prototype.close, "close");
1444
+ setFunctionName(WritableStream.prototype.getWriter, "getWriter");
1445
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {
1446
+ value: "WritableStream",
1447
+ configurable: true
1448
+ });
1449
+ function AcquireWritableStreamDefaultWriter(stream) {
1450
+ return new WritableStreamDefaultWriter(stream);
1451
+ }
1452
+ function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
1453
+ const stream = Object.create(WritableStream.prototype);
1454
+ InitializeWritableStream(stream);
1455
+ SetUpWritableStreamDefaultController(stream, Object.create(WritableStreamDefaultController.prototype), startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
1456
+ return stream;
1457
+ }
1458
+ function InitializeWritableStream(stream) {
1459
+ stream._state = "writable";
1460
+ stream._storedError = void 0;
1461
+ stream._writer = void 0;
1462
+ stream._writableStreamController = void 0;
1463
+ stream._writeRequests = new SimpleQueue();
1464
+ stream._inFlightWriteRequest = void 0;
1465
+ stream._closeRequest = void 0;
1466
+ stream._inFlightCloseRequest = void 0;
1467
+ stream._pendingAbortRequest = void 0;
1468
+ stream._backpressure = false;
1469
+ }
1470
+ function IsWritableStream(x) {
1471
+ if (!typeIsObject(x)) return false;
1472
+ if (!Object.prototype.hasOwnProperty.call(x, "_writableStreamController")) return false;
1473
+ return x instanceof WritableStream;
1474
+ }
1475
+ function IsWritableStreamLocked(stream) {
1476
+ if (stream._writer === void 0) return false;
1477
+ return true;
1478
+ }
1479
+ function WritableStreamAbort(stream, reason) {
1480
+ var _a;
1481
+ if (stream._state === "closed" || stream._state === "errored") return promiseResolvedWith(void 0);
1482
+ stream._writableStreamController._abortReason = reason;
1483
+ (_a = stream._writableStreamController._abortController) === null || _a === void 0 || _a.abort(reason);
1484
+ const state = stream._state;
1485
+ if (state === "closed" || state === "errored") return promiseResolvedWith(void 0);
1486
+ if (stream._pendingAbortRequest !== void 0) return stream._pendingAbortRequest._promise;
1487
+ let wasAlreadyErroring = false;
1488
+ if (state === "erroring") {
1489
+ wasAlreadyErroring = true;
1490
+ reason = void 0;
1491
+ }
1492
+ const promise = newPromise((resolve, reject) => {
1493
+ stream._pendingAbortRequest = {
1494
+ _promise: void 0,
1495
+ _resolve: resolve,
1496
+ _reject: reject,
1497
+ _reason: reason,
1498
+ _wasAlreadyErroring: wasAlreadyErroring
1499
+ };
1500
+ });
1501
+ stream._pendingAbortRequest._promise = promise;
1502
+ if (!wasAlreadyErroring) WritableStreamStartErroring(stream, reason);
1503
+ return promise;
1504
+ }
1505
+ function WritableStreamClose(stream) {
1506
+ const state = stream._state;
1507
+ if (state === "closed" || state === "errored") return promiseRejectedWith(/* @__PURE__ */ new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
1508
+ const promise = newPromise((resolve, reject) => {
1509
+ stream._closeRequest = {
1510
+ _resolve: resolve,
1511
+ _reject: reject
1512
+ };
1513
+ });
1514
+ const writer = stream._writer;
1515
+ if (writer !== void 0 && stream._backpressure && state === "writable") defaultWriterReadyPromiseResolve(writer);
1516
+ WritableStreamDefaultControllerClose(stream._writableStreamController);
1517
+ return promise;
1518
+ }
1519
+ function WritableStreamAddWriteRequest(stream) {
1520
+ return newPromise((resolve, reject) => {
1521
+ const writeRequest = {
1522
+ _resolve: resolve,
1523
+ _reject: reject
1524
+ };
1525
+ stream._writeRequests.push(writeRequest);
1526
+ });
1527
+ }
1528
+ function WritableStreamDealWithRejection(stream, error) {
1529
+ if (stream._state === "writable") {
1530
+ WritableStreamStartErroring(stream, error);
1531
+ return;
1532
+ }
1533
+ WritableStreamFinishErroring(stream);
1534
+ }
1535
+ function WritableStreamStartErroring(stream, reason) {
1536
+ const controller = stream._writableStreamController;
1537
+ stream._state = "erroring";
1538
+ stream._storedError = reason;
1539
+ const writer = stream._writer;
1540
+ if (writer !== void 0) WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
1541
+ if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) WritableStreamFinishErroring(stream);
1542
+ }
1543
+ function WritableStreamFinishErroring(stream) {
1544
+ stream._state = "errored";
1545
+ stream._writableStreamController[ErrorSteps]();
1546
+ const storedError = stream._storedError;
1547
+ stream._writeRequests.forEach((writeRequest) => {
1548
+ writeRequest._reject(storedError);
1549
+ });
1550
+ stream._writeRequests = new SimpleQueue();
1551
+ if (stream._pendingAbortRequest === void 0) {
1552
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
1553
+ return;
1554
+ }
1555
+ const abortRequest = stream._pendingAbortRequest;
1556
+ stream._pendingAbortRequest = void 0;
1557
+ if (abortRequest._wasAlreadyErroring) {
1558
+ abortRequest._reject(storedError);
1559
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
1560
+ return;
1561
+ }
1562
+ uponPromise(stream._writableStreamController[AbortSteps](abortRequest._reason), () => {
1563
+ abortRequest._resolve();
1564
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
1565
+ return null;
1566
+ }, (reason) => {
1567
+ abortRequest._reject(reason);
1568
+ WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
1569
+ return null;
1570
+ });
1571
+ }
1572
+ function WritableStreamFinishInFlightWrite(stream) {
1573
+ stream._inFlightWriteRequest._resolve(void 0);
1574
+ stream._inFlightWriteRequest = void 0;
1575
+ }
1576
+ function WritableStreamFinishInFlightWriteWithError(stream, error) {
1577
+ stream._inFlightWriteRequest._reject(error);
1578
+ stream._inFlightWriteRequest = void 0;
1579
+ WritableStreamDealWithRejection(stream, error);
1580
+ }
1581
+ function WritableStreamFinishInFlightClose(stream) {
1582
+ stream._inFlightCloseRequest._resolve(void 0);
1583
+ stream._inFlightCloseRequest = void 0;
1584
+ if (stream._state === "erroring") {
1585
+ stream._storedError = void 0;
1586
+ if (stream._pendingAbortRequest !== void 0) {
1587
+ stream._pendingAbortRequest._resolve();
1588
+ stream._pendingAbortRequest = void 0;
1589
+ }
1590
+ }
1591
+ stream._state = "closed";
1592
+ const writer = stream._writer;
1593
+ if (writer !== void 0) defaultWriterClosedPromiseResolve(writer);
1594
+ }
1595
+ function WritableStreamFinishInFlightCloseWithError(stream, error) {
1596
+ stream._inFlightCloseRequest._reject(error);
1597
+ stream._inFlightCloseRequest = void 0;
1598
+ if (stream._pendingAbortRequest !== void 0) {
1599
+ stream._pendingAbortRequest._reject(error);
1600
+ stream._pendingAbortRequest = void 0;
1601
+ }
1602
+ WritableStreamDealWithRejection(stream, error);
1603
+ }
1604
+ function WritableStreamCloseQueuedOrInFlight(stream) {
1605
+ if (stream._closeRequest === void 0 && stream._inFlightCloseRequest === void 0) return false;
1606
+ return true;
1607
+ }
1608
+ function WritableStreamHasOperationMarkedInFlight(stream) {
1609
+ if (stream._inFlightWriteRequest === void 0 && stream._inFlightCloseRequest === void 0) return false;
1610
+ return true;
1611
+ }
1612
+ function WritableStreamMarkCloseRequestInFlight(stream) {
1613
+ stream._inFlightCloseRequest = stream._closeRequest;
1614
+ stream._closeRequest = void 0;
1615
+ }
1616
+ function WritableStreamMarkFirstWriteRequestInFlight(stream) {
1617
+ stream._inFlightWriteRequest = stream._writeRequests.shift();
1618
+ }
1619
+ function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
1620
+ if (stream._closeRequest !== void 0) {
1621
+ stream._closeRequest._reject(stream._storedError);
1622
+ stream._closeRequest = void 0;
1623
+ }
1624
+ const writer = stream._writer;
1625
+ if (writer !== void 0) defaultWriterClosedPromiseReject(writer, stream._storedError);
1626
+ }
1627
+ function WritableStreamUpdateBackpressure(stream, backpressure) {
1628
+ const writer = stream._writer;
1629
+ if (writer !== void 0 && backpressure !== stream._backpressure) if (backpressure) defaultWriterReadyPromiseReset(writer);
1630
+ else defaultWriterReadyPromiseResolve(writer);
1631
+ stream._backpressure = backpressure;
1632
+ }
1633
+ /**
1634
+ * A default writer vended by a {@link WritableStream}.
1635
+ *
1636
+ * @public
1637
+ */
1638
+ class WritableStreamDefaultWriter {
1639
+ constructor(stream) {
1640
+ assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter");
1641
+ assertWritableStream(stream, "First parameter");
1642
+ if (IsWritableStreamLocked(stream)) throw new TypeError("This stream has already been locked for exclusive writing by another writer");
1643
+ this._ownerWritableStream = stream;
1644
+ stream._writer = this;
1645
+ const state = stream._state;
1646
+ if (state === "writable") {
1647
+ if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) defaultWriterReadyPromiseInitialize(this);
1648
+ else defaultWriterReadyPromiseInitializeAsResolved(this);
1649
+ defaultWriterClosedPromiseInitialize(this);
1650
+ } else if (state === "erroring") {
1651
+ defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
1652
+ defaultWriterClosedPromiseInitialize(this);
1653
+ } else if (state === "closed") {
1654
+ defaultWriterReadyPromiseInitializeAsResolved(this);
1655
+ defaultWriterClosedPromiseInitializeAsResolved(this);
1656
+ } else {
1657
+ const storedError = stream._storedError;
1658
+ defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
1659
+ defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
1660
+ }
1661
+ }
1662
+ /**
1663
+ * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
1664
+ * the writer’s lock is released before the stream finishes closing.
1665
+ */
1666
+ get closed() {
1667
+ if (!IsWritableStreamDefaultWriter(this)) return promiseRejectedWith(defaultWriterBrandCheckException("closed"));
1668
+ return this._closedPromise;
1669
+ }
1670
+ /**
1671
+ * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
1672
+ * A producer can use this information to determine the right amount of data to write.
1673
+ *
1674
+ * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
1675
+ * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
1676
+ * the writer’s lock is released.
1677
+ */
1678
+ get desiredSize() {
1679
+ if (!IsWritableStreamDefaultWriter(this)) throw defaultWriterBrandCheckException("desiredSize");
1680
+ if (this._ownerWritableStream === void 0) throw defaultWriterLockException("desiredSize");
1681
+ return WritableStreamDefaultWriterGetDesiredSize(this);
1682
+ }
1683
+ /**
1684
+ * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
1685
+ * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
1686
+ * back to zero or below, the getter will return a new promise that stays pending until the next transition.
1687
+ *
1688
+ * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
1689
+ * rejected.
1690
+ */
1691
+ get ready() {
1692
+ if (!IsWritableStreamDefaultWriter(this)) return promiseRejectedWith(defaultWriterBrandCheckException("ready"));
1693
+ return this._readyPromise;
1694
+ }
1695
+ /**
1696
+ * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
1697
+ */
1698
+ abort(reason = void 0) {
1699
+ if (!IsWritableStreamDefaultWriter(this)) return promiseRejectedWith(defaultWriterBrandCheckException("abort"));
1700
+ if (this._ownerWritableStream === void 0) return promiseRejectedWith(defaultWriterLockException("abort"));
1701
+ return WritableStreamDefaultWriterAbort(this, reason);
1702
+ }
1703
+ /**
1704
+ * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
1705
+ */
1706
+ close() {
1707
+ if (!IsWritableStreamDefaultWriter(this)) return promiseRejectedWith(defaultWriterBrandCheckException("close"));
1708
+ const stream = this._ownerWritableStream;
1709
+ if (stream === void 0) return promiseRejectedWith(defaultWriterLockException("close"));
1710
+ if (WritableStreamCloseQueuedOrInFlight(stream)) return promiseRejectedWith(/* @__PURE__ */ new TypeError("Cannot close an already-closing stream"));
1711
+ return WritableStreamDefaultWriterClose(this);
1712
+ }
1713
+ /**
1714
+ * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
1715
+ * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
1716
+ * now on; otherwise, the writer will appear closed.
1717
+ *
1718
+ * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
1719
+ * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
1720
+ * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
1721
+ * other producers from writing in an interleaved manner.
1722
+ */
1723
+ releaseLock() {
1724
+ if (!IsWritableStreamDefaultWriter(this)) throw defaultWriterBrandCheckException("releaseLock");
1725
+ if (this._ownerWritableStream === void 0) return;
1726
+ WritableStreamDefaultWriterRelease(this);
1727
+ }
1728
+ write(chunk = void 0) {
1729
+ if (!IsWritableStreamDefaultWriter(this)) return promiseRejectedWith(defaultWriterBrandCheckException("write"));
1730
+ if (this._ownerWritableStream === void 0) return promiseRejectedWith(defaultWriterLockException("write to"));
1731
+ return WritableStreamDefaultWriterWrite(this, chunk);
1732
+ }
1733
+ }
1734
+ Object.defineProperties(WritableStreamDefaultWriter.prototype, {
1735
+ abort: { enumerable: true },
1736
+ close: { enumerable: true },
1737
+ releaseLock: { enumerable: true },
1738
+ write: { enumerable: true },
1739
+ closed: { enumerable: true },
1740
+ desiredSize: { enumerable: true },
1741
+ ready: { enumerable: true }
1742
+ });
1743
+ setFunctionName(WritableStreamDefaultWriter.prototype.abort, "abort");
1744
+ setFunctionName(WritableStreamDefaultWriter.prototype.close, "close");
1745
+ setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, "releaseLock");
1746
+ setFunctionName(WritableStreamDefaultWriter.prototype.write, "write");
1747
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {
1748
+ value: "WritableStreamDefaultWriter",
1749
+ configurable: true
1750
+ });
1751
+ function IsWritableStreamDefaultWriter(x) {
1752
+ if (!typeIsObject(x)) return false;
1753
+ if (!Object.prototype.hasOwnProperty.call(x, "_ownerWritableStream")) return false;
1754
+ return x instanceof WritableStreamDefaultWriter;
1755
+ }
1756
+ function WritableStreamDefaultWriterAbort(writer, reason) {
1757
+ const stream = writer._ownerWritableStream;
1758
+ return WritableStreamAbort(stream, reason);
1759
+ }
1760
+ function WritableStreamDefaultWriterClose(writer) {
1761
+ const stream = writer._ownerWritableStream;
1762
+ return WritableStreamClose(stream);
1763
+ }
1764
+ function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
1765
+ const stream = writer._ownerWritableStream;
1766
+ const state = stream._state;
1767
+ if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") return promiseResolvedWith(void 0);
1768
+ if (state === "errored") return promiseRejectedWith(stream._storedError);
1769
+ return WritableStreamDefaultWriterClose(writer);
1770
+ }
1771
+ function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
1772
+ if (writer._closedPromiseState === "pending") defaultWriterClosedPromiseReject(writer, error);
1773
+ else defaultWriterClosedPromiseResetToRejected(writer, error);
1774
+ }
1775
+ function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
1776
+ if (writer._readyPromiseState === "pending") defaultWriterReadyPromiseReject(writer, error);
1777
+ else defaultWriterReadyPromiseResetToRejected(writer, error);
1778
+ }
1779
+ function WritableStreamDefaultWriterGetDesiredSize(writer) {
1780
+ const stream = writer._ownerWritableStream;
1781
+ const state = stream._state;
1782
+ if (state === "errored" || state === "erroring") return null;
1783
+ if (state === "closed") return 0;
1784
+ return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
1785
+ }
1786
+ function WritableStreamDefaultWriterRelease(writer) {
1787
+ const stream = writer._ownerWritableStream;
1788
+ const releasedError = /* @__PURE__ */ new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
1789
+ WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
1790
+ WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
1791
+ stream._writer = void 0;
1792
+ writer._ownerWritableStream = void 0;
1793
+ }
1794
+ function WritableStreamDefaultWriterWrite(writer, chunk) {
1795
+ const stream = writer._ownerWritableStream;
1796
+ const controller = stream._writableStreamController;
1797
+ const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
1798
+ if (stream !== writer._ownerWritableStream) return promiseRejectedWith(defaultWriterLockException("write to"));
1799
+ const state = stream._state;
1800
+ if (state === "errored") return promiseRejectedWith(stream._storedError);
1801
+ if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") return promiseRejectedWith(/* @__PURE__ */ new TypeError("The stream is closing or closed and cannot be written to"));
1802
+ if (state === "erroring") return promiseRejectedWith(stream._storedError);
1803
+ const promise = WritableStreamAddWriteRequest(stream);
1804
+ WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
1805
+ return promise;
1806
+ }
1807
+ const closeSentinel = {};
1808
+ /**
1809
+ * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
1810
+ *
1811
+ * @public
1812
+ */
1813
+ class WritableStreamDefaultController {
1814
+ constructor() {
1815
+ throw new TypeError("Illegal constructor");
1816
+ }
1817
+ /**
1818
+ * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
1819
+ *
1820
+ * @deprecated
1821
+ * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
1822
+ * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
1823
+ */
1824
+ get abortReason() {
1825
+ if (!IsWritableStreamDefaultController(this)) throw defaultControllerBrandCheckException$2("abortReason");
1826
+ return this._abortReason;
1827
+ }
1828
+ /**
1829
+ * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
1830
+ */
1831
+ get signal() {
1832
+ if (!IsWritableStreamDefaultController(this)) throw defaultControllerBrandCheckException$2("signal");
1833
+ if (this._abortController === void 0) throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");
1834
+ return this._abortController.signal;
1835
+ }
1836
+ /**
1837
+ * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
1838
+ *
1839
+ * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
1840
+ * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
1841
+ * normal lifecycle of interactions with the underlying sink.
1842
+ */
1843
+ error(e = void 0) {
1844
+ if (!IsWritableStreamDefaultController(this)) throw defaultControllerBrandCheckException$2("error");
1845
+ if (this._controlledWritableStream._state !== "writable") return;
1846
+ WritableStreamDefaultControllerError(this, e);
1847
+ }
1848
+ /** @internal */
1849
+ [AbortSteps](reason) {
1850
+ const result = this._abortAlgorithm(reason);
1851
+ WritableStreamDefaultControllerClearAlgorithms(this);
1852
+ return result;
1853
+ }
1854
+ /** @internal */
1855
+ [ErrorSteps]() {
1856
+ ResetQueue(this);
1857
+ }
1858
+ }
1859
+ Object.defineProperties(WritableStreamDefaultController.prototype, {
1860
+ abortReason: { enumerable: true },
1861
+ signal: { enumerable: true },
1862
+ error: { enumerable: true }
1863
+ });
1864
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {
1865
+ value: "WritableStreamDefaultController",
1866
+ configurable: true
1867
+ });
1868
+ function IsWritableStreamDefaultController(x) {
1869
+ if (!typeIsObject(x)) return false;
1870
+ if (!Object.prototype.hasOwnProperty.call(x, "_controlledWritableStream")) return false;
1871
+ return x instanceof WritableStreamDefaultController;
1872
+ }
1873
+ function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
1874
+ controller._controlledWritableStream = stream;
1875
+ stream._writableStreamController = controller;
1876
+ controller._queue = void 0;
1877
+ controller._queueTotalSize = void 0;
1878
+ ResetQueue(controller);
1879
+ controller._abortReason = void 0;
1880
+ controller._abortController = createAbortController();
1881
+ controller._started = false;
1882
+ controller._strategySizeAlgorithm = sizeAlgorithm;
1883
+ controller._strategyHWM = highWaterMark;
1884
+ controller._writeAlgorithm = writeAlgorithm;
1885
+ controller._closeAlgorithm = closeAlgorithm;
1886
+ controller._abortAlgorithm = abortAlgorithm;
1887
+ WritableStreamUpdateBackpressure(stream, WritableStreamDefaultControllerGetBackpressure(controller));
1888
+ uponPromise(promiseResolvedWith(startAlgorithm()), () => {
1889
+ controller._started = true;
1890
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
1891
+ return null;
1892
+ }, (r) => {
1893
+ controller._started = true;
1894
+ WritableStreamDealWithRejection(stream, r);
1895
+ return null;
1896
+ });
1897
+ }
1898
+ function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
1899
+ const controller = Object.create(WritableStreamDefaultController.prototype);
1900
+ let startAlgorithm;
1901
+ let writeAlgorithm;
1902
+ let closeAlgorithm;
1903
+ let abortAlgorithm;
1904
+ if (underlyingSink.start !== void 0) startAlgorithm = () => underlyingSink.start(controller);
1905
+ else startAlgorithm = () => void 0;
1906
+ if (underlyingSink.write !== void 0) writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller);
1907
+ else writeAlgorithm = () => promiseResolvedWith(void 0);
1908
+ if (underlyingSink.close !== void 0) closeAlgorithm = () => underlyingSink.close();
1909
+ else closeAlgorithm = () => promiseResolvedWith(void 0);
1910
+ if (underlyingSink.abort !== void 0) abortAlgorithm = (reason) => underlyingSink.abort(reason);
1911
+ else abortAlgorithm = () => promiseResolvedWith(void 0);
1912
+ SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
1913
+ }
1914
+ function WritableStreamDefaultControllerClearAlgorithms(controller) {
1915
+ controller._writeAlgorithm = void 0;
1916
+ controller._closeAlgorithm = void 0;
1917
+ controller._abortAlgorithm = void 0;
1918
+ controller._strategySizeAlgorithm = void 0;
1919
+ }
1920
+ function WritableStreamDefaultControllerClose(controller) {
1921
+ EnqueueValueWithSize(controller, closeSentinel, 0);
1922
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
1923
+ }
1924
+ function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
1925
+ try {
1926
+ return controller._strategySizeAlgorithm(chunk);
1927
+ } catch (chunkSizeE) {
1928
+ WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
1929
+ return 1;
1930
+ }
1931
+ }
1932
+ function WritableStreamDefaultControllerGetDesiredSize(controller) {
1933
+ return controller._strategyHWM - controller._queueTotalSize;
1934
+ }
1935
+ function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
1936
+ try {
1937
+ EnqueueValueWithSize(controller, chunk, chunkSize);
1938
+ } catch (enqueueE) {
1939
+ WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
1940
+ return;
1941
+ }
1942
+ const stream = controller._controlledWritableStream;
1943
+ if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") WritableStreamUpdateBackpressure(stream, WritableStreamDefaultControllerGetBackpressure(controller));
1944
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
1945
+ }
1946
+ function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
1947
+ const stream = controller._controlledWritableStream;
1948
+ if (!controller._started) return;
1949
+ if (stream._inFlightWriteRequest !== void 0) return;
1950
+ if (stream._state === "erroring") {
1951
+ WritableStreamFinishErroring(stream);
1952
+ return;
1953
+ }
1954
+ if (controller._queue.length === 0) return;
1955
+ const value = PeekQueueValue(controller);
1956
+ if (value === closeSentinel) WritableStreamDefaultControllerProcessClose(controller);
1957
+ else WritableStreamDefaultControllerProcessWrite(controller, value);
1958
+ }
1959
+ function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
1960
+ if (controller._controlledWritableStream._state === "writable") WritableStreamDefaultControllerError(controller, error);
1961
+ }
1962
+ function WritableStreamDefaultControllerProcessClose(controller) {
1963
+ const stream = controller._controlledWritableStream;
1964
+ WritableStreamMarkCloseRequestInFlight(stream);
1965
+ DequeueValue(controller);
1966
+ const sinkClosePromise = controller._closeAlgorithm();
1967
+ WritableStreamDefaultControllerClearAlgorithms(controller);
1968
+ uponPromise(sinkClosePromise, () => {
1969
+ WritableStreamFinishInFlightClose(stream);
1970
+ return null;
1971
+ }, (reason) => {
1972
+ WritableStreamFinishInFlightCloseWithError(stream, reason);
1973
+ return null;
1974
+ });
1975
+ }
1976
+ function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
1977
+ const stream = controller._controlledWritableStream;
1978
+ WritableStreamMarkFirstWriteRequestInFlight(stream);
1979
+ uponPromise(controller._writeAlgorithm(chunk), () => {
1980
+ WritableStreamFinishInFlightWrite(stream);
1981
+ const state = stream._state;
1982
+ DequeueValue(controller);
1983
+ if (!WritableStreamCloseQueuedOrInFlight(stream) && state === "writable") WritableStreamUpdateBackpressure(stream, WritableStreamDefaultControllerGetBackpressure(controller));
1984
+ WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
1985
+ return null;
1986
+ }, (reason) => {
1987
+ if (stream._state === "writable") WritableStreamDefaultControllerClearAlgorithms(controller);
1988
+ WritableStreamFinishInFlightWriteWithError(stream, reason);
1989
+ return null;
1990
+ });
1991
+ }
1992
+ function WritableStreamDefaultControllerGetBackpressure(controller) {
1993
+ return WritableStreamDefaultControllerGetDesiredSize(controller) <= 0;
1994
+ }
1995
+ function WritableStreamDefaultControllerError(controller, error) {
1996
+ const stream = controller._controlledWritableStream;
1997
+ WritableStreamDefaultControllerClearAlgorithms(controller);
1998
+ WritableStreamStartErroring(stream, error);
1999
+ }
2000
+ function streamBrandCheckException$2(name) {
2001
+ return /* @__PURE__ */ new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
2002
+ }
2003
+ function defaultControllerBrandCheckException$2(name) {
2004
+ return /* @__PURE__ */ new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);
2005
+ }
2006
+ function defaultWriterBrandCheckException(name) {
2007
+ return /* @__PURE__ */ new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
2008
+ }
2009
+ function defaultWriterLockException(name) {
2010
+ return /* @__PURE__ */ new TypeError("Cannot " + name + " a stream using a released writer");
2011
+ }
2012
+ function defaultWriterClosedPromiseInitialize(writer) {
2013
+ writer._closedPromise = newPromise((resolve, reject) => {
2014
+ writer._closedPromise_resolve = resolve;
2015
+ writer._closedPromise_reject = reject;
2016
+ writer._closedPromiseState = "pending";
2017
+ });
2018
+ }
2019
+ function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
2020
+ defaultWriterClosedPromiseInitialize(writer);
2021
+ defaultWriterClosedPromiseReject(writer, reason);
2022
+ }
2023
+ function defaultWriterClosedPromiseInitializeAsResolved(writer) {
2024
+ defaultWriterClosedPromiseInitialize(writer);
2025
+ defaultWriterClosedPromiseResolve(writer);
2026
+ }
2027
+ function defaultWriterClosedPromiseReject(writer, reason) {
2028
+ if (writer._closedPromise_reject === void 0) return;
2029
+ setPromiseIsHandledToTrue(writer._closedPromise);
2030
+ writer._closedPromise_reject(reason);
2031
+ writer._closedPromise_resolve = void 0;
2032
+ writer._closedPromise_reject = void 0;
2033
+ writer._closedPromiseState = "rejected";
2034
+ }
2035
+ function defaultWriterClosedPromiseResetToRejected(writer, reason) {
2036
+ defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
2037
+ }
2038
+ function defaultWriterClosedPromiseResolve(writer) {
2039
+ if (writer._closedPromise_resolve === void 0) return;
2040
+ writer._closedPromise_resolve(void 0);
2041
+ writer._closedPromise_resolve = void 0;
2042
+ writer._closedPromise_reject = void 0;
2043
+ writer._closedPromiseState = "resolved";
2044
+ }
2045
+ function defaultWriterReadyPromiseInitialize(writer) {
2046
+ writer._readyPromise = newPromise((resolve, reject) => {
2047
+ writer._readyPromise_resolve = resolve;
2048
+ writer._readyPromise_reject = reject;
2049
+ });
2050
+ writer._readyPromiseState = "pending";
2051
+ }
2052
+ function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
2053
+ defaultWriterReadyPromiseInitialize(writer);
2054
+ defaultWriterReadyPromiseReject(writer, reason);
2055
+ }
2056
+ function defaultWriterReadyPromiseInitializeAsResolved(writer) {
2057
+ defaultWriterReadyPromiseInitialize(writer);
2058
+ defaultWriterReadyPromiseResolve(writer);
2059
+ }
2060
+ function defaultWriterReadyPromiseReject(writer, reason) {
2061
+ if (writer._readyPromise_reject === void 0) return;
2062
+ setPromiseIsHandledToTrue(writer._readyPromise);
2063
+ writer._readyPromise_reject(reason);
2064
+ writer._readyPromise_resolve = void 0;
2065
+ writer._readyPromise_reject = void 0;
2066
+ writer._readyPromiseState = "rejected";
2067
+ }
2068
+ function defaultWriterReadyPromiseReset(writer) {
2069
+ defaultWriterReadyPromiseInitialize(writer);
2070
+ }
2071
+ function defaultWriterReadyPromiseResetToRejected(writer, reason) {
2072
+ defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
2073
+ }
2074
+ function defaultWriterReadyPromiseResolve(writer) {
2075
+ if (writer._readyPromise_resolve === void 0) return;
2076
+ writer._readyPromise_resolve(void 0);
2077
+ writer._readyPromise_resolve = void 0;
2078
+ writer._readyPromise_reject = void 0;
2079
+ writer._readyPromiseState = "fulfilled";
2080
+ }
2081
+ function getGlobals() {
2082
+ if (typeof globalThis !== "undefined") return globalThis;
2083
+ else if (typeof self !== "undefined") return self;
2084
+ else if (typeof global !== "undefined") return global;
2085
+ }
2086
+ const globals = getGlobals();
2087
+ function isDOMExceptionConstructor(ctor) {
2088
+ if (!(typeof ctor === "function" || typeof ctor === "object")) return false;
2089
+ if (ctor.name !== "DOMException") return false;
2090
+ try {
2091
+ new ctor();
2092
+ return true;
2093
+ } catch (_a) {
2094
+ return false;
2095
+ }
2096
+ }
2097
+ /**
2098
+ * Support:
2099
+ * - Web browsers
2100
+ * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)
2101
+ */
2102
+ function getFromGlobal() {
2103
+ const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
2104
+ return isDOMExceptionConstructor(ctor) ? ctor : void 0;
2105
+ }
2106
+ /**
2107
+ * Support:
2108
+ * - All platforms
2109
+ */
2110
+ function createPolyfill() {
2111
+ const ctor = function DOMException(message, name) {
2112
+ this.message = message || "";
2113
+ this.name = name || "Error";
2114
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
2115
+ };
2116
+ setFunctionName(ctor, "DOMException");
2117
+ ctor.prototype = Object.create(Error.prototype);
2118
+ Object.defineProperty(ctor.prototype, "constructor", {
2119
+ value: ctor,
2120
+ writable: true,
2121
+ configurable: true
2122
+ });
2123
+ return ctor;
2124
+ }
2125
+ const DOMException = getFromGlobal() || createPolyfill();
2126
+ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
2127
+ const reader = AcquireReadableStreamDefaultReader(source);
2128
+ const writer = AcquireWritableStreamDefaultWriter(dest);
2129
+ source._disturbed = true;
2130
+ let shuttingDown = false;
2131
+ let currentWrite = promiseResolvedWith(void 0);
2132
+ return newPromise((resolve, reject) => {
2133
+ let abortAlgorithm;
2134
+ if (signal !== void 0) {
2135
+ abortAlgorithm = () => {
2136
+ const error = signal.reason !== void 0 ? signal.reason : new DOMException("Aborted", "AbortError");
2137
+ const actions = [];
2138
+ if (!preventAbort) actions.push(() => {
2139
+ if (dest._state === "writable") return WritableStreamAbort(dest, error);
2140
+ return promiseResolvedWith(void 0);
2141
+ });
2142
+ if (!preventCancel) actions.push(() => {
2143
+ if (source._state === "readable") return ReadableStreamCancel(source, error);
2144
+ return promiseResolvedWith(void 0);
2145
+ });
2146
+ shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error);
2147
+ };
2148
+ if (signal.aborted) {
2149
+ abortAlgorithm();
2150
+ return;
2151
+ }
2152
+ signal.addEventListener("abort", abortAlgorithm);
2153
+ }
2154
+ function pipeLoop() {
2155
+ return newPromise((resolveLoop, rejectLoop) => {
2156
+ function next(done) {
2157
+ if (done) resolveLoop();
2158
+ else PerformPromiseThen(pipeStep(), next, rejectLoop);
2159
+ }
2160
+ next(false);
2161
+ });
2162
+ }
2163
+ function pipeStep() {
2164
+ if (shuttingDown) return promiseResolvedWith(true);
2165
+ return PerformPromiseThen(writer._readyPromise, () => {
2166
+ return newPromise((resolveRead, rejectRead) => {
2167
+ ReadableStreamDefaultReaderRead(reader, {
2168
+ _chunkSteps: (chunk) => {
2169
+ currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop);
2170
+ resolveRead(false);
2171
+ },
2172
+ _closeSteps: () => resolveRead(true),
2173
+ _errorSteps: rejectRead
2174
+ });
2175
+ });
2176
+ });
2177
+ }
2178
+ isOrBecomesErrored(source, reader._closedPromise, (storedError) => {
2179
+ if (!preventAbort) shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
2180
+ else shutdown(true, storedError);
2181
+ return null;
2182
+ });
2183
+ isOrBecomesErrored(dest, writer._closedPromise, (storedError) => {
2184
+ if (!preventCancel) shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
2185
+ else shutdown(true, storedError);
2186
+ return null;
2187
+ });
2188
+ isOrBecomesClosed(source, reader._closedPromise, () => {
2189
+ if (!preventClose) shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
2190
+ else shutdown();
2191
+ return null;
2192
+ });
2193
+ if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") {
2194
+ const destClosed = /* @__PURE__ */ new TypeError("the destination writable stream closed before all data could be piped to it");
2195
+ if (!preventCancel) shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
2196
+ else shutdown(true, destClosed);
2197
+ }
2198
+ setPromiseIsHandledToTrue(pipeLoop());
2199
+ function waitForWritesToFinish() {
2200
+ const oldCurrentWrite = currentWrite;
2201
+ return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0);
2202
+ }
2203
+ function isOrBecomesErrored(stream, promise, action) {
2204
+ if (stream._state === "errored") action(stream._storedError);
2205
+ else uponRejection(promise, action);
2206
+ }
2207
+ function isOrBecomesClosed(stream, promise, action) {
2208
+ if (stream._state === "closed") action();
2209
+ else uponFulfillment(promise, action);
2210
+ }
2211
+ function shutdownWithAction(action, originalIsError, originalError) {
2212
+ if (shuttingDown) return;
2213
+ shuttingDown = true;
2214
+ if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) uponFulfillment(waitForWritesToFinish(), doTheRest);
2215
+ else doTheRest();
2216
+ function doTheRest() {
2217
+ uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError));
2218
+ return null;
2219
+ }
2220
+ }
2221
+ function shutdown(isError, error) {
2222
+ if (shuttingDown) return;
2223
+ shuttingDown = true;
2224
+ if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
2225
+ else finalize(isError, error);
2226
+ }
2227
+ function finalize(isError, error) {
2228
+ WritableStreamDefaultWriterRelease(writer);
2229
+ ReadableStreamReaderGenericRelease(reader);
2230
+ if (signal !== void 0) signal.removeEventListener("abort", abortAlgorithm);
2231
+ if (isError) reject(error);
2232
+ else resolve(void 0);
2233
+ return null;
2234
+ }
2235
+ });
2236
+ }
2237
+ /**
2238
+ * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
2239
+ *
2240
+ * @public
2241
+ */
2242
+ class ReadableStreamDefaultController {
2243
+ constructor() {
2244
+ throw new TypeError("Illegal constructor");
2245
+ }
2246
+ /**
2247
+ * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
2248
+ * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
2249
+ */
2250
+ get desiredSize() {
2251
+ if (!IsReadableStreamDefaultController(this)) throw defaultControllerBrandCheckException$1("desiredSize");
2252
+ return ReadableStreamDefaultControllerGetDesiredSize(this);
2253
+ }
2254
+ /**
2255
+ * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
2256
+ * the stream, but once those are read, the stream will become closed.
2257
+ */
2258
+ close() {
2259
+ if (!IsReadableStreamDefaultController(this)) throw defaultControllerBrandCheckException$1("close");
2260
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) throw new TypeError("The stream is not in a state that permits close");
2261
+ ReadableStreamDefaultControllerClose(this);
2262
+ }
2263
+ enqueue(chunk = void 0) {
2264
+ if (!IsReadableStreamDefaultController(this)) throw defaultControllerBrandCheckException$1("enqueue");
2265
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) throw new TypeError("The stream is not in a state that permits enqueue");
2266
+ return ReadableStreamDefaultControllerEnqueue(this, chunk);
2267
+ }
2268
+ /**
2269
+ * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
2270
+ */
2271
+ error(e = void 0) {
2272
+ if (!IsReadableStreamDefaultController(this)) throw defaultControllerBrandCheckException$1("error");
2273
+ ReadableStreamDefaultControllerError(this, e);
2274
+ }
2275
+ /** @internal */
2276
+ [CancelSteps](reason) {
2277
+ ResetQueue(this);
2278
+ const result = this._cancelAlgorithm(reason);
2279
+ ReadableStreamDefaultControllerClearAlgorithms(this);
2280
+ return result;
2281
+ }
2282
+ /** @internal */
2283
+ [PullSteps](readRequest) {
2284
+ const stream = this._controlledReadableStream;
2285
+ if (this._queue.length > 0) {
2286
+ const chunk = DequeueValue(this);
2287
+ if (this._closeRequested && this._queue.length === 0) {
2288
+ ReadableStreamDefaultControllerClearAlgorithms(this);
2289
+ ReadableStreamClose(stream);
2290
+ } else ReadableStreamDefaultControllerCallPullIfNeeded(this);
2291
+ readRequest._chunkSteps(chunk);
2292
+ } else {
2293
+ ReadableStreamAddReadRequest(stream, readRequest);
2294
+ ReadableStreamDefaultControllerCallPullIfNeeded(this);
2295
+ }
2296
+ }
2297
+ /** @internal */
2298
+ [ReleaseSteps]() {}
2299
+ }
2300
+ Object.defineProperties(ReadableStreamDefaultController.prototype, {
2301
+ close: { enumerable: true },
2302
+ enqueue: { enumerable: true },
2303
+ error: { enumerable: true },
2304
+ desiredSize: { enumerable: true }
2305
+ });
2306
+ setFunctionName(ReadableStreamDefaultController.prototype.close, "close");
2307
+ setFunctionName(ReadableStreamDefaultController.prototype.enqueue, "enqueue");
2308
+ setFunctionName(ReadableStreamDefaultController.prototype.error, "error");
2309
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {
2310
+ value: "ReadableStreamDefaultController",
2311
+ configurable: true
2312
+ });
2313
+ function IsReadableStreamDefaultController(x) {
2314
+ if (!typeIsObject(x)) return false;
2315
+ if (!Object.prototype.hasOwnProperty.call(x, "_controlledReadableStream")) return false;
2316
+ return x instanceof ReadableStreamDefaultController;
2317
+ }
2318
+ function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
2319
+ if (!ReadableStreamDefaultControllerShouldCallPull(controller)) return;
2320
+ if (controller._pulling) {
2321
+ controller._pullAgain = true;
2322
+ return;
2323
+ }
2324
+ controller._pulling = true;
2325
+ uponPromise(controller._pullAlgorithm(), () => {
2326
+ controller._pulling = false;
2327
+ if (controller._pullAgain) {
2328
+ controller._pullAgain = false;
2329
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
2330
+ }
2331
+ return null;
2332
+ }, (e) => {
2333
+ ReadableStreamDefaultControllerError(controller, e);
2334
+ return null;
2335
+ });
2336
+ }
2337
+ function ReadableStreamDefaultControllerShouldCallPull(controller) {
2338
+ const stream = controller._controlledReadableStream;
2339
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) return false;
2340
+ if (!controller._started) return false;
2341
+ if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) return true;
2342
+ if (ReadableStreamDefaultControllerGetDesiredSize(controller) > 0) return true;
2343
+ return false;
2344
+ }
2345
+ function ReadableStreamDefaultControllerClearAlgorithms(controller) {
2346
+ controller._pullAlgorithm = void 0;
2347
+ controller._cancelAlgorithm = void 0;
2348
+ controller._strategySizeAlgorithm = void 0;
2349
+ }
2350
+ function ReadableStreamDefaultControllerClose(controller) {
2351
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) return;
2352
+ const stream = controller._controlledReadableStream;
2353
+ controller._closeRequested = true;
2354
+ if (controller._queue.length === 0) {
2355
+ ReadableStreamDefaultControllerClearAlgorithms(controller);
2356
+ ReadableStreamClose(stream);
2357
+ }
2358
+ }
2359
+ function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
2360
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) return;
2361
+ const stream = controller._controlledReadableStream;
2362
+ if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) ReadableStreamFulfillReadRequest(stream, chunk, false);
2363
+ else {
2364
+ let chunkSize;
2365
+ try {
2366
+ chunkSize = controller._strategySizeAlgorithm(chunk);
2367
+ } catch (chunkSizeE) {
2368
+ ReadableStreamDefaultControllerError(controller, chunkSizeE);
2369
+ throw chunkSizeE;
2370
+ }
2371
+ try {
2372
+ EnqueueValueWithSize(controller, chunk, chunkSize);
2373
+ } catch (enqueueE) {
2374
+ ReadableStreamDefaultControllerError(controller, enqueueE);
2375
+ throw enqueueE;
2376
+ }
2377
+ }
2378
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
2379
+ }
2380
+ function ReadableStreamDefaultControllerError(controller, e) {
2381
+ const stream = controller._controlledReadableStream;
2382
+ if (stream._state !== "readable") return;
2383
+ ResetQueue(controller);
2384
+ ReadableStreamDefaultControllerClearAlgorithms(controller);
2385
+ ReadableStreamError(stream, e);
2386
+ }
2387
+ function ReadableStreamDefaultControllerGetDesiredSize(controller) {
2388
+ const state = controller._controlledReadableStream._state;
2389
+ if (state === "errored") return null;
2390
+ if (state === "closed") return 0;
2391
+ return controller._strategyHWM - controller._queueTotalSize;
2392
+ }
2393
+ function ReadableStreamDefaultControllerHasBackpressure(controller) {
2394
+ if (ReadableStreamDefaultControllerShouldCallPull(controller)) return false;
2395
+ return true;
2396
+ }
2397
+ function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
2398
+ const state = controller._controlledReadableStream._state;
2399
+ if (!controller._closeRequested && state === "readable") return true;
2400
+ return false;
2401
+ }
2402
+ function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
2403
+ controller._controlledReadableStream = stream;
2404
+ controller._queue = void 0;
2405
+ controller._queueTotalSize = void 0;
2406
+ ResetQueue(controller);
2407
+ controller._started = false;
2408
+ controller._closeRequested = false;
2409
+ controller._pullAgain = false;
2410
+ controller._pulling = false;
2411
+ controller._strategySizeAlgorithm = sizeAlgorithm;
2412
+ controller._strategyHWM = highWaterMark;
2413
+ controller._pullAlgorithm = pullAlgorithm;
2414
+ controller._cancelAlgorithm = cancelAlgorithm;
2415
+ stream._readableStreamController = controller;
2416
+ uponPromise(promiseResolvedWith(startAlgorithm()), () => {
2417
+ controller._started = true;
2418
+ ReadableStreamDefaultControllerCallPullIfNeeded(controller);
2419
+ return null;
2420
+ }, (r) => {
2421
+ ReadableStreamDefaultControllerError(controller, r);
2422
+ return null;
2423
+ });
2424
+ }
2425
+ function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
2426
+ const controller = Object.create(ReadableStreamDefaultController.prototype);
2427
+ let startAlgorithm;
2428
+ let pullAlgorithm;
2429
+ let cancelAlgorithm;
2430
+ if (underlyingSource.start !== void 0) startAlgorithm = () => underlyingSource.start(controller);
2431
+ else startAlgorithm = () => void 0;
2432
+ if (underlyingSource.pull !== void 0) pullAlgorithm = () => underlyingSource.pull(controller);
2433
+ else pullAlgorithm = () => promiseResolvedWith(void 0);
2434
+ if (underlyingSource.cancel !== void 0) cancelAlgorithm = (reason) => underlyingSource.cancel(reason);
2435
+ else cancelAlgorithm = () => promiseResolvedWith(void 0);
2436
+ SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
2437
+ }
2438
+ function defaultControllerBrandCheckException$1(name) {
2439
+ return /* @__PURE__ */ new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
2440
+ }
2441
+ function ReadableStreamTee(stream, cloneForBranch2) {
2442
+ if (IsReadableByteStreamController(stream._readableStreamController)) return ReadableByteStreamTee(stream);
2443
+ return ReadableStreamDefaultTee(stream);
2444
+ }
2445
+ function ReadableStreamDefaultTee(stream, cloneForBranch2) {
2446
+ const reader = AcquireReadableStreamDefaultReader(stream);
2447
+ let reading = false;
2448
+ let readAgain = false;
2449
+ let canceled1 = false;
2450
+ let canceled2 = false;
2451
+ let reason1;
2452
+ let reason2;
2453
+ let branch1;
2454
+ let branch2;
2455
+ let resolveCancelPromise;
2456
+ const cancelPromise = newPromise((resolve) => {
2457
+ resolveCancelPromise = resolve;
2458
+ });
2459
+ function pullAlgorithm() {
2460
+ if (reading) {
2461
+ readAgain = true;
2462
+ return promiseResolvedWith(void 0);
2463
+ }
2464
+ reading = true;
2465
+ ReadableStreamDefaultReaderRead(reader, {
2466
+ _chunkSteps: (chunk) => {
2467
+ _queueMicrotask(() => {
2468
+ readAgain = false;
2469
+ const chunk1 = chunk;
2470
+ const chunk2 = chunk;
2471
+ if (!canceled1) ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
2472
+ if (!canceled2) ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
2473
+ reading = false;
2474
+ if (readAgain) pullAlgorithm();
2475
+ });
2476
+ },
2477
+ _closeSteps: () => {
2478
+ reading = false;
2479
+ if (!canceled1) ReadableStreamDefaultControllerClose(branch1._readableStreamController);
2480
+ if (!canceled2) ReadableStreamDefaultControllerClose(branch2._readableStreamController);
2481
+ if (!canceled1 || !canceled2) resolveCancelPromise(void 0);
2482
+ },
2483
+ _errorSteps: () => {
2484
+ reading = false;
2485
+ }
2486
+ });
2487
+ return promiseResolvedWith(void 0);
2488
+ }
2489
+ function cancel1Algorithm(reason) {
2490
+ canceled1 = true;
2491
+ reason1 = reason;
2492
+ if (canceled2) {
2493
+ const cancelResult = ReadableStreamCancel(stream, CreateArrayFromList([reason1, reason2]));
2494
+ resolveCancelPromise(cancelResult);
2495
+ }
2496
+ return cancelPromise;
2497
+ }
2498
+ function cancel2Algorithm(reason) {
2499
+ canceled2 = true;
2500
+ reason2 = reason;
2501
+ if (canceled1) {
2502
+ const cancelResult = ReadableStreamCancel(stream, CreateArrayFromList([reason1, reason2]));
2503
+ resolveCancelPromise(cancelResult);
2504
+ }
2505
+ return cancelPromise;
2506
+ }
2507
+ function startAlgorithm() {}
2508
+ branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
2509
+ branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
2510
+ uponRejection(reader._closedPromise, (r) => {
2511
+ ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
2512
+ ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
2513
+ if (!canceled1 || !canceled2) resolveCancelPromise(void 0);
2514
+ return null;
2515
+ });
2516
+ return [branch1, branch2];
2517
+ }
2518
+ function ReadableByteStreamTee(stream) {
2519
+ let reader = AcquireReadableStreamDefaultReader(stream);
2520
+ let reading = false;
2521
+ let readAgainForBranch1 = false;
2522
+ let readAgainForBranch2 = false;
2523
+ let canceled1 = false;
2524
+ let canceled2 = false;
2525
+ let reason1;
2526
+ let reason2;
2527
+ let branch1;
2528
+ let branch2;
2529
+ let resolveCancelPromise;
2530
+ const cancelPromise = newPromise((resolve) => {
2531
+ resolveCancelPromise = resolve;
2532
+ });
2533
+ function forwardReaderError(thisReader) {
2534
+ uponRejection(thisReader._closedPromise, (r) => {
2535
+ if (thisReader !== reader) return null;
2536
+ ReadableByteStreamControllerError(branch1._readableStreamController, r);
2537
+ ReadableByteStreamControllerError(branch2._readableStreamController, r);
2538
+ if (!canceled1 || !canceled2) resolveCancelPromise(void 0);
2539
+ return null;
2540
+ });
2541
+ }
2542
+ function pullWithDefaultReader() {
2543
+ if (IsReadableStreamBYOBReader(reader)) {
2544
+ ReadableStreamReaderGenericRelease(reader);
2545
+ reader = AcquireReadableStreamDefaultReader(stream);
2546
+ forwardReaderError(reader);
2547
+ }
2548
+ ReadableStreamDefaultReaderRead(reader, {
2549
+ _chunkSteps: (chunk) => {
2550
+ _queueMicrotask(() => {
2551
+ readAgainForBranch1 = false;
2552
+ readAgainForBranch2 = false;
2553
+ const chunk1 = chunk;
2554
+ let chunk2 = chunk;
2555
+ if (!canceled1 && !canceled2) try {
2556
+ chunk2 = CloneAsUint8Array(chunk);
2557
+ } catch (cloneE) {
2558
+ ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);
2559
+ ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);
2560
+ resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
2561
+ return;
2562
+ }
2563
+ if (!canceled1) ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);
2564
+ if (!canceled2) ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);
2565
+ reading = false;
2566
+ if (readAgainForBranch1) pull1Algorithm();
2567
+ else if (readAgainForBranch2) pull2Algorithm();
2568
+ });
2569
+ },
2570
+ _closeSteps: () => {
2571
+ reading = false;
2572
+ if (!canceled1) ReadableByteStreamControllerClose(branch1._readableStreamController);
2573
+ if (!canceled2) ReadableByteStreamControllerClose(branch2._readableStreamController);
2574
+ if (branch1._readableStreamController._pendingPullIntos.length > 0) ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);
2575
+ if (branch2._readableStreamController._pendingPullIntos.length > 0) ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);
2576
+ if (!canceled1 || !canceled2) resolveCancelPromise(void 0);
2577
+ },
2578
+ _errorSteps: () => {
2579
+ reading = false;
2580
+ }
2581
+ });
2582
+ }
2583
+ function pullWithBYOBReader(view, forBranch2) {
2584
+ if (IsReadableStreamDefaultReader(reader)) {
2585
+ ReadableStreamReaderGenericRelease(reader);
2586
+ reader = AcquireReadableStreamBYOBReader(stream);
2587
+ forwardReaderError(reader);
2588
+ }
2589
+ const byobBranch = forBranch2 ? branch2 : branch1;
2590
+ const otherBranch = forBranch2 ? branch1 : branch2;
2591
+ ReadableStreamBYOBReaderRead(reader, view, 1, {
2592
+ _chunkSteps: (chunk) => {
2593
+ _queueMicrotask(() => {
2594
+ readAgainForBranch1 = false;
2595
+ readAgainForBranch2 = false;
2596
+ const byobCanceled = forBranch2 ? canceled2 : canceled1;
2597
+ if (!(forBranch2 ? canceled1 : canceled2)) {
2598
+ let clonedChunk;
2599
+ try {
2600
+ clonedChunk = CloneAsUint8Array(chunk);
2601
+ } catch (cloneE) {
2602
+ ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);
2603
+ ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);
2604
+ resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
2605
+ return;
2606
+ }
2607
+ if (!byobCanceled) ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
2608
+ ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);
2609
+ } else if (!byobCanceled) ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
2610
+ reading = false;
2611
+ if (readAgainForBranch1) pull1Algorithm();
2612
+ else if (readAgainForBranch2) pull2Algorithm();
2613
+ });
2614
+ },
2615
+ _closeSteps: (chunk) => {
2616
+ reading = false;
2617
+ const byobCanceled = forBranch2 ? canceled2 : canceled1;
2618
+ const otherCanceled = forBranch2 ? canceled1 : canceled2;
2619
+ if (!byobCanceled) ReadableByteStreamControllerClose(byobBranch._readableStreamController);
2620
+ if (!otherCanceled) ReadableByteStreamControllerClose(otherBranch._readableStreamController);
2621
+ if (chunk !== void 0) {
2622
+ if (!byobCanceled) ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
2623
+ if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);
2624
+ }
2625
+ if (!byobCanceled || !otherCanceled) resolveCancelPromise(void 0);
2626
+ },
2627
+ _errorSteps: () => {
2628
+ reading = false;
2629
+ }
2630
+ });
2631
+ }
2632
+ function pull1Algorithm() {
2633
+ if (reading) {
2634
+ readAgainForBranch1 = true;
2635
+ return promiseResolvedWith(void 0);
2636
+ }
2637
+ reading = true;
2638
+ const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);
2639
+ if (byobRequest === null) pullWithDefaultReader();
2640
+ else pullWithBYOBReader(byobRequest._view, false);
2641
+ return promiseResolvedWith(void 0);
2642
+ }
2643
+ function pull2Algorithm() {
2644
+ if (reading) {
2645
+ readAgainForBranch2 = true;
2646
+ return promiseResolvedWith(void 0);
2647
+ }
2648
+ reading = true;
2649
+ const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);
2650
+ if (byobRequest === null) pullWithDefaultReader();
2651
+ else pullWithBYOBReader(byobRequest._view, true);
2652
+ return promiseResolvedWith(void 0);
2653
+ }
2654
+ function cancel1Algorithm(reason) {
2655
+ canceled1 = true;
2656
+ reason1 = reason;
2657
+ if (canceled2) {
2658
+ const cancelResult = ReadableStreamCancel(stream, CreateArrayFromList([reason1, reason2]));
2659
+ resolveCancelPromise(cancelResult);
2660
+ }
2661
+ return cancelPromise;
2662
+ }
2663
+ function cancel2Algorithm(reason) {
2664
+ canceled2 = true;
2665
+ reason2 = reason;
2666
+ if (canceled1) {
2667
+ const cancelResult = ReadableStreamCancel(stream, CreateArrayFromList([reason1, reason2]));
2668
+ resolveCancelPromise(cancelResult);
2669
+ }
2670
+ return cancelPromise;
2671
+ }
2672
+ function startAlgorithm() {}
2673
+ branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);
2674
+ branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);
2675
+ forwardReaderError(reader);
2676
+ return [branch1, branch2];
2677
+ }
2678
+ function isReadableStreamLike(stream) {
2679
+ return typeIsObject(stream) && typeof stream.getReader !== "undefined";
2680
+ }
2681
+ function ReadableStreamFrom(source) {
2682
+ if (isReadableStreamLike(source)) return ReadableStreamFromDefaultReader(source.getReader());
2683
+ return ReadableStreamFromIterable(source);
2684
+ }
2685
+ function ReadableStreamFromIterable(asyncIterable) {
2686
+ let stream;
2687
+ const iteratorRecord = GetIterator(asyncIterable, "async");
2688
+ const startAlgorithm = noop;
2689
+ function pullAlgorithm() {
2690
+ let nextResult;
2691
+ try {
2692
+ nextResult = IteratorNext(iteratorRecord);
2693
+ } catch (e) {
2694
+ return promiseRejectedWith(e);
2695
+ }
2696
+ return transformPromiseWith(promiseResolvedWith(nextResult), (iterResult) => {
2697
+ if (!typeIsObject(iterResult)) throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");
2698
+ if (IteratorComplete(iterResult)) ReadableStreamDefaultControllerClose(stream._readableStreamController);
2699
+ else {
2700
+ const value = IteratorValue(iterResult);
2701
+ ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
2702
+ }
2703
+ });
2704
+ }
2705
+ function cancelAlgorithm(reason) {
2706
+ const iterator = iteratorRecord.iterator;
2707
+ let returnMethod;
2708
+ try {
2709
+ returnMethod = GetMethod(iterator, "return");
2710
+ } catch (e) {
2711
+ return promiseRejectedWith(e);
2712
+ }
2713
+ if (returnMethod === void 0) return promiseResolvedWith(void 0);
2714
+ let returnResult;
2715
+ try {
2716
+ returnResult = reflectCall(returnMethod, iterator, [reason]);
2717
+ } catch (e) {
2718
+ return promiseRejectedWith(e);
2719
+ }
2720
+ return transformPromiseWith(promiseResolvedWith(returnResult), (iterResult) => {
2721
+ if (!typeIsObject(iterResult)) throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object");
2722
+ });
2723
+ }
2724
+ stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
2725
+ return stream;
2726
+ }
2727
+ function ReadableStreamFromDefaultReader(reader) {
2728
+ let stream;
2729
+ const startAlgorithm = noop;
2730
+ function pullAlgorithm() {
2731
+ let readPromise;
2732
+ try {
2733
+ readPromise = reader.read();
2734
+ } catch (e) {
2735
+ return promiseRejectedWith(e);
2736
+ }
2737
+ return transformPromiseWith(readPromise, (readResult) => {
2738
+ if (!typeIsObject(readResult)) throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");
2739
+ if (readResult.done) ReadableStreamDefaultControllerClose(stream._readableStreamController);
2740
+ else {
2741
+ const value = readResult.value;
2742
+ ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
2743
+ }
2744
+ });
2745
+ }
2746
+ function cancelAlgorithm(reason) {
2747
+ try {
2748
+ return promiseResolvedWith(reader.cancel(reason));
2749
+ } catch (e) {
2750
+ return promiseRejectedWith(e);
2751
+ }
2752
+ }
2753
+ stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
2754
+ return stream;
2755
+ }
2756
+ function convertUnderlyingDefaultOrByteSource(source, context) {
2757
+ assertDictionary(source, context);
2758
+ const original = source;
2759
+ const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
2760
+ const cancel = original === null || original === void 0 ? void 0 : original.cancel;
2761
+ const pull = original === null || original === void 0 ? void 0 : original.pull;
2762
+ const start = original === null || original === void 0 ? void 0 : original.start;
2763
+ const type = original === null || original === void 0 ? void 0 : original.type;
2764
+ return {
2765
+ autoAllocateChunkSize: autoAllocateChunkSize === void 0 ? void 0 : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
2766
+ cancel: cancel === void 0 ? void 0 : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
2767
+ pull: pull === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
2768
+ start: start === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
2769
+ type: type === void 0 ? void 0 : convertReadableStreamType(type, `${context} has member 'type' that`)
2770
+ };
2771
+ }
2772
+ function convertUnderlyingSourceCancelCallback(fn, original, context) {
2773
+ assertFunction(fn, context);
2774
+ return (reason) => promiseCall(fn, original, [reason]);
2775
+ }
2776
+ function convertUnderlyingSourcePullCallback(fn, original, context) {
2777
+ assertFunction(fn, context);
2778
+ return (controller) => promiseCall(fn, original, [controller]);
2779
+ }
2780
+ function convertUnderlyingSourceStartCallback(fn, original, context) {
2781
+ assertFunction(fn, context);
2782
+ return (controller) => reflectCall(fn, original, [controller]);
2783
+ }
2784
+ function convertReadableStreamType(type, context) {
2785
+ type = `${type}`;
2786
+ if (type !== "bytes") throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
2787
+ return type;
2788
+ }
2789
+ function convertIteratorOptions(options, context) {
2790
+ assertDictionary(options, context);
2791
+ const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
2792
+ return { preventCancel: Boolean(preventCancel) };
2793
+ }
2794
+ function convertPipeOptions(options, context) {
2795
+ assertDictionary(options, context);
2796
+ const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
2797
+ const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
2798
+ const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
2799
+ const signal = options === null || options === void 0 ? void 0 : options.signal;
2800
+ if (signal !== void 0) assertAbortSignal(signal, `${context} has member 'signal' that`);
2801
+ return {
2802
+ preventAbort: Boolean(preventAbort),
2803
+ preventCancel: Boolean(preventCancel),
2804
+ preventClose: Boolean(preventClose),
2805
+ signal
2806
+ };
2807
+ }
2808
+ function assertAbortSignal(signal, context) {
2809
+ if (!isAbortSignal(signal)) throw new TypeError(`${context} is not an AbortSignal.`);
2810
+ }
2811
+ function convertReadableWritablePair(pair, context) {
2812
+ assertDictionary(pair, context);
2813
+ const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
2814
+ assertRequiredField(readable, "readable", "ReadableWritablePair");
2815
+ assertReadableStream(readable, `${context} has member 'readable' that`);
2816
+ const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
2817
+ assertRequiredField(writable, "writable", "ReadableWritablePair");
2818
+ assertWritableStream(writable, `${context} has member 'writable' that`);
2819
+ return {
2820
+ readable,
2821
+ writable
2822
+ };
2823
+ }
2824
+ /**
2825
+ * A readable stream represents a source of data, from which you can read.
2826
+ *
2827
+ * @public
2828
+ */
2829
+ class ReadableStream {
2830
+ constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
2831
+ if (rawUnderlyingSource === void 0) rawUnderlyingSource = null;
2832
+ else assertObject(rawUnderlyingSource, "First parameter");
2833
+ const strategy = convertQueuingStrategy(rawStrategy, "Second parameter");
2834
+ const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter");
2835
+ InitializeReadableStream(this);
2836
+ if (underlyingSource.type === "bytes") {
2837
+ if (strategy.size !== void 0) throw new RangeError("The strategy for a byte stream cannot have a size function");
2838
+ const highWaterMark = ExtractHighWaterMark(strategy, 0);
2839
+ SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
2840
+ } else {
2841
+ const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
2842
+ const highWaterMark = ExtractHighWaterMark(strategy, 1);
2843
+ SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
2844
+ }
2845
+ }
2846
+ /**
2847
+ * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
2848
+ */
2849
+ get locked() {
2850
+ if (!IsReadableStream(this)) throw streamBrandCheckException$1("locked");
2851
+ return IsReadableStreamLocked(this);
2852
+ }
2853
+ /**
2854
+ * Cancels the stream, signaling a loss of interest in the stream by a consumer.
2855
+ *
2856
+ * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
2857
+ * method, which might or might not use it.
2858
+ */
2859
+ cancel(reason = void 0) {
2860
+ if (!IsReadableStream(this)) return promiseRejectedWith(streamBrandCheckException$1("cancel"));
2861
+ if (IsReadableStreamLocked(this)) return promiseRejectedWith(/* @__PURE__ */ new TypeError("Cannot cancel a stream that already has a reader"));
2862
+ return ReadableStreamCancel(this, reason);
2863
+ }
2864
+ getReader(rawOptions = void 0) {
2865
+ if (!IsReadableStream(this)) throw streamBrandCheckException$1("getReader");
2866
+ if (convertReaderOptions(rawOptions, "First parameter").mode === void 0) return AcquireReadableStreamDefaultReader(this);
2867
+ return AcquireReadableStreamBYOBReader(this);
2868
+ }
2869
+ pipeThrough(rawTransform, rawOptions = {}) {
2870
+ if (!IsReadableStream(this)) throw streamBrandCheckException$1("pipeThrough");
2871
+ assertRequiredArgument(rawTransform, 1, "pipeThrough");
2872
+ const transform = convertReadableWritablePair(rawTransform, "First parameter");
2873
+ const options = convertPipeOptions(rawOptions, "Second parameter");
2874
+ if (IsReadableStreamLocked(this)) throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");
2875
+ if (IsWritableStreamLocked(transform.writable)) throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");
2876
+ setPromiseIsHandledToTrue(ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal));
2877
+ return transform.readable;
2878
+ }
2879
+ pipeTo(destination, rawOptions = {}) {
2880
+ if (!IsReadableStream(this)) return promiseRejectedWith(streamBrandCheckException$1("pipeTo"));
2881
+ if (destination === void 0) return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
2882
+ if (!IsWritableStream(destination)) return promiseRejectedWith(/* @__PURE__ */ new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
2883
+ let options;
2884
+ try {
2885
+ options = convertPipeOptions(rawOptions, "Second parameter");
2886
+ } catch (e) {
2887
+ return promiseRejectedWith(e);
2888
+ }
2889
+ if (IsReadableStreamLocked(this)) return promiseRejectedWith(/* @__PURE__ */ new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));
2890
+ if (IsWritableStreamLocked(destination)) return promiseRejectedWith(/* @__PURE__ */ new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));
2891
+ return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
2892
+ }
2893
+ /**
2894
+ * Tees this readable stream, returning a two-element array containing the two resulting branches as
2895
+ * new {@link ReadableStream} instances.
2896
+ *
2897
+ * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
2898
+ * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
2899
+ * propagated to the stream's underlying source.
2900
+ *
2901
+ * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
2902
+ * this could allow interference between the two branches.
2903
+ */
2904
+ tee() {
2905
+ if (!IsReadableStream(this)) throw streamBrandCheckException$1("tee");
2906
+ return CreateArrayFromList(ReadableStreamTee(this));
2907
+ }
2908
+ values(rawOptions = void 0) {
2909
+ if (!IsReadableStream(this)) throw streamBrandCheckException$1("values");
2910
+ const options = convertIteratorOptions(rawOptions, "First parameter");
2911
+ return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
2912
+ }
2913
+ [SymbolAsyncIterator](options) {
2914
+ return this.values(options);
2915
+ }
2916
+ /**
2917
+ * Creates a new ReadableStream wrapping the provided iterable or async iterable.
2918
+ *
2919
+ * This can be used to adapt various kinds of objects into a readable stream,
2920
+ * such as an array, an async generator, or a Node.js readable stream.
2921
+ */
2922
+ static from(asyncIterable) {
2923
+ return ReadableStreamFrom(asyncIterable);
2924
+ }
2925
+ }
2926
+ Object.defineProperties(ReadableStream, { from: { enumerable: true } });
2927
+ Object.defineProperties(ReadableStream.prototype, {
2928
+ cancel: { enumerable: true },
2929
+ getReader: { enumerable: true },
2930
+ pipeThrough: { enumerable: true },
2931
+ pipeTo: { enumerable: true },
2932
+ tee: { enumerable: true },
2933
+ values: { enumerable: true },
2934
+ locked: { enumerable: true }
2935
+ });
2936
+ setFunctionName(ReadableStream.from, "from");
2937
+ setFunctionName(ReadableStream.prototype.cancel, "cancel");
2938
+ setFunctionName(ReadableStream.prototype.getReader, "getReader");
2939
+ setFunctionName(ReadableStream.prototype.pipeThrough, "pipeThrough");
2940
+ setFunctionName(ReadableStream.prototype.pipeTo, "pipeTo");
2941
+ setFunctionName(ReadableStream.prototype.tee, "tee");
2942
+ setFunctionName(ReadableStream.prototype.values, "values");
2943
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {
2944
+ value: "ReadableStream",
2945
+ configurable: true
2946
+ });
2947
+ Object.defineProperty(ReadableStream.prototype, SymbolAsyncIterator, {
2948
+ value: ReadableStream.prototype.values,
2949
+ writable: true,
2950
+ configurable: true
2951
+ });
2952
+ function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
2953
+ const stream = Object.create(ReadableStream.prototype);
2954
+ InitializeReadableStream(stream);
2955
+ SetUpReadableStreamDefaultController(stream, Object.create(ReadableStreamDefaultController.prototype), startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
2956
+ return stream;
2957
+ }
2958
+ function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
2959
+ const stream = Object.create(ReadableStream.prototype);
2960
+ InitializeReadableStream(stream);
2961
+ SetUpReadableByteStreamController(stream, Object.create(ReadableByteStreamController.prototype), startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0);
2962
+ return stream;
2963
+ }
2964
+ function InitializeReadableStream(stream) {
2965
+ stream._state = "readable";
2966
+ stream._reader = void 0;
2967
+ stream._storedError = void 0;
2968
+ stream._disturbed = false;
2969
+ }
2970
+ function IsReadableStream(x) {
2971
+ if (!typeIsObject(x)) return false;
2972
+ if (!Object.prototype.hasOwnProperty.call(x, "_readableStreamController")) return false;
2973
+ return x instanceof ReadableStream;
2974
+ }
2975
+ function IsReadableStreamLocked(stream) {
2976
+ if (stream._reader === void 0) return false;
2977
+ return true;
2978
+ }
2979
+ function ReadableStreamCancel(stream, reason) {
2980
+ stream._disturbed = true;
2981
+ if (stream._state === "closed") return promiseResolvedWith(void 0);
2982
+ if (stream._state === "errored") return promiseRejectedWith(stream._storedError);
2983
+ ReadableStreamClose(stream);
2984
+ const reader = stream._reader;
2985
+ if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) {
2986
+ const readIntoRequests = reader._readIntoRequests;
2987
+ reader._readIntoRequests = new SimpleQueue();
2988
+ readIntoRequests.forEach((readIntoRequest) => {
2989
+ readIntoRequest._closeSteps(void 0);
2990
+ });
2991
+ }
2992
+ return transformPromiseWith(stream._readableStreamController[CancelSteps](reason), noop);
2993
+ }
2994
+ function ReadableStreamClose(stream) {
2995
+ stream._state = "closed";
2996
+ const reader = stream._reader;
2997
+ if (reader === void 0) return;
2998
+ defaultReaderClosedPromiseResolve(reader);
2999
+ if (IsReadableStreamDefaultReader(reader)) {
3000
+ const readRequests = reader._readRequests;
3001
+ reader._readRequests = new SimpleQueue();
3002
+ readRequests.forEach((readRequest) => {
3003
+ readRequest._closeSteps();
3004
+ });
3005
+ }
3006
+ }
3007
+ function ReadableStreamError(stream, e) {
3008
+ stream._state = "errored";
3009
+ stream._storedError = e;
3010
+ const reader = stream._reader;
3011
+ if (reader === void 0) return;
3012
+ defaultReaderClosedPromiseReject(reader, e);
3013
+ if (IsReadableStreamDefaultReader(reader)) ReadableStreamDefaultReaderErrorReadRequests(reader, e);
3014
+ else ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
3015
+ }
3016
+ function streamBrandCheckException$1(name) {
3017
+ return /* @__PURE__ */ new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
3018
+ }
3019
+ function convertQueuingStrategyInit(init, context) {
3020
+ assertDictionary(init, context);
3021
+ const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
3022
+ assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit");
3023
+ return { highWaterMark: convertUnrestrictedDouble(highWaterMark) };
3024
+ }
3025
+ const byteLengthSizeFunction = (chunk) => {
3026
+ return chunk.byteLength;
3027
+ };
3028
+ setFunctionName(byteLengthSizeFunction, "size");
3029
+ /**
3030
+ * A queuing strategy that counts the number of bytes in each chunk.
3031
+ *
3032
+ * @public
3033
+ */
3034
+ class ByteLengthQueuingStrategy {
3035
+ constructor(options) {
3036
+ assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy");
3037
+ options = convertQueuingStrategyInit(options, "First parameter");
3038
+ this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
3039
+ }
3040
+ /**
3041
+ * Returns the high water mark provided to the constructor.
3042
+ */
3043
+ get highWaterMark() {
3044
+ if (!IsByteLengthQueuingStrategy(this)) throw byteLengthBrandCheckException("highWaterMark");
3045
+ return this._byteLengthQueuingStrategyHighWaterMark;
3046
+ }
3047
+ /**
3048
+ * Measures the size of `chunk` by returning the value of its `byteLength` property.
3049
+ */
3050
+ get size() {
3051
+ if (!IsByteLengthQueuingStrategy(this)) throw byteLengthBrandCheckException("size");
3052
+ return byteLengthSizeFunction;
3053
+ }
3054
+ }
3055
+ Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
3056
+ highWaterMark: { enumerable: true },
3057
+ size: { enumerable: true }
3058
+ });
3059
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {
3060
+ value: "ByteLengthQueuingStrategy",
3061
+ configurable: true
3062
+ });
3063
+ function byteLengthBrandCheckException(name) {
3064
+ return /* @__PURE__ */ new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
3065
+ }
3066
+ function IsByteLengthQueuingStrategy(x) {
3067
+ if (!typeIsObject(x)) return false;
3068
+ if (!Object.prototype.hasOwnProperty.call(x, "_byteLengthQueuingStrategyHighWaterMark")) return false;
3069
+ return x instanceof ByteLengthQueuingStrategy;
3070
+ }
3071
+ const countSizeFunction = () => {
3072
+ return 1;
3073
+ };
3074
+ setFunctionName(countSizeFunction, "size");
3075
+ /**
3076
+ * A queuing strategy that counts the number of chunks.
3077
+ *
3078
+ * @public
3079
+ */
3080
+ class CountQueuingStrategy {
3081
+ constructor(options) {
3082
+ assertRequiredArgument(options, 1, "CountQueuingStrategy");
3083
+ options = convertQueuingStrategyInit(options, "First parameter");
3084
+ this._countQueuingStrategyHighWaterMark = options.highWaterMark;
3085
+ }
3086
+ /**
3087
+ * Returns the high water mark provided to the constructor.
3088
+ */
3089
+ get highWaterMark() {
3090
+ if (!IsCountQueuingStrategy(this)) throw countBrandCheckException("highWaterMark");
3091
+ return this._countQueuingStrategyHighWaterMark;
3092
+ }
3093
+ /**
3094
+ * Measures the size of `chunk` by always returning 1.
3095
+ * This ensures that the total queue size is a count of the number of chunks in the queue.
3096
+ */
3097
+ get size() {
3098
+ if (!IsCountQueuingStrategy(this)) throw countBrandCheckException("size");
3099
+ return countSizeFunction;
3100
+ }
3101
+ }
3102
+ Object.defineProperties(CountQueuingStrategy.prototype, {
3103
+ highWaterMark: { enumerable: true },
3104
+ size: { enumerable: true }
3105
+ });
3106
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {
3107
+ value: "CountQueuingStrategy",
3108
+ configurable: true
3109
+ });
3110
+ function countBrandCheckException(name) {
3111
+ return /* @__PURE__ */ new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
3112
+ }
3113
+ function IsCountQueuingStrategy(x) {
3114
+ if (!typeIsObject(x)) return false;
3115
+ if (!Object.prototype.hasOwnProperty.call(x, "_countQueuingStrategyHighWaterMark")) return false;
3116
+ return x instanceof CountQueuingStrategy;
3117
+ }
3118
+ function convertTransformer(original, context) {
3119
+ assertDictionary(original, context);
3120
+ const cancel = original === null || original === void 0 ? void 0 : original.cancel;
3121
+ const flush = original === null || original === void 0 ? void 0 : original.flush;
3122
+ const readableType = original === null || original === void 0 ? void 0 : original.readableType;
3123
+ const start = original === null || original === void 0 ? void 0 : original.start;
3124
+ const transform = original === null || original === void 0 ? void 0 : original.transform;
3125
+ const writableType = original === null || original === void 0 ? void 0 : original.writableType;
3126
+ return {
3127
+ cancel: cancel === void 0 ? void 0 : convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`),
3128
+ flush: flush === void 0 ? void 0 : convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
3129
+ readableType,
3130
+ start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
3131
+ transform: transform === void 0 ? void 0 : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
3132
+ writableType
3133
+ };
3134
+ }
3135
+ function convertTransformerFlushCallback(fn, original, context) {
3136
+ assertFunction(fn, context);
3137
+ return (controller) => promiseCall(fn, original, [controller]);
3138
+ }
3139
+ function convertTransformerStartCallback(fn, original, context) {
3140
+ assertFunction(fn, context);
3141
+ return (controller) => reflectCall(fn, original, [controller]);
3142
+ }
3143
+ function convertTransformerTransformCallback(fn, original, context) {
3144
+ assertFunction(fn, context);
3145
+ return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
3146
+ }
3147
+ function convertTransformerCancelCallback(fn, original, context) {
3148
+ assertFunction(fn, context);
3149
+ return (reason) => promiseCall(fn, original, [reason]);
3150
+ }
3151
+ /**
3152
+ * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
3153
+ * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
3154
+ * In a manner specific to the transform stream in question, writes to the writable side result in new data being
3155
+ * made available for reading from the readable side.
3156
+ *
3157
+ * @public
3158
+ */
3159
+ class TransformStream {
3160
+ constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
3161
+ if (rawTransformer === void 0) rawTransformer = null;
3162
+ const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter");
3163
+ const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter");
3164
+ const transformer = convertTransformer(rawTransformer, "First parameter");
3165
+ if (transformer.readableType !== void 0) throw new RangeError("Invalid readableType specified");
3166
+ if (transformer.writableType !== void 0) throw new RangeError("Invalid writableType specified");
3167
+ const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
3168
+ const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
3169
+ const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
3170
+ const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
3171
+ let startPromise_resolve;
3172
+ const startPromise = newPromise((resolve) => {
3173
+ startPromise_resolve = resolve;
3174
+ });
3175
+ InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
3176
+ SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
3177
+ if (transformer.start !== void 0) startPromise_resolve(transformer.start(this._transformStreamController));
3178
+ else startPromise_resolve(void 0);
3179
+ }
3180
+ /**
3181
+ * The readable side of the transform stream.
3182
+ */
3183
+ get readable() {
3184
+ if (!IsTransformStream(this)) throw streamBrandCheckException("readable");
3185
+ return this._readable;
3186
+ }
3187
+ /**
3188
+ * The writable side of the transform stream.
3189
+ */
3190
+ get writable() {
3191
+ if (!IsTransformStream(this)) throw streamBrandCheckException("writable");
3192
+ return this._writable;
3193
+ }
3194
+ }
3195
+ Object.defineProperties(TransformStream.prototype, {
3196
+ readable: { enumerable: true },
3197
+ writable: { enumerable: true }
3198
+ });
3199
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {
3200
+ value: "TransformStream",
3201
+ configurable: true
3202
+ });
3203
+ function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
3204
+ function startAlgorithm() {
3205
+ return startPromise;
3206
+ }
3207
+ function writeAlgorithm(chunk) {
3208
+ return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
3209
+ }
3210
+ function abortAlgorithm(reason) {
3211
+ return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
3212
+ }
3213
+ function closeAlgorithm() {
3214
+ return TransformStreamDefaultSinkCloseAlgorithm(stream);
3215
+ }
3216
+ stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
3217
+ function pullAlgorithm() {
3218
+ return TransformStreamDefaultSourcePullAlgorithm(stream);
3219
+ }
3220
+ function cancelAlgorithm(reason) {
3221
+ return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);
3222
+ }
3223
+ stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
3224
+ stream._backpressure = void 0;
3225
+ stream._backpressureChangePromise = void 0;
3226
+ stream._backpressureChangePromise_resolve = void 0;
3227
+ TransformStreamSetBackpressure(stream, true);
3228
+ stream._transformStreamController = void 0;
3229
+ }
3230
+ function IsTransformStream(x) {
3231
+ if (!typeIsObject(x)) return false;
3232
+ if (!Object.prototype.hasOwnProperty.call(x, "_transformStreamController")) return false;
3233
+ return x instanceof TransformStream;
3234
+ }
3235
+ function TransformStreamError(stream, e) {
3236
+ ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
3237
+ TransformStreamErrorWritableAndUnblockWrite(stream, e);
3238
+ }
3239
+ function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
3240
+ TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
3241
+ WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
3242
+ TransformStreamUnblockWrite(stream);
3243
+ }
3244
+ function TransformStreamUnblockWrite(stream) {
3245
+ if (stream._backpressure) TransformStreamSetBackpressure(stream, false);
3246
+ }
3247
+ function TransformStreamSetBackpressure(stream, backpressure) {
3248
+ if (stream._backpressureChangePromise !== void 0) stream._backpressureChangePromise_resolve();
3249
+ stream._backpressureChangePromise = newPromise((resolve) => {
3250
+ stream._backpressureChangePromise_resolve = resolve;
3251
+ });
3252
+ stream._backpressure = backpressure;
3253
+ }
3254
+ /**
3255
+ * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
3256
+ *
3257
+ * @public
3258
+ */
3259
+ class TransformStreamDefaultController {
3260
+ constructor() {
3261
+ throw new TypeError("Illegal constructor");
3262
+ }
3263
+ /**
3264
+ * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
3265
+ */
3266
+ get desiredSize() {
3267
+ if (!IsTransformStreamDefaultController(this)) throw defaultControllerBrandCheckException("desiredSize");
3268
+ const readableController = this._controlledTransformStream._readable._readableStreamController;
3269
+ return ReadableStreamDefaultControllerGetDesiredSize(readableController);
3270
+ }
3271
+ enqueue(chunk = void 0) {
3272
+ if (!IsTransformStreamDefaultController(this)) throw defaultControllerBrandCheckException("enqueue");
3273
+ TransformStreamDefaultControllerEnqueue(this, chunk);
3274
+ }
3275
+ /**
3276
+ * Errors both the readable side and the writable side of the controlled transform stream, making all future
3277
+ * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
3278
+ */
3279
+ error(reason = void 0) {
3280
+ if (!IsTransformStreamDefaultController(this)) throw defaultControllerBrandCheckException("error");
3281
+ TransformStreamDefaultControllerError(this, reason);
3282
+ }
3283
+ /**
3284
+ * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
3285
+ * transformer only needs to consume a portion of the chunks written to the writable side.
3286
+ */
3287
+ terminate() {
3288
+ if (!IsTransformStreamDefaultController(this)) throw defaultControllerBrandCheckException("terminate");
3289
+ TransformStreamDefaultControllerTerminate(this);
3290
+ }
3291
+ }
3292
+ Object.defineProperties(TransformStreamDefaultController.prototype, {
3293
+ enqueue: { enumerable: true },
3294
+ error: { enumerable: true },
3295
+ terminate: { enumerable: true },
3296
+ desiredSize: { enumerable: true }
3297
+ });
3298
+ setFunctionName(TransformStreamDefaultController.prototype.enqueue, "enqueue");
3299
+ setFunctionName(TransformStreamDefaultController.prototype.error, "error");
3300
+ setFunctionName(TransformStreamDefaultController.prototype.terminate, "terminate");
3301
+ if (typeof Symbol.toStringTag === "symbol") Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {
3302
+ value: "TransformStreamDefaultController",
3303
+ configurable: true
3304
+ });
3305
+ function IsTransformStreamDefaultController(x) {
3306
+ if (!typeIsObject(x)) return false;
3307
+ if (!Object.prototype.hasOwnProperty.call(x, "_controlledTransformStream")) return false;
3308
+ return x instanceof TransformStreamDefaultController;
3309
+ }
3310
+ function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
3311
+ controller._controlledTransformStream = stream;
3312
+ stream._transformStreamController = controller;
3313
+ controller._transformAlgorithm = transformAlgorithm;
3314
+ controller._flushAlgorithm = flushAlgorithm;
3315
+ controller._cancelAlgorithm = cancelAlgorithm;
3316
+ controller._finishPromise = void 0;
3317
+ controller._finishPromise_resolve = void 0;
3318
+ controller._finishPromise_reject = void 0;
3319
+ }
3320
+ function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
3321
+ const controller = Object.create(TransformStreamDefaultController.prototype);
3322
+ let transformAlgorithm;
3323
+ let flushAlgorithm;
3324
+ let cancelAlgorithm;
3325
+ if (transformer.transform !== void 0) transformAlgorithm = (chunk) => transformer.transform(chunk, controller);
3326
+ else transformAlgorithm = (chunk) => {
3327
+ try {
3328
+ TransformStreamDefaultControllerEnqueue(controller, chunk);
3329
+ return promiseResolvedWith(void 0);
3330
+ } catch (transformResultE) {
3331
+ return promiseRejectedWith(transformResultE);
3332
+ }
3333
+ };
3334
+ if (transformer.flush !== void 0) flushAlgorithm = () => transformer.flush(controller);
3335
+ else flushAlgorithm = () => promiseResolvedWith(void 0);
3336
+ if (transformer.cancel !== void 0) cancelAlgorithm = (reason) => transformer.cancel(reason);
3337
+ else cancelAlgorithm = () => promiseResolvedWith(void 0);
3338
+ SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
3339
+ }
3340
+ function TransformStreamDefaultControllerClearAlgorithms(controller) {
3341
+ controller._transformAlgorithm = void 0;
3342
+ controller._flushAlgorithm = void 0;
3343
+ controller._cancelAlgorithm = void 0;
3344
+ }
3345
+ function TransformStreamDefaultControllerEnqueue(controller, chunk) {
3346
+ const stream = controller._controlledTransformStream;
3347
+ const readableController = stream._readable._readableStreamController;
3348
+ if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) throw new TypeError("Readable side is not in a state that permits enqueue");
3349
+ try {
3350
+ ReadableStreamDefaultControllerEnqueue(readableController, chunk);
3351
+ } catch (e) {
3352
+ TransformStreamErrorWritableAndUnblockWrite(stream, e);
3353
+ throw stream._readable._storedError;
3354
+ }
3355
+ if (ReadableStreamDefaultControllerHasBackpressure(readableController) !== stream._backpressure) TransformStreamSetBackpressure(stream, true);
3356
+ }
3357
+ function TransformStreamDefaultControllerError(controller, e) {
3358
+ TransformStreamError(controller._controlledTransformStream, e);
3359
+ }
3360
+ function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
3361
+ return transformPromiseWith(controller._transformAlgorithm(chunk), void 0, (r) => {
3362
+ TransformStreamError(controller._controlledTransformStream, r);
3363
+ throw r;
3364
+ });
3365
+ }
3366
+ function TransformStreamDefaultControllerTerminate(controller) {
3367
+ const stream = controller._controlledTransformStream;
3368
+ const readableController = stream._readable._readableStreamController;
3369
+ ReadableStreamDefaultControllerClose(readableController);
3370
+ TransformStreamErrorWritableAndUnblockWrite(stream, /* @__PURE__ */ new TypeError("TransformStream terminated"));
3371
+ }
3372
+ function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
3373
+ const controller = stream._transformStreamController;
3374
+ if (stream._backpressure) {
3375
+ const backpressureChangePromise = stream._backpressureChangePromise;
3376
+ return transformPromiseWith(backpressureChangePromise, () => {
3377
+ const writable = stream._writable;
3378
+ if (writable._state === "erroring") throw writable._storedError;
3379
+ return TransformStreamDefaultControllerPerformTransform(controller, chunk);
3380
+ });
3381
+ }
3382
+ return TransformStreamDefaultControllerPerformTransform(controller, chunk);
3383
+ }
3384
+ function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
3385
+ const controller = stream._transformStreamController;
3386
+ if (controller._finishPromise !== void 0) return controller._finishPromise;
3387
+ const readable = stream._readable;
3388
+ controller._finishPromise = newPromise((resolve, reject) => {
3389
+ controller._finishPromise_resolve = resolve;
3390
+ controller._finishPromise_reject = reject;
3391
+ });
3392
+ const cancelPromise = controller._cancelAlgorithm(reason);
3393
+ TransformStreamDefaultControllerClearAlgorithms(controller);
3394
+ uponPromise(cancelPromise, () => {
3395
+ if (readable._state === "errored") defaultControllerFinishPromiseReject(controller, readable._storedError);
3396
+ else {
3397
+ ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
3398
+ defaultControllerFinishPromiseResolve(controller);
3399
+ }
3400
+ return null;
3401
+ }, (r) => {
3402
+ ReadableStreamDefaultControllerError(readable._readableStreamController, r);
3403
+ defaultControllerFinishPromiseReject(controller, r);
3404
+ return null;
3405
+ });
3406
+ return controller._finishPromise;
3407
+ }
3408
+ function TransformStreamDefaultSinkCloseAlgorithm(stream) {
3409
+ const controller = stream._transformStreamController;
3410
+ if (controller._finishPromise !== void 0) return controller._finishPromise;
3411
+ const readable = stream._readable;
3412
+ controller._finishPromise = newPromise((resolve, reject) => {
3413
+ controller._finishPromise_resolve = resolve;
3414
+ controller._finishPromise_reject = reject;
3415
+ });
3416
+ const flushPromise = controller._flushAlgorithm();
3417
+ TransformStreamDefaultControllerClearAlgorithms(controller);
3418
+ uponPromise(flushPromise, () => {
3419
+ if (readable._state === "errored") defaultControllerFinishPromiseReject(controller, readable._storedError);
3420
+ else {
3421
+ ReadableStreamDefaultControllerClose(readable._readableStreamController);
3422
+ defaultControllerFinishPromiseResolve(controller);
3423
+ }
3424
+ return null;
3425
+ }, (r) => {
3426
+ ReadableStreamDefaultControllerError(readable._readableStreamController, r);
3427
+ defaultControllerFinishPromiseReject(controller, r);
3428
+ return null;
3429
+ });
3430
+ return controller._finishPromise;
3431
+ }
3432
+ function TransformStreamDefaultSourcePullAlgorithm(stream) {
3433
+ TransformStreamSetBackpressure(stream, false);
3434
+ return stream._backpressureChangePromise;
3435
+ }
3436
+ function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) {
3437
+ const controller = stream._transformStreamController;
3438
+ if (controller._finishPromise !== void 0) return controller._finishPromise;
3439
+ const writable = stream._writable;
3440
+ controller._finishPromise = newPromise((resolve, reject) => {
3441
+ controller._finishPromise_resolve = resolve;
3442
+ controller._finishPromise_reject = reject;
3443
+ });
3444
+ const cancelPromise = controller._cancelAlgorithm(reason);
3445
+ TransformStreamDefaultControllerClearAlgorithms(controller);
3446
+ uponPromise(cancelPromise, () => {
3447
+ if (writable._state === "errored") defaultControllerFinishPromiseReject(controller, writable._storedError);
3448
+ else {
3449
+ WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
3450
+ TransformStreamUnblockWrite(stream);
3451
+ defaultControllerFinishPromiseResolve(controller);
3452
+ }
3453
+ return null;
3454
+ }, (r) => {
3455
+ WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);
3456
+ TransformStreamUnblockWrite(stream);
3457
+ defaultControllerFinishPromiseReject(controller, r);
3458
+ return null;
3459
+ });
3460
+ return controller._finishPromise;
3461
+ }
3462
+ function defaultControllerBrandCheckException(name) {
3463
+ return /* @__PURE__ */ new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
3464
+ }
3465
+ function defaultControllerFinishPromiseResolve(controller) {
3466
+ if (controller._finishPromise_resolve === void 0) return;
3467
+ controller._finishPromise_resolve();
3468
+ controller._finishPromise_resolve = void 0;
3469
+ controller._finishPromise_reject = void 0;
3470
+ }
3471
+ function defaultControllerFinishPromiseReject(controller, reason) {
3472
+ if (controller._finishPromise_reject === void 0) return;
3473
+ setPromiseIsHandledToTrue(controller._finishPromise);
3474
+ controller._finishPromise_reject(reason);
3475
+ controller._finishPromise_resolve = void 0;
3476
+ controller._finishPromise_reject = void 0;
3477
+ }
3478
+ function streamBrandCheckException(name) {
3479
+ return /* @__PURE__ */ new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
3480
+ }
3481
+ exports$1.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy;
3482
+ exports$1.CountQueuingStrategy = CountQueuingStrategy;
3483
+ exports$1.ReadableByteStreamController = ReadableByteStreamController;
3484
+ exports$1.ReadableStream = ReadableStream;
3485
+ exports$1.ReadableStreamBYOBReader = ReadableStreamBYOBReader;
3486
+ exports$1.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
3487
+ exports$1.ReadableStreamDefaultController = ReadableStreamDefaultController;
3488
+ exports$1.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
3489
+ exports$1.TransformStream = TransformStream;
3490
+ exports$1.TransformStreamDefaultController = TransformStreamDefaultController;
3491
+ exports$1.WritableStream = WritableStream;
3492
+ exports$1.WritableStreamDefaultController = WritableStreamDefaultController;
3493
+ exports$1.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
3494
+ }));
3495
+ }));
3496
+
3497
+ //#endregion
3498
+ //#region ../../node_modules/.bun/fetch-blob@3.2.0/node_modules/fetch-blob/streams.cjs
3499
+ var require_streams = /* @__PURE__ */ __commonJSMin((() => {
3500
+ /* c8 ignore start */
3501
+ const POOL_SIZE = 65536;
3502
+ if (!globalThis.ReadableStream) try {
3503
+ const process = __require("node:process");
3504
+ const { emitWarning } = process;
3505
+ try {
3506
+ process.emitWarning = () => {};
3507
+ Object.assign(globalThis, __require("node:stream/web"));
3508
+ process.emitWarning = emitWarning;
3509
+ } catch (error) {
3510
+ process.emitWarning = emitWarning;
3511
+ throw error;
3512
+ }
3513
+ } catch (error) {
3514
+ Object.assign(globalThis, require_ponyfill_es2018());
3515
+ }
3516
+ try {
3517
+ const { Blob } = __require("buffer");
3518
+ if (Blob && !Blob.prototype.stream) Blob.prototype.stream = function name(params) {
3519
+ let position = 0;
3520
+ const blob = this;
3521
+ return new ReadableStream({
3522
+ type: "bytes",
3523
+ async pull(ctrl) {
3524
+ const buffer = await blob.slice(position, Math.min(blob.size, position + POOL_SIZE)).arrayBuffer();
3525
+ position += buffer.byteLength;
3526
+ ctrl.enqueue(new Uint8Array(buffer));
3527
+ if (position === blob.size) ctrl.close();
3528
+ }
3529
+ });
3530
+ };
3531
+ } catch (error) {}
3532
+ }));
3533
+ /* c8 ignore end */
3534
+
3535
+ //#endregion
3536
+ //#region ../../node_modules/.bun/fetch-blob@3.2.0/node_modules/fetch-blob/index.js
3537
+ /** @param {(Blob | Uint8Array)[]} parts */
3538
+ async function* toIterator(parts, clone = true) {
3539
+ for (const part of parts) if ("stream" in part) yield* part.stream();
3540
+ else if (ArrayBuffer.isView(part)) if (clone) {
3541
+ let position = part.byteOffset;
3542
+ const end = part.byteOffset + part.byteLength;
3543
+ while (position !== end) {
3544
+ const size = Math.min(end - position, POOL_SIZE);
3545
+ const chunk = part.buffer.slice(position, position + size);
3546
+ position += chunk.byteLength;
3547
+ yield new Uint8Array(chunk);
3548
+ }
3549
+ } else yield part;
3550
+ else {
3551
+ let position = 0, b = part;
3552
+ while (position !== b.size) {
3553
+ const buffer = await b.slice(position, Math.min(b.size, position + POOL_SIZE)).arrayBuffer();
3554
+ position += buffer.byteLength;
3555
+ yield new Uint8Array(buffer);
3556
+ }
3557
+ }
3558
+ }
3559
+ var import_streams, POOL_SIZE, _Blob, Blob;
3560
+ var init_fetch_blob = __esmMin((() => {
3561
+ import_streams = require_streams();
3562
+ POOL_SIZE = 65536;
3563
+ _Blob = class Blob {
3564
+ /** @type {Array.<(Blob|Uint8Array)>} */
3565
+ #parts = [];
3566
+ #type = "";
3567
+ #size = 0;
3568
+ #endings = "transparent";
3569
+ /**
3570
+ * The Blob() constructor returns a new Blob object. The content
3571
+ * of the blob consists of the concatenation of the values given
3572
+ * in the parameter array.
3573
+ *
3574
+ * @param {*} blobParts
3575
+ * @param {{ type?: string, endings?: string }} [options]
3576
+ */
3577
+ constructor(blobParts = [], options = {}) {
3578
+ if (typeof blobParts !== "object" || blobParts === null) throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence.");
3579
+ if (typeof blobParts[Symbol.iterator] !== "function") throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property.");
3580
+ if (typeof options !== "object" && typeof options !== "function") throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary.");
3581
+ if (options === null) options = {};
3582
+ const encoder = new TextEncoder();
3583
+ for (const element of blobParts) {
3584
+ let part;
3585
+ if (ArrayBuffer.isView(element)) part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength));
3586
+ else if (element instanceof ArrayBuffer) part = new Uint8Array(element.slice(0));
3587
+ else if (element instanceof Blob) part = element;
3588
+ else part = encoder.encode(`${element}`);
3589
+ this.#size += ArrayBuffer.isView(part) ? part.byteLength : part.size;
3590
+ this.#parts.push(part);
3591
+ }
3592
+ this.#endings = `${options.endings === void 0 ? "transparent" : options.endings}`;
3593
+ const type = options.type === void 0 ? "" : String(options.type);
3594
+ this.#type = /^[\x20-\x7E]*$/.test(type) ? type : "";
3595
+ }
3596
+ /**
3597
+ * The Blob interface's size property returns the
3598
+ * size of the Blob in bytes.
3599
+ */
3600
+ get size() {
3601
+ return this.#size;
3602
+ }
3603
+ /**
3604
+ * The type property of a Blob object returns the MIME type of the file.
3605
+ */
3606
+ get type() {
3607
+ return this.#type;
3608
+ }
3609
+ /**
3610
+ * The text() method in the Blob interface returns a Promise
3611
+ * that resolves with a string containing the contents of
3612
+ * the blob, interpreted as UTF-8.
3613
+ *
3614
+ * @return {Promise<string>}
3615
+ */
3616
+ async text() {
3617
+ const decoder = new TextDecoder();
3618
+ let str = "";
3619
+ for await (const part of toIterator(this.#parts, false)) str += decoder.decode(part, { stream: true });
3620
+ str += decoder.decode();
3621
+ return str;
3622
+ }
3623
+ /**
3624
+ * The arrayBuffer() method in the Blob interface returns a
3625
+ * Promise that resolves with the contents of the blob as
3626
+ * binary data contained in an ArrayBuffer.
3627
+ *
3628
+ * @return {Promise<ArrayBuffer>}
3629
+ */
3630
+ async arrayBuffer() {
3631
+ const data = new Uint8Array(this.size);
3632
+ let offset = 0;
3633
+ for await (const chunk of toIterator(this.#parts, false)) {
3634
+ data.set(chunk, offset);
3635
+ offset += chunk.length;
3636
+ }
3637
+ return data.buffer;
3638
+ }
3639
+ stream() {
3640
+ const it = toIterator(this.#parts, true);
3641
+ return new globalThis.ReadableStream({
3642
+ type: "bytes",
3643
+ async pull(ctrl) {
3644
+ const chunk = await it.next();
3645
+ chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value);
3646
+ },
3647
+ async cancel() {
3648
+ await it.return();
3649
+ }
3650
+ });
3651
+ }
3652
+ /**
3653
+ * The Blob interface's slice() method creates and returns a
3654
+ * new Blob object which contains data from a subset of the
3655
+ * blob on which it's called.
3656
+ *
3657
+ * @param {number} [start]
3658
+ * @param {number} [end]
3659
+ * @param {string} [type]
3660
+ */
3661
+ slice(start = 0, end = this.size, type = "") {
3662
+ const { size } = this;
3663
+ let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size);
3664
+ let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size);
3665
+ const span = Math.max(relativeEnd - relativeStart, 0);
3666
+ const parts = this.#parts;
3667
+ const blobParts = [];
3668
+ let added = 0;
3669
+ for (const part of parts) {
3670
+ if (added >= span) break;
3671
+ const size = ArrayBuffer.isView(part) ? part.byteLength : part.size;
3672
+ if (relativeStart && size <= relativeStart) {
3673
+ relativeStart -= size;
3674
+ relativeEnd -= size;
3675
+ } else {
3676
+ let chunk;
3677
+ if (ArrayBuffer.isView(part)) {
3678
+ chunk = part.subarray(relativeStart, Math.min(size, relativeEnd));
3679
+ added += chunk.byteLength;
3680
+ } else {
3681
+ chunk = part.slice(relativeStart, Math.min(size, relativeEnd));
3682
+ added += chunk.size;
3683
+ }
3684
+ relativeEnd -= size;
3685
+ blobParts.push(chunk);
3686
+ relativeStart = 0;
3687
+ }
3688
+ }
3689
+ const blob = new Blob([], { type: String(type).toLowerCase() });
3690
+ blob.#size = span;
3691
+ blob.#parts = blobParts;
3692
+ return blob;
3693
+ }
3694
+ get [Symbol.toStringTag]() {
3695
+ return "Blob";
3696
+ }
3697
+ static [Symbol.hasInstance](object) {
3698
+ return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]);
3699
+ }
3700
+ };
3701
+ Object.defineProperties(_Blob.prototype, {
3702
+ size: { enumerable: true },
3703
+ type: { enumerable: true },
3704
+ slice: { enumerable: true }
3705
+ });
3706
+ Blob = _Blob;
3707
+ }));
3708
+
3709
+ //#endregion
3710
+ //#region ../../node_modules/.bun/fetch-blob@3.2.0/node_modules/fetch-blob/file.js
3711
+ var _File, File;
3712
+ var init_file = __esmMin((() => {
3713
+ init_fetch_blob();
3714
+ _File = class File extends Blob {
3715
+ #lastModified = 0;
3716
+ #name = "";
3717
+ /**
3718
+ * @param {*[]} fileBits
3719
+ * @param {string} fileName
3720
+ * @param {{lastModified?: number, type?: string}} options
3721
+ */ constructor(fileBits, fileName, options = {}) {
3722
+ if (arguments.length < 2) throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`);
3723
+ super(fileBits, options);
3724
+ if (options === null) options = {};
3725
+ const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified);
3726
+ if (!Number.isNaN(lastModified)) this.#lastModified = lastModified;
3727
+ this.#name = String(fileName);
3728
+ }
3729
+ get name() {
3730
+ return this.#name;
3731
+ }
3732
+ get lastModified() {
3733
+ return this.#lastModified;
3734
+ }
3735
+ get [Symbol.toStringTag]() {
3736
+ return "File";
3737
+ }
3738
+ static [Symbol.hasInstance](object) {
3739
+ return !!object && object instanceof Blob && /^(File)$/.test(object[Symbol.toStringTag]);
3740
+ }
3741
+ };
3742
+ File = _File;
3743
+ }));
3744
+
3745
+ //#endregion
3746
+ //#region ../../node_modules/.bun/formdata-polyfill@4.0.10/node_modules/formdata-polyfill/esm.min.js
3747
+ /** @param {FormData} F */
3748
+ function formDataToBlob(F, B = Blob) {
3749
+ var b = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c = [], p = `--${b}\r\nContent-Disposition: form-data; name="`;
3750
+ F.forEach((v, n) => typeof v == "string" ? c.push(p + e(n) + `"\r\n\r\n${v.replace(/\r(?!\n)|(?<!\r)\n/g, "\r\n")}\r\n`) : c.push(p + e(n) + `"; filename="${e(v.name, 1)}"\r\nContent-Type: ${v.type || "application/octet-stream"}\r\n\r\n`, v, "\r\n"));
3751
+ c.push(`--${b}--`);
3752
+ return new B(c, { type: "multipart/form-data; boundary=" + b });
3753
+ }
3754
+ var t, i, h, r, m, f, e, x, FormData;
3755
+ var init_esm_min = __esmMin((() => {
3756
+ init_fetch_blob();
3757
+ init_file();
3758
+ ({toStringTag: t, iterator: i, hasInstance: h} = Symbol), r = Math.random, m = "append,set,get,getAll,delete,keys,values,entries,forEach,constructor".split(","), f = (a, b, c) => (a += "", /^(Blob|File)$/.test(b && b[t]) ? [(c = c !== void 0 ? c + "" : b[t] == "File" ? b.name : "blob", a), b.name !== c || b[t] == "blob" ? new File([b], c, b) : b] : [a, b + ""]), e = (c, f) => (f ? c : c.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"), x = (n, a, e) => {
3759
+ if (a.length < e) throw new TypeError(`Failed to execute '${n}' on 'FormData': ${e} arguments required, but only ${a.length} present.`);
3760
+ };
3761
+ FormData = class FormData {
3762
+ #d = [];
3763
+ constructor(...a) {
3764
+ if (a.length) throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`);
3765
+ }
3766
+ get [t]() {
3767
+ return "FormData";
3768
+ }
3769
+ [i]() {
3770
+ return this.entries();
3771
+ }
3772
+ static [h](o) {
3773
+ return o && typeof o === "object" && o[t] === "FormData" && !m.some((m) => typeof o[m] != "function");
3774
+ }
3775
+ append(...a) {
3776
+ x("append", arguments, 2);
3777
+ this.#d.push(f(...a));
3778
+ }
3779
+ delete(a) {
3780
+ x("delete", arguments, 1);
3781
+ a += "";
3782
+ this.#d = this.#d.filter(([b]) => b !== a);
3783
+ }
3784
+ get(a) {
3785
+ x("get", arguments, 1);
3786
+ a += "";
3787
+ for (var b = this.#d, l = b.length, c = 0; c < l; c++) if (b[c][0] === a) return b[c][1];
3788
+ return null;
3789
+ }
3790
+ getAll(a, b) {
3791
+ x("getAll", arguments, 1);
3792
+ b = [];
3793
+ a += "";
3794
+ this.#d.forEach((c) => c[0] === a && b.push(c[1]));
3795
+ return b;
3796
+ }
3797
+ has(a) {
3798
+ x("has", arguments, 1);
3799
+ a += "";
3800
+ return this.#d.some((b) => b[0] === a);
3801
+ }
3802
+ forEach(a, b) {
3803
+ x("forEach", arguments, 1);
3804
+ for (var [c, d] of this) a.call(b, d, c, this);
3805
+ }
3806
+ set(...a) {
3807
+ x("set", arguments, 2);
3808
+ var b = [], c = !0;
3809
+ a = f(...a);
3810
+ this.#d.forEach((d) => {
3811
+ d[0] === a[0] ? c && (c = !b.push(a)) : b.push(d);
3812
+ });
3813
+ c && b.push(a);
3814
+ this.#d = b;
3815
+ }
3816
+ *entries() {
3817
+ yield* this.#d;
3818
+ }
3819
+ *keys() {
3820
+ for (var [a] of this) yield a;
3821
+ }
3822
+ *values() {
3823
+ for (var [, a] of this) yield a;
3824
+ }
3825
+ };
3826
+ }));
3827
+
3828
+ //#endregion
3829
+ //#region ../../node_modules/.bun/node-domexception@1.0.0/node_modules/node-domexception/index.js
3830
+ var require_node_domexception = /* @__PURE__ */ __commonJSMin(((exports, module) => {
3831
+ /*! node-domexception. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
3832
+ if (!globalThis.DOMException) try {
3833
+ const { MessageChannel } = __require("worker_threads"), port = new MessageChannel().port1, ab = /* @__PURE__ */ new ArrayBuffer();
3834
+ port.postMessage(ab, [ab, ab]);
3835
+ } catch (err) {
3836
+ err.constructor.name === "DOMException" && (globalThis.DOMException = err.constructor);
3837
+ }
3838
+ module.exports = globalThis.DOMException;
3839
+ }));
3840
+
3841
+ //#endregion
3842
+ //#region ../../node_modules/.bun/fetch-blob@3.2.0/node_modules/fetch-blob/from.js
3843
+ var import_node_domexception, stat, BlobDataItem;
3844
+ var init_from = __esmMin((() => {
3845
+ import_node_domexception = /* @__PURE__ */ __toESM(require_node_domexception(), 1);
3846
+ init_file();
3847
+ init_fetch_blob();
3848
+ ({stat} = promises);
3849
+ BlobDataItem = class BlobDataItem {
3850
+ #path;
3851
+ #start;
3852
+ constructor(options) {
3853
+ this.#path = options.path;
3854
+ this.#start = options.start;
3855
+ this.size = options.size;
3856
+ this.lastModified = options.lastModified;
3857
+ }
3858
+ /**
3859
+ * Slicing arguments is first validated and formatted
3860
+ * to not be out of range by Blob.prototype.slice
3861
+ */
3862
+ slice(start, end) {
3863
+ return new BlobDataItem({
3864
+ path: this.#path,
3865
+ lastModified: this.lastModified,
3866
+ size: end - start,
3867
+ start: this.#start + start
3868
+ });
3869
+ }
3870
+ async *stream() {
3871
+ const { mtimeMs } = await stat(this.#path);
3872
+ if (mtimeMs > this.lastModified) throw new import_node_domexception.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", "NotReadableError");
3873
+ yield* createReadStream(this.#path, {
3874
+ start: this.#start,
3875
+ end: this.#start + this.size - 1
3876
+ });
3877
+ }
3878
+ get [Symbol.toStringTag]() {
3879
+ return "Blob";
3880
+ }
3881
+ };
3882
+ }));
3883
+
3884
+ //#endregion
3885
+ export { File as a, init_esm_min as i, FormData as n, Blob as o, formDataToBlob as r, init_fetch_blob as s, init_from as t };
3886
+ //# sourceMappingURL=from-Bc9kdEMW.js.map