web-streams-polyfill 3.2.1 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +11 -14
  3. package/dist/polyfill.es2018.js +723 -197
  4. package/dist/polyfill.es2018.js.map +1 -1
  5. package/dist/polyfill.es2018.min.js +8 -1
  6. package/dist/polyfill.es2018.min.js.map +1 -1
  7. package/dist/polyfill.es2018.mjs +721 -193
  8. package/dist/polyfill.es2018.mjs.map +1 -1
  9. package/dist/polyfill.es6.js +789 -197
  10. package/dist/polyfill.es6.js.map +1 -1
  11. package/dist/polyfill.es6.min.js +8 -1
  12. package/dist/polyfill.es6.min.js.map +1 -1
  13. package/dist/polyfill.es6.mjs +787 -193
  14. package/dist/polyfill.es6.mjs.map +1 -1
  15. package/dist/polyfill.js +873 -243
  16. package/dist/polyfill.js.map +1 -1
  17. package/dist/polyfill.min.js +8 -1
  18. package/dist/polyfill.min.js.map +1 -1
  19. package/dist/polyfill.mjs +871 -239
  20. package/dist/polyfill.mjs.map +1 -1
  21. package/dist/ponyfill.es2018.js +723 -197
  22. package/dist/ponyfill.es2018.js.map +1 -1
  23. package/dist/ponyfill.es2018.mjs +721 -193
  24. package/dist/ponyfill.es2018.mjs.map +1 -1
  25. package/dist/ponyfill.es6.js +789 -197
  26. package/dist/ponyfill.es6.js.map +1 -1
  27. package/dist/ponyfill.es6.mjs +787 -193
  28. package/dist/ponyfill.es6.mjs.map +1 -1
  29. package/dist/ponyfill.js +873 -243
  30. package/dist/ponyfill.js.map +1 -1
  31. package/dist/ponyfill.mjs +871 -239
  32. package/dist/ponyfill.mjs.map +1 -1
  33. package/dist/types/{polyfill.d.ts → ponyfill.d.ts} +780 -771
  34. package/dist/types/ts3.6/{polyfill.d.ts → ponyfill.d.ts} +57 -7
  35. package/dist/types/tsdoc-metadata.json +1 -1
  36. package/es2018/package.json +8 -1
  37. package/es6/package.json +8 -1
  38. package/package.json +28 -21
  39. package/ponyfill/es2018/package.json +8 -1
  40. package/ponyfill/es6/package.json +8 -1
  41. package/ponyfill/package.json +8 -1
@@ -1,44 +1,48 @@
1
1
  /**
2
- * web-streams-polyfill v3.2.1
2
+ * @license
3
+ * web-streams-polyfill v3.3.1
4
+ * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors.
5
+ * This code is released under the MIT license.
6
+ * SPDX-License-Identifier: MIT
3
7
  */
4
8
  /// <reference lib="es2015.symbol" />
5
9
  const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
6
10
  Symbol :
7
11
  description => `Symbol(${description})`;
8
12
 
9
- /// <reference lib="dom" />
10
13
  function noop() {
11
14
  return undefined;
12
15
  }
13
- function getGlobals() {
14
- if (typeof self !== 'undefined') {
15
- return self;
16
- }
17
- else if (typeof window !== 'undefined') {
18
- return window;
19
- }
20
- else if (typeof global !== 'undefined') {
21
- return global;
22
- }
23
- return undefined;
24
- }
25
- const globals = getGlobals();
26
16
 
27
17
  function typeIsObject(x) {
28
18
  return (typeof x === 'object' && x !== null) || typeof x === 'function';
29
19
  }
30
20
  const rethrowAssertionErrorRejection = noop;
21
+ function setFunctionName(fn, name) {
22
+ try {
23
+ Object.defineProperty(fn, 'name', {
24
+ value: name,
25
+ configurable: true
26
+ });
27
+ }
28
+ catch (_a) {
29
+ // This property is non-configurable in older browsers, so ignore if this throws.
30
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
31
+ }
32
+ }
31
33
 
32
34
  const originalPromise = Promise;
33
35
  const originalPromiseThen = Promise.prototype.then;
34
- const originalPromiseResolve = Promise.resolve.bind(originalPromise);
35
36
  const originalPromiseReject = Promise.reject.bind(originalPromise);
37
+ // https://webidl.spec.whatwg.org/#a-new-promise
36
38
  function newPromise(executor) {
37
39
  return new originalPromise(executor);
38
40
  }
41
+ // https://webidl.spec.whatwg.org/#a-promise-resolved-with
39
42
  function promiseResolvedWith(value) {
40
- return originalPromiseResolve(value);
43
+ return newPromise(resolve => resolve(value));
41
44
  }
45
+ // https://webidl.spec.whatwg.org/#a-promise-rejected-with
42
46
  function promiseRejectedWith(reason) {
43
47
  return originalPromiseReject(reason);
44
48
  }
@@ -47,6 +51,9 @@ function PerformPromiseThen(promise, onFulfilled, onRejected) {
47
51
  // approximation.
48
52
  return originalPromiseThen.call(promise, onFulfilled, onRejected);
49
53
  }
54
+ // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned
55
+ // from that handler. To prevent this, return null instead of void from all handlers.
56
+ // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it
50
57
  function uponPromise(promise, onFulfilled, onRejected) {
51
58
  PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
52
59
  }
@@ -62,14 +69,16 @@ function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
62
69
  function setPromiseIsHandledToTrue(promise) {
63
70
  PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
64
71
  }
65
- const queueMicrotask = (() => {
66
- const globalQueueMicrotask = globals && globals.queueMicrotask;
67
- if (typeof globalQueueMicrotask === 'function') {
68
- return globalQueueMicrotask;
72
+ let _queueMicrotask = callback => {
73
+ if (typeof queueMicrotask === 'function') {
74
+ _queueMicrotask = queueMicrotask;
69
75
  }
70
- const resolvedPromise = promiseResolvedWith(undefined);
71
- return (fn) => PerformPromiseThen(resolvedPromise, fn);
72
- })();
76
+ else {
77
+ const resolvedPromise = promiseResolvedWith(undefined);
78
+ _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);
79
+ }
80
+ return _queueMicrotask(callback);
81
+ };
73
82
  function reflectCall(F, V, args) {
74
83
  if (typeof F !== 'function') {
75
84
  throw new TypeError('Argument is not a function');
@@ -193,6 +202,12 @@ class SimpleQueue {
193
202
  }
194
203
  }
195
204
 
205
+ const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
206
+ const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
207
+ const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
208
+ const PullSteps = SymbolPolyfill('[[PullSteps]]');
209
+ const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]');
210
+
196
211
  function ReadableStreamReaderGenericInitialize(reader, stream) {
197
212
  reader._ownerReadableStream = stream;
198
213
  stream._reader = reader;
@@ -213,13 +228,15 @@ function ReadableStreamReaderGenericCancel(reader, reason) {
213
228
  return ReadableStreamCancel(stream, reason);
214
229
  }
215
230
  function ReadableStreamReaderGenericRelease(reader) {
216
- if (reader._ownerReadableStream._state === 'readable') {
231
+ const stream = reader._ownerReadableStream;
232
+ if (stream._state === 'readable') {
217
233
  defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
218
234
  }
219
235
  else {
220
236
  defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
221
237
  }
222
- reader._ownerReadableStream._reader = undefined;
238
+ stream._readableStreamController[ReleaseSteps]();
239
+ stream._reader = undefined;
223
240
  reader._ownerReadableStream = undefined;
224
241
  }
225
242
  // Helper functions for the readers.
@@ -262,11 +279,6 @@ function defaultReaderClosedPromiseResolve(reader) {
262
279
  reader._closedPromise_reject = undefined;
263
280
  }
264
281
 
265
- const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
266
- const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
267
- const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
268
- const PullSteps = SymbolPolyfill('[[PullSteps]]');
269
-
270
282
  /// <reference lib="es2015.core" />
271
283
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
272
284
  const NumberIsFinite = Number.isFinite || function (x) {
@@ -462,10 +474,7 @@ class ReadableStreamDefaultReader {
462
474
  if (this._ownerReadableStream === undefined) {
463
475
  return;
464
476
  }
465
- if (this._readRequests.length > 0) {
466
- throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
467
- }
468
- ReadableStreamReaderGenericRelease(this);
477
+ ReadableStreamDefaultReaderRelease(this);
469
478
  }
470
479
  }
471
480
  Object.defineProperties(ReadableStreamDefaultReader.prototype, {
@@ -474,6 +483,9 @@ Object.defineProperties(ReadableStreamDefaultReader.prototype, {
474
483
  releaseLock: { enumerable: true },
475
484
  closed: { enumerable: true }
476
485
  });
486
+ setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');
487
+ setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');
488
+ setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');
477
489
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
478
490
  Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
479
491
  value: 'ReadableStreamDefaultReader',
@@ -503,6 +515,18 @@ function ReadableStreamDefaultReaderRead(reader, readRequest) {
503
515
  stream._readableStreamController[PullSteps](readRequest);
504
516
  }
505
517
  }
518
+ function ReadableStreamDefaultReaderRelease(reader) {
519
+ ReadableStreamReaderGenericRelease(reader);
520
+ const e = new TypeError('Reader was released');
521
+ ReadableStreamDefaultReaderErrorReadRequests(reader, e);
522
+ }
523
+ function ReadableStreamDefaultReaderErrorReadRequests(reader, e) {
524
+ const readRequests = reader._readRequests;
525
+ reader._readRequests = new SimpleQueue();
526
+ readRequests.forEach(readRequest => {
527
+ readRequest._errorSteps(e);
528
+ });
529
+ }
506
530
  // Helper functions for the ReadableStreamDefaultReader.
507
531
  function defaultReaderBrandCheckException(name) {
508
532
  return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
@@ -549,9 +573,6 @@ class ReadableStreamAsyncIteratorImpl {
549
573
  return Promise.resolve({ value: undefined, done: true });
550
574
  }
551
575
  const reader = this._reader;
552
- if (reader._ownerReadableStream === undefined) {
553
- return promiseRejectedWith(readerLockException('iterate'));
554
- }
555
576
  let resolvePromise;
556
577
  let rejectPromise;
557
578
  const promise = newPromise((resolve, reject) => {
@@ -563,7 +584,7 @@ class ReadableStreamAsyncIteratorImpl {
563
584
  this._ongoingPromise = undefined;
564
585
  // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
565
586
  // FIXME Is this a bug in the specification, or in the test?
566
- queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
587
+ _queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
567
588
  },
568
589
  _closeSteps: () => {
569
590
  this._ongoingPromise = undefined;
@@ -587,9 +608,6 @@ class ReadableStreamAsyncIteratorImpl {
587
608
  }
588
609
  this._isFinished = true;
589
610
  const reader = this._reader;
590
- if (reader._ownerReadableStream === undefined) {
591
- return promiseRejectedWith(readerLockException('finish iterating'));
592
- }
593
611
  if (!this._preventCancel) {
594
612
  const result = ReadableStreamReaderGenericCancel(reader, value);
595
613
  ReadableStreamReaderGenericRelease(reader);
@@ -652,6 +670,70 @@ const NumberIsNaN = Number.isNaN || function (x) {
652
670
  return x !== x;
653
671
  };
654
672
 
673
+ /******************************************************************************
674
+ Copyright (c) Microsoft Corporation.
675
+
676
+ Permission to use, copy, modify, and/or distribute this software for any
677
+ purpose with or without fee is hereby granted.
678
+
679
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
680
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
681
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
682
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
683
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
684
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
685
+ PERFORMANCE OF THIS SOFTWARE.
686
+ ***************************************************************************** */
687
+ /* global Reflect, Promise, SuppressedError, Symbol */
688
+
689
+
690
+ function __values(o) {
691
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
692
+ if (m) return m.call(o);
693
+ if (o && typeof o.length === "number") return {
694
+ next: function () {
695
+ if (o && i >= o.length) o = void 0;
696
+ return { value: o && o[i++], done: !o };
697
+ }
698
+ };
699
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
700
+ }
701
+
702
+ function __await(v) {
703
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
704
+ }
705
+
706
+ function __asyncGenerator(thisArg, _arguments, generator) {
707
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
708
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
709
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
710
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
711
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
712
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
713
+ function fulfill(value) { resume("next", value); }
714
+ function reject(value) { resume("throw", value); }
715
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
716
+ }
717
+
718
+ function __asyncDelegator(o) {
719
+ var i, p;
720
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
721
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
722
+ }
723
+
724
+ function __asyncValues(o) {
725
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
726
+ var m = o[Symbol.asyncIterator], i;
727
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
728
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
729
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
730
+ }
731
+
732
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
733
+ var e = new Error(message);
734
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
735
+ };
736
+
655
737
  function CreateArrayFromList(elements) {
656
738
  // We use arrays to represent lists, so this is basically a no-op.
657
739
  // Do a slice though just in case we happen to depend on the unique-ness.
@@ -660,15 +742,29 @@ function CreateArrayFromList(elements) {
660
742
  function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
661
743
  new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
662
744
  }
663
- // Not implemented correctly
664
- function TransferArrayBuffer(O) {
665
- return O;
666
- }
667
- // Not implemented correctly
668
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
669
- function IsDetachedBuffer(O) {
670
- return false;
671
- }
745
+ let TransferArrayBuffer = (O) => {
746
+ if (typeof O.transfer === 'function') {
747
+ TransferArrayBuffer = buffer => buffer.transfer();
748
+ }
749
+ else if (typeof structuredClone === 'function') {
750
+ TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });
751
+ }
752
+ else {
753
+ // Not implemented correctly
754
+ TransferArrayBuffer = buffer => buffer;
755
+ }
756
+ return TransferArrayBuffer(O);
757
+ };
758
+ let IsDetachedBuffer = (O) => {
759
+ if (typeof O.detached === 'boolean') {
760
+ IsDetachedBuffer = buffer => buffer.detached;
761
+ }
762
+ else {
763
+ // Not implemented correctly
764
+ IsDetachedBuffer = buffer => buffer.byteLength === 0;
765
+ }
766
+ return IsDetachedBuffer(O);
767
+ };
672
768
  function ArrayBufferSlice(buffer, begin, end) {
673
769
  // ArrayBuffer.prototype.slice is not available on IE10
674
770
  // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice
@@ -680,6 +776,70 @@ function ArrayBufferSlice(buffer, begin, end) {
680
776
  CopyDataBlockBytes(slice, 0, buffer, begin, length);
681
777
  return slice;
682
778
  }
779
+ function GetMethod(receiver, prop) {
780
+ const func = receiver[prop];
781
+ if (func === undefined || func === null) {
782
+ return undefined;
783
+ }
784
+ if (typeof func !== 'function') {
785
+ throw new TypeError(`${String(prop)} is not a function`);
786
+ }
787
+ return func;
788
+ }
789
+ function CreateAsyncFromSyncIterator(syncIteratorRecord) {
790
+ // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,
791
+ // we use yield* inside an async generator function to achieve the same result.
792
+ // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.
793
+ const syncIterable = {
794
+ [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator
795
+ };
796
+ // Create an async generator function and immediately invoke it.
797
+ const asyncIterator = (function () {
798
+ return __asyncGenerator(this, arguments, function* () {
799
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable))));
800
+ });
801
+ }());
802
+ // Return as an async iterator record.
803
+ const nextMethod = asyncIterator.next;
804
+ return { iterator: asyncIterator, nextMethod, done: false };
805
+ }
806
+ function GetIterator(obj, hint = 'sync', method) {
807
+ if (method === undefined) {
808
+ if (hint === 'async') {
809
+ method = GetMethod(obj, SymbolPolyfill.asyncIterator);
810
+ if (method === undefined) {
811
+ const syncMethod = GetMethod(obj, SymbolPolyfill.iterator);
812
+ const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod);
813
+ return CreateAsyncFromSyncIterator(syncIteratorRecord);
814
+ }
815
+ }
816
+ else {
817
+ method = GetMethod(obj, SymbolPolyfill.iterator);
818
+ }
819
+ }
820
+ if (method === undefined) {
821
+ throw new TypeError('The object is not iterable');
822
+ }
823
+ const iterator = reflectCall(method, obj, []);
824
+ if (!typeIsObject(iterator)) {
825
+ throw new TypeError('The iterator method must return an object');
826
+ }
827
+ const nextMethod = iterator.next;
828
+ return { iterator, nextMethod, done: false };
829
+ }
830
+ function IteratorNext(iteratorRecord) {
831
+ const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
832
+ if (!typeIsObject(result)) {
833
+ throw new TypeError('The iterator.next() method must return an object');
834
+ }
835
+ return result;
836
+ }
837
+ function IteratorComplete(iterResult) {
838
+ return Boolean(iterResult.done);
839
+ }
840
+ function IteratorValue(iterResult) {
841
+ return iterResult.value;
842
+ }
683
843
 
684
844
  function IsNonNegativeNumber(v) {
685
845
  if (typeof v !== 'number') {
@@ -722,6 +882,19 @@ function ResetQueue(container) {
722
882
  container._queueTotalSize = 0;
723
883
  }
724
884
 
885
+ function isDataViewConstructor(ctor) {
886
+ return ctor === DataView;
887
+ }
888
+ function isDataView(view) {
889
+ return isDataViewConstructor(view.constructor);
890
+ }
891
+ function arrayBufferViewElementSize(ctor) {
892
+ if (isDataViewConstructor(ctor)) {
893
+ return 1;
894
+ }
895
+ return ctor.BYTES_PER_ELEMENT;
896
+ }
897
+
725
898
  /**
726
899
  * A pull-into request in a {@link ReadableByteStreamController}.
727
900
  *
@@ -749,7 +922,9 @@ class ReadableStreamBYOBRequest {
749
922
  if (this._associatedReadableByteStreamController === undefined) {
750
923
  throw new TypeError('This BYOB request has been invalidated');
751
924
  }
752
- if (IsDetachedBuffer(this._view.buffer)) ;
925
+ if (IsDetachedBuffer(this._view.buffer)) {
926
+ throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
927
+ }
753
928
  ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
754
929
  }
755
930
  respondWithNewView(view) {
@@ -763,7 +938,9 @@ class ReadableStreamBYOBRequest {
763
938
  if (this._associatedReadableByteStreamController === undefined) {
764
939
  throw new TypeError('This BYOB request has been invalidated');
765
940
  }
766
- if (IsDetachedBuffer(view.buffer)) ;
941
+ if (IsDetachedBuffer(view.buffer)) {
942
+ throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response');
943
+ }
767
944
  ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
768
945
  }
769
946
  }
@@ -772,6 +949,8 @@ Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
772
949
  respondWithNewView: { enumerable: true },
773
950
  view: { enumerable: true }
774
951
  });
952
+ setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');
953
+ setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');
775
954
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
776
955
  Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
777
956
  value: 'ReadableStreamBYOBRequest',
@@ -867,11 +1046,7 @@ class ReadableByteStreamController {
867
1046
  [PullSteps](readRequest) {
868
1047
  const stream = this._controlledReadableByteStream;
869
1048
  if (this._queueTotalSize > 0) {
870
- const entry = this._queue.shift();
871
- this._queueTotalSize -= entry.byteLength;
872
- ReadableByteStreamControllerHandleQueueDrain(this);
873
- const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
874
- readRequest._chunkSteps(view);
1049
+ ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
875
1050
  return;
876
1051
  }
877
1052
  const autoAllocateChunkSize = this._autoAllocateChunkSize;
@@ -890,6 +1065,7 @@ class ReadableByteStreamController {
890
1065
  byteOffset: 0,
891
1066
  byteLength: autoAllocateChunkSize,
892
1067
  bytesFilled: 0,
1068
+ minimumFill: 1,
893
1069
  elementSize: 1,
894
1070
  viewConstructor: Uint8Array,
895
1071
  readerType: 'default'
@@ -899,6 +1075,15 @@ class ReadableByteStreamController {
899
1075
  ReadableStreamAddReadRequest(stream, readRequest);
900
1076
  ReadableByteStreamControllerCallPullIfNeeded(this);
901
1077
  }
1078
+ /** @internal */
1079
+ [ReleaseSteps]() {
1080
+ if (this._pendingPullIntos.length > 0) {
1081
+ const firstPullInto = this._pendingPullIntos.peek();
1082
+ firstPullInto.readerType = 'none';
1083
+ this._pendingPullIntos = new SimpleQueue();
1084
+ this._pendingPullIntos.push(firstPullInto);
1085
+ }
1086
+ }
902
1087
  }
903
1088
  Object.defineProperties(ReadableByteStreamController.prototype, {
904
1089
  close: { enumerable: true },
@@ -907,6 +1092,9 @@ Object.defineProperties(ReadableByteStreamController.prototype, {
907
1092
  byobRequest: { enumerable: true },
908
1093
  desiredSize: { enumerable: true }
909
1094
  });
1095
+ setFunctionName(ReadableByteStreamController.prototype.close, 'close');
1096
+ setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');
1097
+ setFunctionName(ReadableByteStreamController.prototype.error, 'error');
910
1098
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
911
1099
  Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
912
1100
  value: 'ReadableByteStreamController',
@@ -950,8 +1138,10 @@ function ReadableByteStreamControllerCallPullIfNeeded(controller) {
950
1138
  controller._pullAgain = false;
951
1139
  ReadableByteStreamControllerCallPullIfNeeded(controller);
952
1140
  }
1141
+ return null;
953
1142
  }, e => {
954
1143
  ReadableByteStreamControllerError(controller, e);
1144
+ return null;
955
1145
  });
956
1146
  }
957
1147
  function ReadableByteStreamControllerClearPendingPullIntos(controller) {
@@ -980,15 +1170,33 @@ function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byt
980
1170
  controller._queue.push({ buffer, byteOffset, byteLength });
981
1171
  controller._queueTotalSize += byteLength;
982
1172
  }
1173
+ function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
1174
+ let clonedChunk;
1175
+ try {
1176
+ clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
1177
+ }
1178
+ catch (cloneE) {
1179
+ ReadableByteStreamControllerError(controller, cloneE);
1180
+ throw cloneE;
1181
+ }
1182
+ ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
1183
+ }
1184
+ function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
1185
+ if (firstDescriptor.bytesFilled > 0) {
1186
+ ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
1187
+ }
1188
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
1189
+ }
983
1190
  function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
984
- const elementSize = pullIntoDescriptor.elementSize;
985
- const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize;
986
1191
  const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
987
1192
  const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
988
- const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize;
989
1193
  let totalBytesToCopyRemaining = maxBytesToCopy;
990
1194
  let ready = false;
991
- if (maxAlignedBytes > currentAlignedBytes) {
1195
+ const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;
1196
+ const maxAlignedBytes = maxBytesFilled - remainderBytes;
1197
+ // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1198
+ // of the queue, so the underlying source can keep filling it.
1199
+ if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
992
1200
  totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
993
1201
  ready = true;
994
1202
  }
@@ -1043,25 +1251,37 @@ function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(contro
1043
1251
  }
1044
1252
  }
1045
1253
  }
1046
- function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) {
1047
- const stream = controller._controlledReadableByteStream;
1048
- let elementSize = 1;
1049
- if (view.constructor !== DataView) {
1050
- elementSize = view.constructor.BYTES_PER_ELEMENT;
1254
+ function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
1255
+ const reader = controller._controlledReadableByteStream._reader;
1256
+ while (reader._readRequests.length > 0) {
1257
+ if (controller._queueTotalSize === 0) {
1258
+ return;
1259
+ }
1260
+ const readRequest = reader._readRequests.shift();
1261
+ ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);
1051
1262
  }
1263
+ }
1264
+ function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) {
1265
+ const stream = controller._controlledReadableByteStream;
1052
1266
  const ctor = view.constructor;
1053
- // try {
1054
- const buffer = TransferArrayBuffer(view.buffer);
1055
- // } catch (e) {
1056
- // readIntoRequest._errorSteps(e);
1057
- // return;
1058
- // }
1267
+ const elementSize = arrayBufferViewElementSize(ctor);
1268
+ const { byteOffset, byteLength } = view;
1269
+ const minimumFill = min * elementSize;
1270
+ let buffer;
1271
+ try {
1272
+ buffer = TransferArrayBuffer(view.buffer);
1273
+ }
1274
+ catch (e) {
1275
+ readIntoRequest._errorSteps(e);
1276
+ return;
1277
+ }
1059
1278
  const pullIntoDescriptor = {
1060
1279
  buffer,
1061
1280
  bufferByteLength: buffer.byteLength,
1062
- byteOffset: view.byteOffset,
1063
- byteLength: view.byteLength,
1281
+ byteOffset,
1282
+ byteLength,
1064
1283
  bytesFilled: 0,
1284
+ minimumFill,
1065
1285
  elementSize,
1066
1286
  viewConstructor: ctor,
1067
1287
  readerType: 'byob'
@@ -1098,6 +1318,9 @@ function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest)
1098
1318
  ReadableByteStreamControllerCallPullIfNeeded(controller);
1099
1319
  }
1100
1320
  function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
1321
+ if (firstDescriptor.readerType === 'none') {
1322
+ ReadableByteStreamControllerShiftPendingPullInto(controller);
1323
+ }
1101
1324
  const stream = controller._controlledReadableByteStream;
1102
1325
  if (ReadableStreamHasBYOBReader(stream)) {
1103
1326
  while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
@@ -1108,15 +1331,21 @@ function ReadableByteStreamControllerRespondInClosedState(controller, firstDescr
1108
1331
  }
1109
1332
  function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
1110
1333
  ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
1111
- if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) {
1334
+ if (pullIntoDescriptor.readerType === 'none') {
1335
+ ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
1336
+ ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1337
+ return;
1338
+ }
1339
+ if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {
1340
+ // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1341
+ // of the queue, so the underlying source can keep filling it.
1112
1342
  return;
1113
1343
  }
1114
1344
  ReadableByteStreamControllerShiftPendingPullInto(controller);
1115
1345
  const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
1116
1346
  if (remainderSize > 0) {
1117
1347
  const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
1118
- const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end);
1119
- ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength);
1348
+ ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
1120
1349
  }
1121
1350
  pullIntoDescriptor.bytesFilled -= remainderSize;
1122
1351
  ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
@@ -1127,7 +1356,7 @@ function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
1127
1356
  ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1128
1357
  const state = controller._controlledReadableByteStream._state;
1129
1358
  if (state === 'closed') {
1130
- ReadableByteStreamControllerRespondInClosedState(controller);
1359
+ ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
1131
1360
  }
1132
1361
  else {
1133
1362
  ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
@@ -1177,7 +1406,7 @@ function ReadableByteStreamControllerClose(controller) {
1177
1406
  }
1178
1407
  if (controller._pendingPullIntos.length > 0) {
1179
1408
  const firstPendingPullInto = controller._pendingPullIntos.peek();
1180
- if (firstPendingPullInto.bytesFilled > 0) {
1409
+ if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
1181
1410
  const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
1182
1411
  ReadableByteStreamControllerError(controller, e);
1183
1412
  throw e;
@@ -1191,17 +1420,24 @@ function ReadableByteStreamControllerEnqueue(controller, chunk) {
1191
1420
  if (controller._closeRequested || stream._state !== 'readable') {
1192
1421
  return;
1193
1422
  }
1194
- const buffer = chunk.buffer;
1195
- const byteOffset = chunk.byteOffset;
1196
- const byteLength = chunk.byteLength;
1423
+ const { buffer, byteOffset, byteLength } = chunk;
1424
+ if (IsDetachedBuffer(buffer)) {
1425
+ throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued');
1426
+ }
1197
1427
  const transferredBuffer = TransferArrayBuffer(buffer);
1198
1428
  if (controller._pendingPullIntos.length > 0) {
1199
1429
  const firstPendingPullInto = controller._pendingPullIntos.peek();
1200
- if (IsDetachedBuffer(firstPendingPullInto.buffer)) ;
1430
+ if (IsDetachedBuffer(firstPendingPullInto.buffer)) {
1431
+ throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk');
1432
+ }
1433
+ ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1201
1434
  firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
1435
+ if (firstPendingPullInto.readerType === 'none') {
1436
+ ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
1437
+ }
1202
1438
  }
1203
- ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1204
1439
  if (ReadableStreamHasDefaultReader(stream)) {
1440
+ ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
1205
1441
  if (ReadableStreamGetNumReadRequests(stream) === 0) {
1206
1442
  ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1207
1443
  }
@@ -1233,6 +1469,13 @@ function ReadableByteStreamControllerError(controller, e) {
1233
1469
  ReadableByteStreamControllerClearAlgorithms(controller);
1234
1470
  ReadableStreamError(stream, e);
1235
1471
  }
1472
+ function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
1473
+ const entry = controller._queue.shift();
1474
+ controller._queueTotalSize -= entry.byteLength;
1475
+ ReadableByteStreamControllerHandleQueueDrain(controller);
1476
+ const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
1477
+ readRequest._chunkSteps(view);
1478
+ }
1236
1479
  function ReadableByteStreamControllerGetBYOBRequest(controller) {
1237
1480
  if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
1238
1481
  const firstDescriptor = controller._pendingPullIntos.peek();
@@ -1318,24 +1561,35 @@ function SetUpReadableByteStreamController(stream, controller, startAlgorithm, p
1318
1561
  uponPromise(promiseResolvedWith(startResult), () => {
1319
1562
  controller._started = true;
1320
1563
  ReadableByteStreamControllerCallPullIfNeeded(controller);
1564
+ return null;
1321
1565
  }, r => {
1322
1566
  ReadableByteStreamControllerError(controller, r);
1567
+ return null;
1323
1568
  });
1324
1569
  }
1325
1570
  function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
1326
1571
  const controller = Object.create(ReadableByteStreamController.prototype);
1327
- let startAlgorithm = () => undefined;
1328
- let pullAlgorithm = () => promiseResolvedWith(undefined);
1329
- let cancelAlgorithm = () => promiseResolvedWith(undefined);
1572
+ let startAlgorithm;
1573
+ let pullAlgorithm;
1574
+ let cancelAlgorithm;
1330
1575
  if (underlyingByteSource.start !== undefined) {
1331
1576
  startAlgorithm = () => underlyingByteSource.start(controller);
1332
1577
  }
1578
+ else {
1579
+ startAlgorithm = () => undefined;
1580
+ }
1333
1581
  if (underlyingByteSource.pull !== undefined) {
1334
1582
  pullAlgorithm = () => underlyingByteSource.pull(controller);
1335
1583
  }
1584
+ else {
1585
+ pullAlgorithm = () => promiseResolvedWith(undefined);
1586
+ }
1336
1587
  if (underlyingByteSource.cancel !== undefined) {
1337
1588
  cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
1338
1589
  }
1590
+ else {
1591
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
1592
+ }
1339
1593
  const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
1340
1594
  if (autoAllocateChunkSize === 0) {
1341
1595
  throw new TypeError('autoAllocateChunkSize must be greater than 0');
@@ -1355,6 +1609,29 @@ function byteStreamControllerBrandCheckException(name) {
1355
1609
  return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
1356
1610
  }
1357
1611
 
1612
+ function convertReaderOptions(options, context) {
1613
+ assertDictionary(options, context);
1614
+ const mode = options === null || options === void 0 ? void 0 : options.mode;
1615
+ return {
1616
+ mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
1617
+ };
1618
+ }
1619
+ function convertReadableStreamReaderMode(mode, context) {
1620
+ mode = `${mode}`;
1621
+ if (mode !== 'byob') {
1622
+ throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
1623
+ }
1624
+ return mode;
1625
+ }
1626
+ function convertByobReadOptions(options, context) {
1627
+ var _a;
1628
+ assertDictionary(options, context);
1629
+ const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1;
1630
+ return {
1631
+ min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`)
1632
+ };
1633
+ }
1634
+
1358
1635
  // Abstract operations for the ReadableStream.
1359
1636
  function AcquireReadableStreamBYOBReader(stream) {
1360
1637
  return new ReadableStreamBYOBReader(stream);
@@ -1427,12 +1704,7 @@ class ReadableStreamBYOBReader {
1427
1704
  }
1428
1705
  return ReadableStreamReaderGenericCancel(this, reason);
1429
1706
  }
1430
- /**
1431
- * Attempts to reads bytes into view, and returns a promise resolved with the result.
1432
- *
1433
- * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
1434
- */
1435
- read(view) {
1707
+ read(view, rawOptions = {}) {
1436
1708
  if (!IsReadableStreamBYOBReader(this)) {
1437
1709
  return promiseRejectedWith(byobReaderBrandCheckException('read'));
1438
1710
  }
@@ -1445,7 +1717,28 @@ class ReadableStreamBYOBReader {
1445
1717
  if (view.buffer.byteLength === 0) {
1446
1718
  return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
1447
1719
  }
1448
- if (IsDetachedBuffer(view.buffer)) ;
1720
+ if (IsDetachedBuffer(view.buffer)) {
1721
+ return promiseRejectedWith(new TypeError('view\'s buffer has been detached'));
1722
+ }
1723
+ let options;
1724
+ try {
1725
+ options = convertByobReadOptions(rawOptions, 'options');
1726
+ }
1727
+ catch (e) {
1728
+ return promiseRejectedWith(e);
1729
+ }
1730
+ const min = options.min;
1731
+ if (min === 0) {
1732
+ return promiseRejectedWith(new TypeError('options.min must be greater than 0'));
1733
+ }
1734
+ if (!isDataView(view)) {
1735
+ if (min > view.length) {
1736
+ return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length'));
1737
+ }
1738
+ }
1739
+ else if (min > view.byteLength) {
1740
+ return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength'));
1741
+ }
1449
1742
  if (this._ownerReadableStream === undefined) {
1450
1743
  return promiseRejectedWith(readerLockException('read from'));
1451
1744
  }
@@ -1460,7 +1753,7 @@ class ReadableStreamBYOBReader {
1460
1753
  _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
1461
1754
  _errorSteps: e => rejectPromise(e)
1462
1755
  };
1463
- ReadableStreamBYOBReaderRead(this, view, readIntoRequest);
1756
+ ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);
1464
1757
  return promise;
1465
1758
  }
1466
1759
  /**
@@ -1479,10 +1772,7 @@ class ReadableStreamBYOBReader {
1479
1772
  if (this._ownerReadableStream === undefined) {
1480
1773
  return;
1481
1774
  }
1482
- if (this._readIntoRequests.length > 0) {
1483
- throw new TypeError('Tried to release a reader lock when that reader has pending read() calls un-settled');
1484
- }
1485
- ReadableStreamReaderGenericRelease(this);
1775
+ ReadableStreamBYOBReaderRelease(this);
1486
1776
  }
1487
1777
  }
1488
1778
  Object.defineProperties(ReadableStreamBYOBReader.prototype, {
@@ -1491,6 +1781,9 @@ Object.defineProperties(ReadableStreamBYOBReader.prototype, {
1491
1781
  releaseLock: { enumerable: true },
1492
1782
  closed: { enumerable: true }
1493
1783
  });
1784
+ setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');
1785
+ setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');
1786
+ setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');
1494
1787
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1495
1788
  Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
1496
1789
  value: 'ReadableStreamBYOBReader',
@@ -1507,16 +1800,28 @@ function IsReadableStreamBYOBReader(x) {
1507
1800
  }
1508
1801
  return x instanceof ReadableStreamBYOBReader;
1509
1802
  }
1510
- function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) {
1803
+ function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) {
1511
1804
  const stream = reader._ownerReadableStream;
1512
1805
  stream._disturbed = true;
1513
1806
  if (stream._state === 'errored') {
1514
1807
  readIntoRequest._errorSteps(stream._storedError);
1515
1808
  }
1516
1809
  else {
1517
- ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest);
1810
+ ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest);
1518
1811
  }
1519
1812
  }
1813
+ function ReadableStreamBYOBReaderRelease(reader) {
1814
+ ReadableStreamReaderGenericRelease(reader);
1815
+ const e = new TypeError('Reader was released');
1816
+ ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
1817
+ }
1818
+ function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) {
1819
+ const readIntoRequests = reader._readIntoRequests;
1820
+ reader._readIntoRequests = new SimpleQueue();
1821
+ readIntoRequests.forEach(readIntoRequest => {
1822
+ readIntoRequest._errorSteps(e);
1823
+ });
1824
+ }
1520
1825
  // Helper functions for the ReadableStreamBYOBReader.
1521
1826
  function byobReaderBrandCheckException(name) {
1522
1827
  return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
@@ -1717,6 +2022,9 @@ Object.defineProperties(WritableStream.prototype, {
1717
2022
  getWriter: { enumerable: true },
1718
2023
  locked: { enumerable: true }
1719
2024
  });
2025
+ setFunctionName(WritableStream.prototype.abort, 'abort');
2026
+ setFunctionName(WritableStream.prototype.close, 'close');
2027
+ setFunctionName(WritableStream.prototype.getWriter, 'getWriter');
1720
2028
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1721
2029
  Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
1722
2030
  value: 'WritableStream',
@@ -1782,7 +2090,7 @@ function WritableStreamAbort(stream, reason) {
1782
2090
  return promiseResolvedWith(undefined);
1783
2091
  }
1784
2092
  stream._writableStreamController._abortReason = reason;
1785
- (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort();
2093
+ (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason);
1786
2094
  // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',
1787
2095
  // but it doesn't know that signaling abort runs author code that might have changed the state.
1788
2096
  // Widen the type again by casting to WritableStreamState.
@@ -1887,9 +2195,11 @@ function WritableStreamFinishErroring(stream) {
1887
2195
  uponPromise(promise, () => {
1888
2196
  abortRequest._resolve();
1889
2197
  WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2198
+ return null;
1890
2199
  }, (reason) => {
1891
2200
  abortRequest._reject(reason);
1892
2201
  WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2202
+ return null;
1893
2203
  });
1894
2204
  }
1895
2205
  function WritableStreamFinishInFlightWrite(stream) {
@@ -2117,6 +2427,10 @@ Object.defineProperties(WritableStreamDefaultWriter.prototype, {
2117
2427
  desiredSize: { enumerable: true },
2118
2428
  ready: { enumerable: true }
2119
2429
  });
2430
+ setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');
2431
+ setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');
2432
+ setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');
2433
+ setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');
2120
2434
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2121
2435
  Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
2122
2436
  value: 'WritableStreamDefaultWriter',
@@ -2322,29 +2636,43 @@ function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm
2322
2636
  uponPromise(startPromise, () => {
2323
2637
  controller._started = true;
2324
2638
  WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2639
+ return null;
2325
2640
  }, r => {
2326
2641
  controller._started = true;
2327
2642
  WritableStreamDealWithRejection(stream, r);
2643
+ return null;
2328
2644
  });
2329
2645
  }
2330
2646
  function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
2331
2647
  const controller = Object.create(WritableStreamDefaultController.prototype);
2332
- let startAlgorithm = () => undefined;
2333
- let writeAlgorithm = () => promiseResolvedWith(undefined);
2334
- let closeAlgorithm = () => promiseResolvedWith(undefined);
2335
- let abortAlgorithm = () => promiseResolvedWith(undefined);
2648
+ let startAlgorithm;
2649
+ let writeAlgorithm;
2650
+ let closeAlgorithm;
2651
+ let abortAlgorithm;
2336
2652
  if (underlyingSink.start !== undefined) {
2337
2653
  startAlgorithm = () => underlyingSink.start(controller);
2338
2654
  }
2655
+ else {
2656
+ startAlgorithm = () => undefined;
2657
+ }
2339
2658
  if (underlyingSink.write !== undefined) {
2340
2659
  writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
2341
2660
  }
2661
+ else {
2662
+ writeAlgorithm = () => promiseResolvedWith(undefined);
2663
+ }
2342
2664
  if (underlyingSink.close !== undefined) {
2343
2665
  closeAlgorithm = () => underlyingSink.close();
2344
2666
  }
2667
+ else {
2668
+ closeAlgorithm = () => promiseResolvedWith(undefined);
2669
+ }
2345
2670
  if (underlyingSink.abort !== undefined) {
2346
2671
  abortAlgorithm = reason => underlyingSink.abort(reason);
2347
2672
  }
2673
+ else {
2674
+ abortAlgorithm = () => promiseResolvedWith(undefined);
2675
+ }
2348
2676
  SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
2349
2677
  }
2350
2678
  // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
@@ -2423,8 +2751,10 @@ function WritableStreamDefaultControllerProcessClose(controller) {
2423
2751
  WritableStreamDefaultControllerClearAlgorithms(controller);
2424
2752
  uponPromise(sinkClosePromise, () => {
2425
2753
  WritableStreamFinishInFlightClose(stream);
2754
+ return null;
2426
2755
  }, reason => {
2427
2756
  WritableStreamFinishInFlightCloseWithError(stream, reason);
2757
+ return null;
2428
2758
  });
2429
2759
  }
2430
2760
  function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
@@ -2440,11 +2770,13 @@ function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
2440
2770
  WritableStreamUpdateBackpressure(stream, backpressure);
2441
2771
  }
2442
2772
  WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2773
+ return null;
2443
2774
  }, reason => {
2444
2775
  if (stream._state === 'writable') {
2445
2776
  WritableStreamDefaultControllerClearAlgorithms(controller);
2446
2777
  }
2447
2778
  WritableStreamFinishInFlightWriteWithError(stream, reason);
2779
+ return null;
2448
2780
  });
2449
2781
  }
2450
2782
  function WritableStreamDefaultControllerGetBackpressure(controller) {
@@ -2551,13 +2883,28 @@ function defaultWriterReadyPromiseResolve(writer) {
2551
2883
  }
2552
2884
 
2553
2885
  /// <reference lib="dom" />
2554
- const NativeDOMException = typeof DOMException !== 'undefined' ? DOMException : undefined;
2886
+ function getGlobals() {
2887
+ if (typeof globalThis !== 'undefined') {
2888
+ return globalThis;
2889
+ }
2890
+ else if (typeof self !== 'undefined') {
2891
+ return self;
2892
+ }
2893
+ else if (typeof global !== 'undefined') {
2894
+ return global;
2895
+ }
2896
+ return undefined;
2897
+ }
2898
+ const globals = getGlobals();
2555
2899
 
2556
2900
  /// <reference types="node" />
2557
2901
  function isDOMExceptionConstructor(ctor) {
2558
2902
  if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
2559
2903
  return false;
2560
2904
  }
2905
+ if (ctor.name !== 'DOMException') {
2906
+ return false;
2907
+ }
2561
2908
  try {
2562
2909
  new ctor();
2563
2910
  return true;
@@ -2566,8 +2913,21 @@ function isDOMExceptionConstructor(ctor) {
2566
2913
  return false;
2567
2914
  }
2568
2915
  }
2569
- function createDOMExceptionPolyfill() {
2570
- // eslint-disable-next-line no-shadow
2916
+ /**
2917
+ * Support:
2918
+ * - Web browsers
2919
+ * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)
2920
+ */
2921
+ function getFromGlobal() {
2922
+ const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
2923
+ return isDOMExceptionConstructor(ctor) ? ctor : undefined;
2924
+ }
2925
+ /**
2926
+ * Support:
2927
+ * - All platforms
2928
+ */
2929
+ function createPolyfill() {
2930
+ // eslint-disable-next-line @typescript-eslint/no-shadow
2571
2931
  const ctor = function DOMException(message, name) {
2572
2932
  this.message = message || '';
2573
2933
  this.name = name || 'Error';
@@ -2575,12 +2935,13 @@ function createDOMExceptionPolyfill() {
2575
2935
  Error.captureStackTrace(this, this.constructor);
2576
2936
  }
2577
2937
  };
2938
+ setFunctionName(ctor, 'DOMException');
2578
2939
  ctor.prototype = Object.create(Error.prototype);
2579
2940
  Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
2580
2941
  return ctor;
2581
2942
  }
2582
- // eslint-disable-next-line no-redeclare
2583
- const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill();
2943
+ // eslint-disable-next-line @typescript-eslint/no-redeclare
2944
+ const DOMException = getFromGlobal() || createPolyfill();
2584
2945
 
2585
2946
  function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
2586
2947
  const reader = AcquireReadableStreamDefaultReader(source);
@@ -2593,7 +2954,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2593
2954
  let abortAlgorithm;
2594
2955
  if (signal !== undefined) {
2595
2956
  abortAlgorithm = () => {
2596
- const error = new DOMException$1('Aborted', 'AbortError');
2957
+ const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');
2597
2958
  const actions = [];
2598
2959
  if (!preventAbort) {
2599
2960
  actions.push(() => {
@@ -2662,6 +3023,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2662
3023
  else {
2663
3024
  shutdown(true, storedError);
2664
3025
  }
3026
+ return null;
2665
3027
  });
2666
3028
  // Errors must be propagated backward
2667
3029
  isOrBecomesErrored(dest, writer._closedPromise, storedError => {
@@ -2671,6 +3033,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2671
3033
  else {
2672
3034
  shutdown(true, storedError);
2673
3035
  }
3036
+ return null;
2674
3037
  });
2675
3038
  // Closing must be propagated forward
2676
3039
  isOrBecomesClosed(source, reader._closedPromise, () => {
@@ -2680,6 +3043,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2680
3043
  else {
2681
3044
  shutdown();
2682
3045
  }
3046
+ return null;
2683
3047
  });
2684
3048
  // Closing must be propagated backward
2685
3049
  if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
@@ -2727,6 +3091,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2727
3091
  }
2728
3092
  function doTheRest() {
2729
3093
  uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
3094
+ return null;
2730
3095
  }
2731
3096
  }
2732
3097
  function shutdown(isError, error) {
@@ -2753,6 +3118,7 @@ function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventC
2753
3118
  else {
2754
3119
  resolve(undefined);
2755
3120
  }
3121
+ return null;
2756
3122
  }
2757
3123
  });
2758
3124
  }
@@ -2833,6 +3199,10 @@ class ReadableStreamDefaultController {
2833
3199
  ReadableStreamDefaultControllerCallPullIfNeeded(this);
2834
3200
  }
2835
3201
  }
3202
+ /** @internal */
3203
+ [ReleaseSteps]() {
3204
+ // Do nothing.
3205
+ }
2836
3206
  }
2837
3207
  Object.defineProperties(ReadableStreamDefaultController.prototype, {
2838
3208
  close: { enumerable: true },
@@ -2840,6 +3210,9 @@ Object.defineProperties(ReadableStreamDefaultController.prototype, {
2840
3210
  error: { enumerable: true },
2841
3211
  desiredSize: { enumerable: true }
2842
3212
  });
3213
+ setFunctionName(ReadableStreamDefaultController.prototype.close, 'close');
3214
+ setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');
3215
+ setFunctionName(ReadableStreamDefaultController.prototype.error, 'error');
2843
3216
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2844
3217
  Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
2845
3218
  value: 'ReadableStreamDefaultController',
@@ -2873,8 +3246,10 @@ function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
2873
3246
  controller._pullAgain = false;
2874
3247
  ReadableStreamDefaultControllerCallPullIfNeeded(controller);
2875
3248
  }
3249
+ return null;
2876
3250
  }, e => {
2877
3251
  ReadableStreamDefaultControllerError(controller, e);
3252
+ return null;
2878
3253
  });
2879
3254
  }
2880
3255
  function ReadableStreamDefaultControllerShouldCallPull(controller) {
@@ -2989,24 +3364,35 @@ function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm
2989
3364
  uponPromise(promiseResolvedWith(startResult), () => {
2990
3365
  controller._started = true;
2991
3366
  ReadableStreamDefaultControllerCallPullIfNeeded(controller);
3367
+ return null;
2992
3368
  }, r => {
2993
3369
  ReadableStreamDefaultControllerError(controller, r);
3370
+ return null;
2994
3371
  });
2995
3372
  }
2996
3373
  function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
2997
3374
  const controller = Object.create(ReadableStreamDefaultController.prototype);
2998
- let startAlgorithm = () => undefined;
2999
- let pullAlgorithm = () => promiseResolvedWith(undefined);
3000
- let cancelAlgorithm = () => promiseResolvedWith(undefined);
3375
+ let startAlgorithm;
3376
+ let pullAlgorithm;
3377
+ let cancelAlgorithm;
3001
3378
  if (underlyingSource.start !== undefined) {
3002
3379
  startAlgorithm = () => underlyingSource.start(controller);
3003
3380
  }
3381
+ else {
3382
+ startAlgorithm = () => undefined;
3383
+ }
3004
3384
  if (underlyingSource.pull !== undefined) {
3005
3385
  pullAlgorithm = () => underlyingSource.pull(controller);
3006
3386
  }
3387
+ else {
3388
+ pullAlgorithm = () => promiseResolvedWith(undefined);
3389
+ }
3007
3390
  if (underlyingSource.cancel !== undefined) {
3008
3391
  cancelAlgorithm = reason => underlyingSource.cancel(reason);
3009
3392
  }
3393
+ else {
3394
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
3395
+ }
3010
3396
  SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
3011
3397
  }
3012
3398
  // Helper functions for the ReadableStreamDefaultController.
@@ -3045,7 +3431,7 @@ function ReadableStreamDefaultTee(stream, cloneForBranch2) {
3045
3431
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3046
3432
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3047
3433
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3048
- queueMicrotask(() => {
3434
+ _queueMicrotask(() => {
3049
3435
  readAgain = false;
3050
3436
  const chunk1 = chunk;
3051
3437
  const chunk2 = chunk;
@@ -3116,6 +3502,7 @@ function ReadableStreamDefaultTee(stream, cloneForBranch2) {
3116
3502
  if (!canceled1 || !canceled2) {
3117
3503
  resolveCancelPromise(undefined);
3118
3504
  }
3505
+ return null;
3119
3506
  });
3120
3507
  return [branch1, branch2];
3121
3508
  }
@@ -3137,13 +3524,14 @@ function ReadableByteStreamTee(stream) {
3137
3524
  function forwardReaderError(thisReader) {
3138
3525
  uponRejection(thisReader._closedPromise, r => {
3139
3526
  if (thisReader !== reader) {
3140
- return;
3527
+ return null;
3141
3528
  }
3142
3529
  ReadableByteStreamControllerError(branch1._readableStreamController, r);
3143
3530
  ReadableByteStreamControllerError(branch2._readableStreamController, r);
3144
3531
  if (!canceled1 || !canceled2) {
3145
3532
  resolveCancelPromise(undefined);
3146
3533
  }
3534
+ return null;
3147
3535
  });
3148
3536
  }
3149
3537
  function pullWithDefaultReader() {
@@ -3157,7 +3545,7 @@ function ReadableByteStreamTee(stream) {
3157
3545
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3158
3546
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3159
3547
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3160
- queueMicrotask(() => {
3548
+ _queueMicrotask(() => {
3161
3549
  readAgainForBranch1 = false;
3162
3550
  readAgainForBranch2 = false;
3163
3551
  const chunk1 = chunk;
@@ -3225,7 +3613,7 @@ function ReadableByteStreamTee(stream) {
3225
3613
  // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3226
3614
  // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3227
3615
  // successful synchronously-available reads get ahead of asynchronously-available errors.
3228
- queueMicrotask(() => {
3616
+ _queueMicrotask(() => {
3229
3617
  readAgainForBranch1 = false;
3230
3618
  readAgainForBranch2 = false;
3231
3619
  const byobCanceled = forBranch2 ? canceled2 : canceled1;
@@ -3284,7 +3672,7 @@ function ReadableByteStreamTee(stream) {
3284
3672
  reading = false;
3285
3673
  }
3286
3674
  };
3287
- ReadableStreamBYOBReaderRead(reader, view, readIntoRequest);
3675
+ ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);
3288
3676
  }
3289
3677
  function pull1Algorithm() {
3290
3678
  if (reading) {
@@ -3345,6 +3733,109 @@ function ReadableByteStreamTee(stream) {
3345
3733
  return [branch1, branch2];
3346
3734
  }
3347
3735
 
3736
+ function isReadableStreamLike(stream) {
3737
+ return typeIsObject(stream) && typeof stream.getReader !== 'undefined';
3738
+ }
3739
+
3740
+ function ReadableStreamFrom(source) {
3741
+ if (isReadableStreamLike(source)) {
3742
+ return ReadableStreamFromDefaultReader(source.getReader());
3743
+ }
3744
+ return ReadableStreamFromIterable(source);
3745
+ }
3746
+ function ReadableStreamFromIterable(asyncIterable) {
3747
+ let stream;
3748
+ const iteratorRecord = GetIterator(asyncIterable, 'async');
3749
+ const startAlgorithm = noop;
3750
+ function pullAlgorithm() {
3751
+ let nextResult;
3752
+ try {
3753
+ nextResult = IteratorNext(iteratorRecord);
3754
+ }
3755
+ catch (e) {
3756
+ return promiseRejectedWith(e);
3757
+ }
3758
+ const nextPromise = promiseResolvedWith(nextResult);
3759
+ return transformPromiseWith(nextPromise, iterResult => {
3760
+ if (!typeIsObject(iterResult)) {
3761
+ throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');
3762
+ }
3763
+ const done = IteratorComplete(iterResult);
3764
+ if (done) {
3765
+ ReadableStreamDefaultControllerClose(stream._readableStreamController);
3766
+ }
3767
+ else {
3768
+ const value = IteratorValue(iterResult);
3769
+ ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3770
+ }
3771
+ });
3772
+ }
3773
+ function cancelAlgorithm(reason) {
3774
+ const iterator = iteratorRecord.iterator;
3775
+ let returnMethod;
3776
+ try {
3777
+ returnMethod = GetMethod(iterator, 'return');
3778
+ }
3779
+ catch (e) {
3780
+ return promiseRejectedWith(e);
3781
+ }
3782
+ if (returnMethod === undefined) {
3783
+ return promiseResolvedWith(undefined);
3784
+ }
3785
+ let returnResult;
3786
+ try {
3787
+ returnResult = reflectCall(returnMethod, iterator, [reason]);
3788
+ }
3789
+ catch (e) {
3790
+ return promiseRejectedWith(e);
3791
+ }
3792
+ const returnPromise = promiseResolvedWith(returnResult);
3793
+ return transformPromiseWith(returnPromise, iterResult => {
3794
+ if (!typeIsObject(iterResult)) {
3795
+ throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');
3796
+ }
3797
+ return undefined;
3798
+ });
3799
+ }
3800
+ stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3801
+ return stream;
3802
+ }
3803
+ function ReadableStreamFromDefaultReader(reader) {
3804
+ let stream;
3805
+ const startAlgorithm = noop;
3806
+ function pullAlgorithm() {
3807
+ let readPromise;
3808
+ try {
3809
+ readPromise = reader.read();
3810
+ }
3811
+ catch (e) {
3812
+ return promiseRejectedWith(e);
3813
+ }
3814
+ return transformPromiseWith(readPromise, readResult => {
3815
+ if (!typeIsObject(readResult)) {
3816
+ throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');
3817
+ }
3818
+ if (readResult.done) {
3819
+ ReadableStreamDefaultControllerClose(stream._readableStreamController);
3820
+ }
3821
+ else {
3822
+ const value = readResult.value;
3823
+ ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3824
+ }
3825
+ });
3826
+ }
3827
+ function cancelAlgorithm(reason) {
3828
+ try {
3829
+ return promiseResolvedWith(reader.cancel(reason));
3830
+ }
3831
+ catch (e) {
3832
+ return promiseRejectedWith(e);
3833
+ }
3834
+ }
3835
+ stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3836
+ return stream;
3837
+ }
3838
+
3348
3839
  function convertUnderlyingDefaultOrByteSource(source, context) {
3349
3840
  assertDictionary(source, context);
3350
3841
  const original = source;
@@ -3389,21 +3880,6 @@ function convertReadableStreamType(type, context) {
3389
3880
  return type;
3390
3881
  }
3391
3882
 
3392
- function convertReaderOptions(options, context) {
3393
- assertDictionary(options, context);
3394
- const mode = options === null || options === void 0 ? void 0 : options.mode;
3395
- return {
3396
- mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
3397
- };
3398
- }
3399
- function convertReadableStreamReaderMode(mode, context) {
3400
- mode = `${mode}`;
3401
- if (mode !== 'byob') {
3402
- throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
3403
- }
3404
- return mode;
3405
- }
3406
-
3407
3883
  function convertIteratorOptions(options, context) {
3408
3884
  assertDictionary(options, context);
3409
3885
  const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
@@ -3573,7 +4049,19 @@ class ReadableStream {
3573
4049
  const options = convertIteratorOptions(rawOptions, 'First parameter');
3574
4050
  return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
3575
4051
  }
4052
+ /**
4053
+ * Creates a new ReadableStream wrapping the provided iterable or async iterable.
4054
+ *
4055
+ * This can be used to adapt various kinds of objects into a readable stream,
4056
+ * such as an array, an async generator, or a Node.js readable stream.
4057
+ */
4058
+ static from(asyncIterable) {
4059
+ return ReadableStreamFrom(asyncIterable);
4060
+ }
3576
4061
  }
4062
+ Object.defineProperties(ReadableStream, {
4063
+ from: { enumerable: true }
4064
+ });
3577
4065
  Object.defineProperties(ReadableStream.prototype, {
3578
4066
  cancel: { enumerable: true },
3579
4067
  getReader: { enumerable: true },
@@ -3583,6 +4071,13 @@ Object.defineProperties(ReadableStream.prototype, {
3583
4071
  values: { enumerable: true },
3584
4072
  locked: { enumerable: true }
3585
4073
  });
4074
+ setFunctionName(ReadableStream.from, 'from');
4075
+ setFunctionName(ReadableStream.prototype.cancel, 'cancel');
4076
+ setFunctionName(ReadableStream.prototype.getReader, 'getReader');
4077
+ setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');
4078
+ setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');
4079
+ setFunctionName(ReadableStream.prototype.tee, 'tee');
4080
+ setFunctionName(ReadableStream.prototype.values, 'values');
3586
4081
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3587
4082
  Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {
3588
4083
  value: 'ReadableStream',
@@ -3646,10 +4141,11 @@ function ReadableStreamCancel(stream, reason) {
3646
4141
  ReadableStreamClose(stream);
3647
4142
  const reader = stream._reader;
3648
4143
  if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {
3649
- reader._readIntoRequests.forEach(readIntoRequest => {
4144
+ const readIntoRequests = reader._readIntoRequests;
4145
+ reader._readIntoRequests = new SimpleQueue();
4146
+ readIntoRequests.forEach(readIntoRequest => {
3650
4147
  readIntoRequest._closeSteps(undefined);
3651
4148
  });
3652
- reader._readIntoRequests = new SimpleQueue();
3653
4149
  }
3654
4150
  const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
3655
4151
  return transformPromiseWith(sourceCancelPromise, noop);
@@ -3662,10 +4158,11 @@ function ReadableStreamClose(stream) {
3662
4158
  }
3663
4159
  defaultReaderClosedPromiseResolve(reader);
3664
4160
  if (IsReadableStreamDefaultReader(reader)) {
3665
- reader._readRequests.forEach(readRequest => {
4161
+ const readRequests = reader._readRequests;
4162
+ reader._readRequests = new SimpleQueue();
4163
+ readRequests.forEach(readRequest => {
3666
4164
  readRequest._closeSteps();
3667
4165
  });
3668
- reader._readRequests = new SimpleQueue();
3669
4166
  }
3670
4167
  }
3671
4168
  function ReadableStreamError(stream, e) {
@@ -3677,16 +4174,10 @@ function ReadableStreamError(stream, e) {
3677
4174
  }
3678
4175
  defaultReaderClosedPromiseReject(reader, e);
3679
4176
  if (IsReadableStreamDefaultReader(reader)) {
3680
- reader._readRequests.forEach(readRequest => {
3681
- readRequest._errorSteps(e);
3682
- });
3683
- reader._readRequests = new SimpleQueue();
4177
+ ReadableStreamDefaultReaderErrorReadRequests(reader, e);
3684
4178
  }
3685
4179
  else {
3686
- reader._readIntoRequests.forEach(readIntoRequest => {
3687
- readIntoRequest._errorSteps(e);
3688
- });
3689
- reader._readIntoRequests = new SimpleQueue();
4180
+ ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
3690
4181
  }
3691
4182
  }
3692
4183
  // Helper functions for the ReadableStream.
@@ -3707,16 +4198,7 @@ function convertQueuingStrategyInit(init, context) {
3707
4198
  const byteLengthSizeFunction = (chunk) => {
3708
4199
  return chunk.byteLength;
3709
4200
  };
3710
- try {
3711
- Object.defineProperty(byteLengthSizeFunction, 'name', {
3712
- value: 'size',
3713
- configurable: true
3714
- });
3715
- }
3716
- catch (_a) {
3717
- // This property is non-configurable in older browsers, so ignore if this throws.
3718
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
3719
- }
4201
+ setFunctionName(byteLengthSizeFunction, 'size');
3720
4202
  /**
3721
4203
  * A queuing strategy that counts the number of bytes in each chunk.
3722
4204
  *
@@ -3775,16 +4257,7 @@ function IsByteLengthQueuingStrategy(x) {
3775
4257
  const countSizeFunction = () => {
3776
4258
  return 1;
3777
4259
  };
3778
- try {
3779
- Object.defineProperty(countSizeFunction, 'name', {
3780
- value: 'size',
3781
- configurable: true
3782
- });
3783
- }
3784
- catch (_a) {
3785
- // This property is non-configurable in older browsers, so ignore if this throws.
3786
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
3787
- }
4260
+ setFunctionName(countSizeFunction, 'size');
3788
4261
  /**
3789
4262
  * A queuing strategy that counts the number of chunks.
3790
4263
  *
@@ -3842,12 +4315,16 @@ function IsCountQueuingStrategy(x) {
3842
4315
 
3843
4316
  function convertTransformer(original, context) {
3844
4317
  assertDictionary(original, context);
4318
+ const cancel = original === null || original === void 0 ? void 0 : original.cancel;
3845
4319
  const flush = original === null || original === void 0 ? void 0 : original.flush;
3846
4320
  const readableType = original === null || original === void 0 ? void 0 : original.readableType;
3847
4321
  const start = original === null || original === void 0 ? void 0 : original.start;
3848
4322
  const transform = original === null || original === void 0 ? void 0 : original.transform;
3849
4323
  const writableType = original === null || original === void 0 ? void 0 : original.writableType;
3850
4324
  return {
4325
+ cancel: cancel === undefined ?
4326
+ undefined :
4327
+ convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`),
3851
4328
  flush: flush === undefined ?
3852
4329
  undefined :
3853
4330
  convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
@@ -3873,6 +4350,10 @@ function convertTransformerTransformCallback(fn, original, context) {
3873
4350
  assertFunction(fn, context);
3874
4351
  return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
3875
4352
  }
4353
+ function convertTransformerCancelCallback(fn, original, context) {
4354
+ assertFunction(fn, context);
4355
+ return (reason) => promiseCall(fn, original, [reason]);
4356
+ }
3876
4357
 
3877
4358
  // Class TransformStream
3878
4359
  /**
@@ -3961,8 +4442,7 @@ function InitializeTransformStream(stream, startPromise, writableHighWaterMark,
3961
4442
  return TransformStreamDefaultSourcePullAlgorithm(stream);
3962
4443
  }
3963
4444
  function cancelAlgorithm(reason) {
3964
- TransformStreamErrorWritableAndUnblockWrite(stream, reason);
3965
- return promiseResolvedWith(undefined);
4445
+ return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);
3966
4446
  }
3967
4447
  stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
3968
4448
  // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
@@ -3989,6 +4469,9 @@ function TransformStreamError(stream, e) {
3989
4469
  function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
3990
4470
  TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
3991
4471
  WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
4472
+ TransformStreamUnblockWrite(stream);
4473
+ }
4474
+ function TransformStreamUnblockWrite(stream) {
3992
4475
  if (stream._backpressure) {
3993
4476
  // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
3994
4477
  // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
@@ -4059,6 +4542,9 @@ Object.defineProperties(TransformStreamDefaultController.prototype, {
4059
4542
  terminate: { enumerable: true },
4060
4543
  desiredSize: { enumerable: true }
4061
4544
  });
4545
+ setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');
4546
+ setFunctionName(TransformStreamDefaultController.prototype.error, 'error');
4547
+ setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');
4062
4548
  if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4063
4549
  Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
4064
4550
  value: 'TransformStreamDefaultController',
@@ -4075,35 +4561,53 @@ function IsTransformStreamDefaultController(x) {
4075
4561
  }
4076
4562
  return x instanceof TransformStreamDefaultController;
4077
4563
  }
4078
- function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) {
4564
+ function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
4079
4565
  controller._controlledTransformStream = stream;
4080
4566
  stream._transformStreamController = controller;
4081
4567
  controller._transformAlgorithm = transformAlgorithm;
4082
4568
  controller._flushAlgorithm = flushAlgorithm;
4569
+ controller._cancelAlgorithm = cancelAlgorithm;
4570
+ controller._finishPromise = undefined;
4571
+ controller._finishPromise_resolve = undefined;
4572
+ controller._finishPromise_reject = undefined;
4083
4573
  }
4084
4574
  function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
4085
4575
  const controller = Object.create(TransformStreamDefaultController.prototype);
4086
- let transformAlgorithm = (chunk) => {
4087
- try {
4088
- TransformStreamDefaultControllerEnqueue(controller, chunk);
4089
- return promiseResolvedWith(undefined);
4090
- }
4091
- catch (transformResultE) {
4092
- return promiseRejectedWith(transformResultE);
4093
- }
4094
- };
4095
- let flushAlgorithm = () => promiseResolvedWith(undefined);
4576
+ let transformAlgorithm;
4577
+ let flushAlgorithm;
4578
+ let cancelAlgorithm;
4096
4579
  if (transformer.transform !== undefined) {
4097
4580
  transformAlgorithm = chunk => transformer.transform(chunk, controller);
4098
4581
  }
4582
+ else {
4583
+ transformAlgorithm = chunk => {
4584
+ try {
4585
+ TransformStreamDefaultControllerEnqueue(controller, chunk);
4586
+ return promiseResolvedWith(undefined);
4587
+ }
4588
+ catch (transformResultE) {
4589
+ return promiseRejectedWith(transformResultE);
4590
+ }
4591
+ };
4592
+ }
4099
4593
  if (transformer.flush !== undefined) {
4100
4594
  flushAlgorithm = () => transformer.flush(controller);
4101
4595
  }
4102
- SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm);
4596
+ else {
4597
+ flushAlgorithm = () => promiseResolvedWith(undefined);
4598
+ }
4599
+ if (transformer.cancel !== undefined) {
4600
+ cancelAlgorithm = reason => transformer.cancel(reason);
4601
+ }
4602
+ else {
4603
+ cancelAlgorithm = () => promiseResolvedWith(undefined);
4604
+ }
4605
+ SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
4103
4606
  }
4104
4607
  function TransformStreamDefaultControllerClearAlgorithms(controller) {
4105
4608
  controller._transformAlgorithm = undefined;
4106
4609
  controller._flushAlgorithm = undefined;
4610
+ controller._cancelAlgorithm = undefined;
4107
4611
  }
4108
4612
  function TransformStreamDefaultControllerEnqueue(controller, chunk) {
4109
4613
  const stream = controller._controlledTransformStream;
@@ -4160,27 +4664,66 @@ function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
4160
4664
  return TransformStreamDefaultControllerPerformTransform(controller, chunk);
4161
4665
  }
4162
4666
  function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
4163
- // abort() is not called synchronously, so it is possible for abort() to be called when the stream is already
4164
- // errored.
4165
- TransformStreamError(stream, reason);
4166
- return promiseResolvedWith(undefined);
4667
+ const controller = stream._transformStreamController;
4668
+ if (controller._finishPromise !== undefined) {
4669
+ return controller._finishPromise;
4670
+ }
4671
+ // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4672
+ const readable = stream._readable;
4673
+ // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,
4674
+ // we don't run the _cancelAlgorithm again.
4675
+ controller._finishPromise = newPromise((resolve, reject) => {
4676
+ controller._finishPromise_resolve = resolve;
4677
+ controller._finishPromise_reject = reject;
4678
+ });
4679
+ const cancelPromise = controller._cancelAlgorithm(reason);
4680
+ TransformStreamDefaultControllerClearAlgorithms(controller);
4681
+ uponPromise(cancelPromise, () => {
4682
+ if (readable._state === 'errored') {
4683
+ defaultControllerFinishPromiseReject(controller, readable._storedError);
4684
+ }
4685
+ else {
4686
+ ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
4687
+ defaultControllerFinishPromiseResolve(controller);
4688
+ }
4689
+ return null;
4690
+ }, r => {
4691
+ ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4692
+ defaultControllerFinishPromiseReject(controller, r);
4693
+ return null;
4694
+ });
4695
+ return controller._finishPromise;
4167
4696
  }
4168
4697
  function TransformStreamDefaultSinkCloseAlgorithm(stream) {
4698
+ const controller = stream._transformStreamController;
4699
+ if (controller._finishPromise !== undefined) {
4700
+ return controller._finishPromise;
4701
+ }
4169
4702
  // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4170
4703
  const readable = stream._readable;
4171
- const controller = stream._transformStreamController;
4704
+ // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,
4705
+ // we don't also run the _cancelAlgorithm.
4706
+ controller._finishPromise = newPromise((resolve, reject) => {
4707
+ controller._finishPromise_resolve = resolve;
4708
+ controller._finishPromise_reject = reject;
4709
+ });
4172
4710
  const flushPromise = controller._flushAlgorithm();
4173
4711
  TransformStreamDefaultControllerClearAlgorithms(controller);
4174
- // Return a promise that is fulfilled with undefined on success.
4175
- return transformPromiseWith(flushPromise, () => {
4712
+ uponPromise(flushPromise, () => {
4176
4713
  if (readable._state === 'errored') {
4177
- throw readable._storedError;
4714
+ defaultControllerFinishPromiseReject(controller, readable._storedError);
4715
+ }
4716
+ else {
4717
+ ReadableStreamDefaultControllerClose(readable._readableStreamController);
4718
+ defaultControllerFinishPromiseResolve(controller);
4178
4719
  }
4179
- ReadableStreamDefaultControllerClose(readable._readableStreamController);
4720
+ return null;
4180
4721
  }, r => {
4181
- TransformStreamError(stream, r);
4182
- throw readable._storedError;
4722
+ ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4723
+ defaultControllerFinishPromiseReject(controller, r);
4724
+ return null;
4183
4725
  });
4726
+ return controller._finishPromise;
4184
4727
  }
4185
4728
  // TransformStreamDefaultSource Algorithms
4186
4729
  function TransformStreamDefaultSourcePullAlgorithm(stream) {
@@ -4189,10 +4732,61 @@ function TransformStreamDefaultSourcePullAlgorithm(stream) {
4189
4732
  // Prevent the next pull() call until there is backpressure.
4190
4733
  return stream._backpressureChangePromise;
4191
4734
  }
4735
+ function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) {
4736
+ const controller = stream._transformStreamController;
4737
+ if (controller._finishPromise !== undefined) {
4738
+ return controller._finishPromise;
4739
+ }
4740
+ // stream._writable cannot change after construction, so caching it across a call to user code is safe.
4741
+ const writable = stream._writable;
4742
+ // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or
4743
+ // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the
4744
+ // _flushAlgorithm.
4745
+ controller._finishPromise = newPromise((resolve, reject) => {
4746
+ controller._finishPromise_resolve = resolve;
4747
+ controller._finishPromise_reject = reject;
4748
+ });
4749
+ const cancelPromise = controller._cancelAlgorithm(reason);
4750
+ TransformStreamDefaultControllerClearAlgorithms(controller);
4751
+ uponPromise(cancelPromise, () => {
4752
+ if (writable._state === 'errored') {
4753
+ defaultControllerFinishPromiseReject(controller, writable._storedError);
4754
+ }
4755
+ else {
4756
+ WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
4757
+ TransformStreamUnblockWrite(stream);
4758
+ defaultControllerFinishPromiseResolve(controller);
4759
+ }
4760
+ return null;
4761
+ }, r => {
4762
+ WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);
4763
+ TransformStreamUnblockWrite(stream);
4764
+ defaultControllerFinishPromiseReject(controller, r);
4765
+ return null;
4766
+ });
4767
+ return controller._finishPromise;
4768
+ }
4192
4769
  // Helper functions for the TransformStreamDefaultController.
4193
4770
  function defaultControllerBrandCheckException(name) {
4194
4771
  return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
4195
4772
  }
4773
+ function defaultControllerFinishPromiseResolve(controller) {
4774
+ if (controller._finishPromise_resolve === undefined) {
4775
+ return;
4776
+ }
4777
+ controller._finishPromise_resolve();
4778
+ controller._finishPromise_resolve = undefined;
4779
+ controller._finishPromise_reject = undefined;
4780
+ }
4781
+ function defaultControllerFinishPromiseReject(controller, reason) {
4782
+ if (controller._finishPromise_reject === undefined) {
4783
+ return;
4784
+ }
4785
+ setPromiseIsHandledToTrue(controller._finishPromise);
4786
+ controller._finishPromise_reject(reason);
4787
+ controller._finishPromise_resolve = undefined;
4788
+ controller._finishPromise_reject = undefined;
4789
+ }
4196
4790
  // Helper functions for the TransformStream.
4197
4791
  function streamBrandCheckException(name) {
4198
4792
  return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);