source: node_modules/web-streams-polyfill/dist/ponyfill.es6.js

main
Last change on this file was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 211.7 KB
Line 
1/**
2 * @license
3 * web-streams-polyfill v3.3.2
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
7 */
8(function (global, factory) {
9 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
10 typeof define === 'function' && define.amd ? define(['exports'], factory) :
11 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {}));
12})(this, (function (exports) { 'use strict';
13
14 /// <reference lib="es2015.symbol" />
15 const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?
16 Symbol :
17 description => `Symbol(${description})`;
18
19 function noop() {
20 return undefined;
21 }
22
23 function typeIsObject(x) {
24 return (typeof x === 'object' && x !== null) || typeof x === 'function';
25 }
26 const rethrowAssertionErrorRejection = noop;
27 function setFunctionName(fn, name) {
28 try {
29 Object.defineProperty(fn, 'name', {
30 value: name,
31 configurable: true
32 });
33 }
34 catch (_a) {
35 // This property is non-configurable in older browsers, so ignore if this throws.
36 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility
37 }
38 }
39
40 const originalPromise = Promise;
41 const originalPromiseThen = Promise.prototype.then;
42 const originalPromiseReject = Promise.reject.bind(originalPromise);
43 // https://webidl.spec.whatwg.org/#a-new-promise
44 function newPromise(executor) {
45 return new originalPromise(executor);
46 }
47 // https://webidl.spec.whatwg.org/#a-promise-resolved-with
48 function promiseResolvedWith(value) {
49 return newPromise(resolve => resolve(value));
50 }
51 // https://webidl.spec.whatwg.org/#a-promise-rejected-with
52 function promiseRejectedWith(reason) {
53 return originalPromiseReject(reason);
54 }
55 function PerformPromiseThen(promise, onFulfilled, onRejected) {
56 // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an
57 // approximation.
58 return originalPromiseThen.call(promise, onFulfilled, onRejected);
59 }
60 // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned
61 // from that handler. To prevent this, return null instead of void from all handlers.
62 // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it
63 function uponPromise(promise, onFulfilled, onRejected) {
64 PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection);
65 }
66 function uponFulfillment(promise, onFulfilled) {
67 uponPromise(promise, onFulfilled);
68 }
69 function uponRejection(promise, onRejected) {
70 uponPromise(promise, undefined, onRejected);
71 }
72 function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) {
73 return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);
74 }
75 function setPromiseIsHandledToTrue(promise) {
76 PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);
77 }
78 let _queueMicrotask = callback => {
79 if (typeof queueMicrotask === 'function') {
80 _queueMicrotask = queueMicrotask;
81 }
82 else {
83 const resolvedPromise = promiseResolvedWith(undefined);
84 _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);
85 }
86 return _queueMicrotask(callback);
87 };
88 function reflectCall(F, V, args) {
89 if (typeof F !== 'function') {
90 throw new TypeError('Argument is not a function');
91 }
92 return Function.prototype.apply.call(F, V, args);
93 }
94 function promiseCall(F, V, args) {
95 try {
96 return promiseResolvedWith(reflectCall(F, V, args));
97 }
98 catch (value) {
99 return promiseRejectedWith(value);
100 }
101 }
102
103 // Original from Chromium
104 // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js
105 const QUEUE_MAX_ARRAY_SIZE = 16384;
106 /**
107 * Simple queue structure.
108 *
109 * Avoids scalability issues with using a packed array directly by using
110 * multiple arrays in a linked list and keeping the array size bounded.
111 */
112 class SimpleQueue {
113 constructor() {
114 this._cursor = 0;
115 this._size = 0;
116 // _front and _back are always defined.
117 this._front = {
118 _elements: [],
119 _next: undefined
120 };
121 this._back = this._front;
122 // The cursor is used to avoid calling Array.shift().
123 // It contains the index of the front element of the array inside the
124 // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).
125 this._cursor = 0;
126 // When there is only one node, size === elements.length - cursor.
127 this._size = 0;
128 }
129 get length() {
130 return this._size;
131 }
132 // For exception safety, this method is structured in order:
133 // 1. Read state
134 // 2. Calculate required state mutations
135 // 3. Perform state mutations
136 push(element) {
137 const oldBack = this._back;
138 let newBack = oldBack;
139 if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {
140 newBack = {
141 _elements: [],
142 _next: undefined
143 };
144 }
145 // push() is the mutation most likely to throw an exception, so it
146 // goes first.
147 oldBack._elements.push(element);
148 if (newBack !== oldBack) {
149 this._back = newBack;
150 oldBack._next = newBack;
151 }
152 ++this._size;
153 }
154 // Like push(), shift() follows the read -> calculate -> mutate pattern for
155 // exception safety.
156 shift() { // must not be called on an empty queue
157 const oldFront = this._front;
158 let newFront = oldFront;
159 const oldCursor = this._cursor;
160 let newCursor = oldCursor + 1;
161 const elements = oldFront._elements;
162 const element = elements[oldCursor];
163 if (newCursor === QUEUE_MAX_ARRAY_SIZE) {
164 newFront = oldFront._next;
165 newCursor = 0;
166 }
167 // No mutations before this point.
168 --this._size;
169 this._cursor = newCursor;
170 if (oldFront !== newFront) {
171 this._front = newFront;
172 }
173 // Permit shifted element to be garbage collected.
174 elements[oldCursor] = undefined;
175 return element;
176 }
177 // The tricky thing about forEach() is that it can be called
178 // re-entrantly. The queue may be mutated inside the callback. It is easy to
179 // see that push() within the callback has no negative effects since the end
180 // of the queue is checked for on every iteration. If shift() is called
181 // repeatedly within the callback then the next iteration may return an
182 // element that has been removed. In this case the callback will be called
183 // with undefined values until we either "catch up" with elements that still
184 // exist or reach the back of the queue.
185 forEach(callback) {
186 let i = this._cursor;
187 let node = this._front;
188 let elements = node._elements;
189 while (i !== elements.length || node._next !== undefined) {
190 if (i === elements.length) {
191 node = node._next;
192 elements = node._elements;
193 i = 0;
194 if (elements.length === 0) {
195 break;
196 }
197 }
198 callback(elements[i]);
199 ++i;
200 }
201 }
202 // Return the element that would be returned if shift() was called now,
203 // without modifying the queue.
204 peek() { // must not be called on an empty queue
205 const front = this._front;
206 const cursor = this._cursor;
207 return front._elements[cursor];
208 }
209 }
210
211 const AbortSteps = SymbolPolyfill('[[AbortSteps]]');
212 const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]');
213 const CancelSteps = SymbolPolyfill('[[CancelSteps]]');
214 const PullSteps = SymbolPolyfill('[[PullSteps]]');
215 const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]');
216
217 function ReadableStreamReaderGenericInitialize(reader, stream) {
218 reader._ownerReadableStream = stream;
219 stream._reader = reader;
220 if (stream._state === 'readable') {
221 defaultReaderClosedPromiseInitialize(reader);
222 }
223 else if (stream._state === 'closed') {
224 defaultReaderClosedPromiseInitializeAsResolved(reader);
225 }
226 else {
227 defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);
228 }
229 }
230 // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state
231 // check.
232 function ReadableStreamReaderGenericCancel(reader, reason) {
233 const stream = reader._ownerReadableStream;
234 return ReadableStreamCancel(stream, reason);
235 }
236 function ReadableStreamReaderGenericRelease(reader) {
237 const stream = reader._ownerReadableStream;
238 if (stream._state === 'readable') {
239 defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
240 }
241 else {
242 defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));
243 }
244 stream._readableStreamController[ReleaseSteps]();
245 stream._reader = undefined;
246 reader._ownerReadableStream = undefined;
247 }
248 // Helper functions for the readers.
249 function readerLockException(name) {
250 return new TypeError('Cannot ' + name + ' a stream using a released reader');
251 }
252 // Helper functions for the ReadableStreamDefaultReader.
253 function defaultReaderClosedPromiseInitialize(reader) {
254 reader._closedPromise = newPromise((resolve, reject) => {
255 reader._closedPromise_resolve = resolve;
256 reader._closedPromise_reject = reject;
257 });
258 }
259 function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) {
260 defaultReaderClosedPromiseInitialize(reader);
261 defaultReaderClosedPromiseReject(reader, reason);
262 }
263 function defaultReaderClosedPromiseInitializeAsResolved(reader) {
264 defaultReaderClosedPromiseInitialize(reader);
265 defaultReaderClosedPromiseResolve(reader);
266 }
267 function defaultReaderClosedPromiseReject(reader, reason) {
268 if (reader._closedPromise_reject === undefined) {
269 return;
270 }
271 setPromiseIsHandledToTrue(reader._closedPromise);
272 reader._closedPromise_reject(reason);
273 reader._closedPromise_resolve = undefined;
274 reader._closedPromise_reject = undefined;
275 }
276 function defaultReaderClosedPromiseResetToRejected(reader, reason) {
277 defaultReaderClosedPromiseInitializeAsRejected(reader, reason);
278 }
279 function defaultReaderClosedPromiseResolve(reader) {
280 if (reader._closedPromise_resolve === undefined) {
281 return;
282 }
283 reader._closedPromise_resolve(undefined);
284 reader._closedPromise_resolve = undefined;
285 reader._closedPromise_reject = undefined;
286 }
287
288 /// <reference lib="es2015.core" />
289 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill
290 const NumberIsFinite = Number.isFinite || function (x) {
291 return typeof x === 'number' && isFinite(x);
292 };
293
294 /// <reference lib="es2015.core" />
295 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill
296 const MathTrunc = Math.trunc || function (v) {
297 return v < 0 ? Math.ceil(v) : Math.floor(v);
298 };
299
300 // https://heycam.github.io/webidl/#idl-dictionaries
301 function isDictionary(x) {
302 return typeof x === 'object' || typeof x === 'function';
303 }
304 function assertDictionary(obj, context) {
305 if (obj !== undefined && !isDictionary(obj)) {
306 throw new TypeError(`${context} is not an object.`);
307 }
308 }
309 // https://heycam.github.io/webidl/#idl-callback-functions
310 function assertFunction(x, context) {
311 if (typeof x !== 'function') {
312 throw new TypeError(`${context} is not a function.`);
313 }
314 }
315 // https://heycam.github.io/webidl/#idl-object
316 function isObject(x) {
317 return (typeof x === 'object' && x !== null) || typeof x === 'function';
318 }
319 function assertObject(x, context) {
320 if (!isObject(x)) {
321 throw new TypeError(`${context} is not an object.`);
322 }
323 }
324 function assertRequiredArgument(x, position, context) {
325 if (x === undefined) {
326 throw new TypeError(`Parameter ${position} is required in '${context}'.`);
327 }
328 }
329 function assertRequiredField(x, field, context) {
330 if (x === undefined) {
331 throw new TypeError(`${field} is required in '${context}'.`);
332 }
333 }
334 // https://heycam.github.io/webidl/#idl-unrestricted-double
335 function convertUnrestrictedDouble(value) {
336 return Number(value);
337 }
338 function censorNegativeZero(x) {
339 return x === 0 ? 0 : x;
340 }
341 function integerPart(x) {
342 return censorNegativeZero(MathTrunc(x));
343 }
344 // https://heycam.github.io/webidl/#idl-unsigned-long-long
345 function convertUnsignedLongLongWithEnforceRange(value, context) {
346 const lowerBound = 0;
347 const upperBound = Number.MAX_SAFE_INTEGER;
348 let x = Number(value);
349 x = censorNegativeZero(x);
350 if (!NumberIsFinite(x)) {
351 throw new TypeError(`${context} is not a finite number`);
352 }
353 x = integerPart(x);
354 if (x < lowerBound || x > upperBound) {
355 throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);
356 }
357 if (!NumberIsFinite(x) || x === 0) {
358 return 0;
359 }
360 // TODO Use BigInt if supported?
361 // let xBigInt = BigInt(integerPart(x));
362 // xBigInt = BigInt.asUintN(64, xBigInt);
363 // return Number(xBigInt);
364 return x;
365 }
366
367 function assertReadableStream(x, context) {
368 if (!IsReadableStream(x)) {
369 throw new TypeError(`${context} is not a ReadableStream.`);
370 }
371 }
372
373 // Abstract operations for the ReadableStream.
374 function AcquireReadableStreamDefaultReader(stream) {
375 return new ReadableStreamDefaultReader(stream);
376 }
377 // ReadableStream API exposed for controllers.
378 function ReadableStreamAddReadRequest(stream, readRequest) {
379 stream._reader._readRequests.push(readRequest);
380 }
381 function ReadableStreamFulfillReadRequest(stream, chunk, done) {
382 const reader = stream._reader;
383 const readRequest = reader._readRequests.shift();
384 if (done) {
385 readRequest._closeSteps();
386 }
387 else {
388 readRequest._chunkSteps(chunk);
389 }
390 }
391 function ReadableStreamGetNumReadRequests(stream) {
392 return stream._reader._readRequests.length;
393 }
394 function ReadableStreamHasDefaultReader(stream) {
395 const reader = stream._reader;
396 if (reader === undefined) {
397 return false;
398 }
399 if (!IsReadableStreamDefaultReader(reader)) {
400 return false;
401 }
402 return true;
403 }
404 /**
405 * A default reader vended by a {@link ReadableStream}.
406 *
407 * @public
408 */
409 class ReadableStreamDefaultReader {
410 constructor(stream) {
411 assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');
412 assertReadableStream(stream, 'First parameter');
413 if (IsReadableStreamLocked(stream)) {
414 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
415 }
416 ReadableStreamReaderGenericInitialize(this, stream);
417 this._readRequests = new SimpleQueue();
418 }
419 /**
420 * Returns a promise that will be fulfilled when the stream becomes closed,
421 * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
422 */
423 get closed() {
424 if (!IsReadableStreamDefaultReader(this)) {
425 return promiseRejectedWith(defaultReaderBrandCheckException('closed'));
426 }
427 return this._closedPromise;
428 }
429 /**
430 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
431 */
432 cancel(reason = undefined) {
433 if (!IsReadableStreamDefaultReader(this)) {
434 return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));
435 }
436 if (this._ownerReadableStream === undefined) {
437 return promiseRejectedWith(readerLockException('cancel'));
438 }
439 return ReadableStreamReaderGenericCancel(this, reason);
440 }
441 /**
442 * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
443 *
444 * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
445 */
446 read() {
447 if (!IsReadableStreamDefaultReader(this)) {
448 return promiseRejectedWith(defaultReaderBrandCheckException('read'));
449 }
450 if (this._ownerReadableStream === undefined) {
451 return promiseRejectedWith(readerLockException('read from'));
452 }
453 let resolvePromise;
454 let rejectPromise;
455 const promise = newPromise((resolve, reject) => {
456 resolvePromise = resolve;
457 rejectPromise = reject;
458 });
459 const readRequest = {
460 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
461 _closeSteps: () => resolvePromise({ value: undefined, done: true }),
462 _errorSteps: e => rejectPromise(e)
463 };
464 ReadableStreamDefaultReaderRead(this, readRequest);
465 return promise;
466 }
467 /**
468 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
469 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
470 * from now on; otherwise, the reader will appear closed.
471 *
472 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
473 * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
474 * do so will throw a `TypeError` and leave the reader locked to the stream.
475 */
476 releaseLock() {
477 if (!IsReadableStreamDefaultReader(this)) {
478 throw defaultReaderBrandCheckException('releaseLock');
479 }
480 if (this._ownerReadableStream === undefined) {
481 return;
482 }
483 ReadableStreamDefaultReaderRelease(this);
484 }
485 }
486 Object.defineProperties(ReadableStreamDefaultReader.prototype, {
487 cancel: { enumerable: true },
488 read: { enumerable: true },
489 releaseLock: { enumerable: true },
490 closed: { enumerable: true }
491 });
492 setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');
493 setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');
494 setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');
495 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
496 Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, {
497 value: 'ReadableStreamDefaultReader',
498 configurable: true
499 });
500 }
501 // Abstract operations for the readers.
502 function IsReadableStreamDefaultReader(x) {
503 if (!typeIsObject(x)) {
504 return false;
505 }
506 if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {
507 return false;
508 }
509 return x instanceof ReadableStreamDefaultReader;
510 }
511 function ReadableStreamDefaultReaderRead(reader, readRequest) {
512 const stream = reader._ownerReadableStream;
513 stream._disturbed = true;
514 if (stream._state === 'closed') {
515 readRequest._closeSteps();
516 }
517 else if (stream._state === 'errored') {
518 readRequest._errorSteps(stream._storedError);
519 }
520 else {
521 stream._readableStreamController[PullSteps](readRequest);
522 }
523 }
524 function ReadableStreamDefaultReaderRelease(reader) {
525 ReadableStreamReaderGenericRelease(reader);
526 const e = new TypeError('Reader was released');
527 ReadableStreamDefaultReaderErrorReadRequests(reader, e);
528 }
529 function ReadableStreamDefaultReaderErrorReadRequests(reader, e) {
530 const readRequests = reader._readRequests;
531 reader._readRequests = new SimpleQueue();
532 readRequests.forEach(readRequest => {
533 readRequest._errorSteps(e);
534 });
535 }
536 // Helper functions for the ReadableStreamDefaultReader.
537 function defaultReaderBrandCheckException(name) {
538 return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);
539 }
540
541 /// <reference lib="es2018.asynciterable" />
542 let AsyncIteratorPrototype;
543 if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
544 // We're running inside a ES2018+ environment, but we're compiling to an older syntax.
545 // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.
546 AsyncIteratorPrototype = {
547 // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )
548 // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator
549 [SymbolPolyfill.asyncIterator]() {
550 return this;
551 }
552 };
553 Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false });
554 }
555
556 /// <reference lib="es2018.asynciterable" />
557 class ReadableStreamAsyncIteratorImpl {
558 constructor(reader, preventCancel) {
559 this._ongoingPromise = undefined;
560 this._isFinished = false;
561 this._reader = reader;
562 this._preventCancel = preventCancel;
563 }
564 next() {
565 const nextSteps = () => this._nextSteps();
566 this._ongoingPromise = this._ongoingPromise ?
567 transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :
568 nextSteps();
569 return this._ongoingPromise;
570 }
571 return(value) {
572 const returnSteps = () => this._returnSteps(value);
573 return this._ongoingPromise ?
574 transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :
575 returnSteps();
576 }
577 _nextSteps() {
578 if (this._isFinished) {
579 return Promise.resolve({ value: undefined, done: true });
580 }
581 const reader = this._reader;
582 let resolvePromise;
583 let rejectPromise;
584 const promise = newPromise((resolve, reject) => {
585 resolvePromise = resolve;
586 rejectPromise = reject;
587 });
588 const readRequest = {
589 _chunkSteps: chunk => {
590 this._ongoingPromise = undefined;
591 // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.
592 // FIXME Is this a bug in the specification, or in the test?
593 _queueMicrotask(() => resolvePromise({ value: chunk, done: false }));
594 },
595 _closeSteps: () => {
596 this._ongoingPromise = undefined;
597 this._isFinished = true;
598 ReadableStreamReaderGenericRelease(reader);
599 resolvePromise({ value: undefined, done: true });
600 },
601 _errorSteps: reason => {
602 this._ongoingPromise = undefined;
603 this._isFinished = true;
604 ReadableStreamReaderGenericRelease(reader);
605 rejectPromise(reason);
606 }
607 };
608 ReadableStreamDefaultReaderRead(reader, readRequest);
609 return promise;
610 }
611 _returnSteps(value) {
612 if (this._isFinished) {
613 return Promise.resolve({ value, done: true });
614 }
615 this._isFinished = true;
616 const reader = this._reader;
617 if (!this._preventCancel) {
618 const result = ReadableStreamReaderGenericCancel(reader, value);
619 ReadableStreamReaderGenericRelease(reader);
620 return transformPromiseWith(result, () => ({ value, done: true }));
621 }
622 ReadableStreamReaderGenericRelease(reader);
623 return promiseResolvedWith({ value, done: true });
624 }
625 }
626 const ReadableStreamAsyncIteratorPrototype = {
627 next() {
628 if (!IsReadableStreamAsyncIterator(this)) {
629 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));
630 }
631 return this._asyncIteratorImpl.next();
632 },
633 return(value) {
634 if (!IsReadableStreamAsyncIterator(this)) {
635 return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));
636 }
637 return this._asyncIteratorImpl.return(value);
638 }
639 };
640 if (AsyncIteratorPrototype !== undefined) {
641 Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);
642 }
643 // Abstract operations for the ReadableStream.
644 function AcquireReadableStreamAsyncIterator(stream, preventCancel) {
645 const reader = AcquireReadableStreamDefaultReader(stream);
646 const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);
647 const iterator = Object.create(ReadableStreamAsyncIteratorPrototype);
648 iterator._asyncIteratorImpl = impl;
649 return iterator;
650 }
651 function IsReadableStreamAsyncIterator(x) {
652 if (!typeIsObject(x)) {
653 return false;
654 }
655 if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {
656 return false;
657 }
658 try {
659 // noinspection SuspiciousTypeOfGuard
660 return x._asyncIteratorImpl instanceof
661 ReadableStreamAsyncIteratorImpl;
662 }
663 catch (_a) {
664 return false;
665 }
666 }
667 // Helper functions for the ReadableStream.
668 function streamAsyncIteratorBrandCheckException(name) {
669 return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);
670 }
671
672 /// <reference lib="es2015.core" />
673 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill
674 const NumberIsNaN = Number.isNaN || function (x) {
675 // eslint-disable-next-line no-self-compare
676 return x !== x;
677 };
678
679 /******************************************************************************
680 Copyright (c) Microsoft Corporation.
681
682 Permission to use, copy, modify, and/or distribute this software for any
683 purpose with or without fee is hereby granted.
684
685 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
686 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
687 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
688 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
689 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
690 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
691 PERFORMANCE OF THIS SOFTWARE.
692 ***************************************************************************** */
693 /* global Reflect, Promise, SuppressedError, Symbol */
694
695
696 function __values(o) {
697 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
698 if (m) return m.call(o);
699 if (o && typeof o.length === "number") return {
700 next: function () {
701 if (o && i >= o.length) o = void 0;
702 return { value: o && o[i++], done: !o };
703 }
704 };
705 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
706 }
707
708 function __await(v) {
709 return this instanceof __await ? (this.v = v, this) : new __await(v);
710 }
711
712 function __asyncGenerator(thisArg, _arguments, generator) {
713 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
714 var g = generator.apply(thisArg, _arguments || []), i, q = [];
715 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
716 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); }); }; }
717 function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
718 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
719 function fulfill(value) { resume("next", value); }
720 function reject(value) { resume("throw", value); }
721 function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
722 }
723
724 function __asyncDelegator(o) {
725 var i, p;
726 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
727 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; }
728 }
729
730 function __asyncValues(o) {
731 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
732 var m = o[Symbol.asyncIterator], i;
733 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);
734 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); }); }; }
735 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
736 }
737
738 typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
739 var e = new Error(message);
740 return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
741 };
742
743 function CreateArrayFromList(elements) {
744 // We use arrays to represent lists, so this is basically a no-op.
745 // Do a slice though just in case we happen to depend on the unique-ness.
746 return elements.slice();
747 }
748 function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) {
749 new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);
750 }
751 let TransferArrayBuffer = (O) => {
752 if (typeof O.transfer === 'function') {
753 TransferArrayBuffer = buffer => buffer.transfer();
754 }
755 else if (typeof structuredClone === 'function') {
756 TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });
757 }
758 else {
759 // Not implemented correctly
760 TransferArrayBuffer = buffer => buffer;
761 }
762 return TransferArrayBuffer(O);
763 };
764 let IsDetachedBuffer = (O) => {
765 if (typeof O.detached === 'boolean') {
766 IsDetachedBuffer = buffer => buffer.detached;
767 }
768 else {
769 // Not implemented correctly
770 IsDetachedBuffer = buffer => buffer.byteLength === 0;
771 }
772 return IsDetachedBuffer(O);
773 };
774 function ArrayBufferSlice(buffer, begin, end) {
775 // ArrayBuffer.prototype.slice is not available on IE10
776 // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice
777 if (buffer.slice) {
778 return buffer.slice(begin, end);
779 }
780 const length = end - begin;
781 const slice = new ArrayBuffer(length);
782 CopyDataBlockBytes(slice, 0, buffer, begin, length);
783 return slice;
784 }
785 function GetMethod(receiver, prop) {
786 const func = receiver[prop];
787 if (func === undefined || func === null) {
788 return undefined;
789 }
790 if (typeof func !== 'function') {
791 throw new TypeError(`${String(prop)} is not a function`);
792 }
793 return func;
794 }
795 function CreateAsyncFromSyncIterator(syncIteratorRecord) {
796 // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,
797 // we use yield* inside an async generator function to achieve the same result.
798 // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.
799 const syncIterable = {
800 [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator
801 };
802 // Create an async generator function and immediately invoke it.
803 const asyncIterator = (function () {
804 return __asyncGenerator(this, arguments, function* () {
805 return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable))));
806 });
807 }());
808 // Return as an async iterator record.
809 const nextMethod = asyncIterator.next;
810 return { iterator: asyncIterator, nextMethod, done: false };
811 }
812 function GetIterator(obj, hint = 'sync', method) {
813 if (method === undefined) {
814 if (hint === 'async') {
815 method = GetMethod(obj, SymbolPolyfill.asyncIterator);
816 if (method === undefined) {
817 const syncMethod = GetMethod(obj, SymbolPolyfill.iterator);
818 const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod);
819 return CreateAsyncFromSyncIterator(syncIteratorRecord);
820 }
821 }
822 else {
823 method = GetMethod(obj, SymbolPolyfill.iterator);
824 }
825 }
826 if (method === undefined) {
827 throw new TypeError('The object is not iterable');
828 }
829 const iterator = reflectCall(method, obj, []);
830 if (!typeIsObject(iterator)) {
831 throw new TypeError('The iterator method must return an object');
832 }
833 const nextMethod = iterator.next;
834 return { iterator, nextMethod, done: false };
835 }
836 function IteratorNext(iteratorRecord) {
837 const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);
838 if (!typeIsObject(result)) {
839 throw new TypeError('The iterator.next() method must return an object');
840 }
841 return result;
842 }
843 function IteratorComplete(iterResult) {
844 return Boolean(iterResult.done);
845 }
846 function IteratorValue(iterResult) {
847 return iterResult.value;
848 }
849
850 function IsNonNegativeNumber(v) {
851 if (typeof v !== 'number') {
852 return false;
853 }
854 if (NumberIsNaN(v)) {
855 return false;
856 }
857 if (v < 0) {
858 return false;
859 }
860 return true;
861 }
862 function CloneAsUint8Array(O) {
863 const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);
864 return new Uint8Array(buffer);
865 }
866
867 function DequeueValue(container) {
868 const pair = container._queue.shift();
869 container._queueTotalSize -= pair.size;
870 if (container._queueTotalSize < 0) {
871 container._queueTotalSize = 0;
872 }
873 return pair.value;
874 }
875 function EnqueueValueWithSize(container, value, size) {
876 if (!IsNonNegativeNumber(size) || size === Infinity) {
877 throw new RangeError('Size must be a finite, non-NaN, non-negative number.');
878 }
879 container._queue.push({ value, size });
880 container._queueTotalSize += size;
881 }
882 function PeekQueueValue(container) {
883 const pair = container._queue.peek();
884 return pair.value;
885 }
886 function ResetQueue(container) {
887 container._queue = new SimpleQueue();
888 container._queueTotalSize = 0;
889 }
890
891 function isDataViewConstructor(ctor) {
892 return ctor === DataView;
893 }
894 function isDataView(view) {
895 return isDataViewConstructor(view.constructor);
896 }
897 function arrayBufferViewElementSize(ctor) {
898 if (isDataViewConstructor(ctor)) {
899 return 1;
900 }
901 return ctor.BYTES_PER_ELEMENT;
902 }
903
904 /**
905 * A pull-into request in a {@link ReadableByteStreamController}.
906 *
907 * @public
908 */
909 class ReadableStreamBYOBRequest {
910 constructor() {
911 throw new TypeError('Illegal constructor');
912 }
913 /**
914 * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
915 */
916 get view() {
917 if (!IsReadableStreamBYOBRequest(this)) {
918 throw byobRequestBrandCheckException('view');
919 }
920 return this._view;
921 }
922 respond(bytesWritten) {
923 if (!IsReadableStreamBYOBRequest(this)) {
924 throw byobRequestBrandCheckException('respond');
925 }
926 assertRequiredArgument(bytesWritten, 1, 'respond');
927 bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');
928 if (this._associatedReadableByteStreamController === undefined) {
929 throw new TypeError('This BYOB request has been invalidated');
930 }
931 if (IsDetachedBuffer(this._view.buffer)) {
932 throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);
933 }
934 ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);
935 }
936 respondWithNewView(view) {
937 if (!IsReadableStreamBYOBRequest(this)) {
938 throw byobRequestBrandCheckException('respondWithNewView');
939 }
940 assertRequiredArgument(view, 1, 'respondWithNewView');
941 if (!ArrayBuffer.isView(view)) {
942 throw new TypeError('You can only respond with array buffer views');
943 }
944 if (this._associatedReadableByteStreamController === undefined) {
945 throw new TypeError('This BYOB request has been invalidated');
946 }
947 if (IsDetachedBuffer(view.buffer)) {
948 throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response');
949 }
950 ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);
951 }
952 }
953 Object.defineProperties(ReadableStreamBYOBRequest.prototype, {
954 respond: { enumerable: true },
955 respondWithNewView: { enumerable: true },
956 view: { enumerable: true }
957 });
958 setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');
959 setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');
960 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
961 Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, {
962 value: 'ReadableStreamBYOBRequest',
963 configurable: true
964 });
965 }
966 /**
967 * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
968 *
969 * @public
970 */
971 class ReadableByteStreamController {
972 constructor() {
973 throw new TypeError('Illegal constructor');
974 }
975 /**
976 * Returns the current BYOB pull request, or `null` if there isn't one.
977 */
978 get byobRequest() {
979 if (!IsReadableByteStreamController(this)) {
980 throw byteStreamControllerBrandCheckException('byobRequest');
981 }
982 return ReadableByteStreamControllerGetBYOBRequest(this);
983 }
984 /**
985 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
986 * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
987 */
988 get desiredSize() {
989 if (!IsReadableByteStreamController(this)) {
990 throw byteStreamControllerBrandCheckException('desiredSize');
991 }
992 return ReadableByteStreamControllerGetDesiredSize(this);
993 }
994 /**
995 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
996 * the stream, but once those are read, the stream will become closed.
997 */
998 close() {
999 if (!IsReadableByteStreamController(this)) {
1000 throw byteStreamControllerBrandCheckException('close');
1001 }
1002 if (this._closeRequested) {
1003 throw new TypeError('The stream has already been closed; do not close it again!');
1004 }
1005 const state = this._controlledReadableByteStream._state;
1006 if (state !== 'readable') {
1007 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);
1008 }
1009 ReadableByteStreamControllerClose(this);
1010 }
1011 enqueue(chunk) {
1012 if (!IsReadableByteStreamController(this)) {
1013 throw byteStreamControllerBrandCheckException('enqueue');
1014 }
1015 assertRequiredArgument(chunk, 1, 'enqueue');
1016 if (!ArrayBuffer.isView(chunk)) {
1017 throw new TypeError('chunk must be an array buffer view');
1018 }
1019 if (chunk.byteLength === 0) {
1020 throw new TypeError('chunk must have non-zero byteLength');
1021 }
1022 if (chunk.buffer.byteLength === 0) {
1023 throw new TypeError(`chunk's buffer must have non-zero byteLength`);
1024 }
1025 if (this._closeRequested) {
1026 throw new TypeError('stream is closed or draining');
1027 }
1028 const state = this._controlledReadableByteStream._state;
1029 if (state !== 'readable') {
1030 throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);
1031 }
1032 ReadableByteStreamControllerEnqueue(this, chunk);
1033 }
1034 /**
1035 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
1036 */
1037 error(e = undefined) {
1038 if (!IsReadableByteStreamController(this)) {
1039 throw byteStreamControllerBrandCheckException('error');
1040 }
1041 ReadableByteStreamControllerError(this, e);
1042 }
1043 /** @internal */
1044 [CancelSteps](reason) {
1045 ReadableByteStreamControllerClearPendingPullIntos(this);
1046 ResetQueue(this);
1047 const result = this._cancelAlgorithm(reason);
1048 ReadableByteStreamControllerClearAlgorithms(this);
1049 return result;
1050 }
1051 /** @internal */
1052 [PullSteps](readRequest) {
1053 const stream = this._controlledReadableByteStream;
1054 if (this._queueTotalSize > 0) {
1055 ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);
1056 return;
1057 }
1058 const autoAllocateChunkSize = this._autoAllocateChunkSize;
1059 if (autoAllocateChunkSize !== undefined) {
1060 let buffer;
1061 try {
1062 buffer = new ArrayBuffer(autoAllocateChunkSize);
1063 }
1064 catch (bufferE) {
1065 readRequest._errorSteps(bufferE);
1066 return;
1067 }
1068 const pullIntoDescriptor = {
1069 buffer,
1070 bufferByteLength: autoAllocateChunkSize,
1071 byteOffset: 0,
1072 byteLength: autoAllocateChunkSize,
1073 bytesFilled: 0,
1074 minimumFill: 1,
1075 elementSize: 1,
1076 viewConstructor: Uint8Array,
1077 readerType: 'default'
1078 };
1079 this._pendingPullIntos.push(pullIntoDescriptor);
1080 }
1081 ReadableStreamAddReadRequest(stream, readRequest);
1082 ReadableByteStreamControllerCallPullIfNeeded(this);
1083 }
1084 /** @internal */
1085 [ReleaseSteps]() {
1086 if (this._pendingPullIntos.length > 0) {
1087 const firstPullInto = this._pendingPullIntos.peek();
1088 firstPullInto.readerType = 'none';
1089 this._pendingPullIntos = new SimpleQueue();
1090 this._pendingPullIntos.push(firstPullInto);
1091 }
1092 }
1093 }
1094 Object.defineProperties(ReadableByteStreamController.prototype, {
1095 close: { enumerable: true },
1096 enqueue: { enumerable: true },
1097 error: { enumerable: true },
1098 byobRequest: { enumerable: true },
1099 desiredSize: { enumerable: true }
1100 });
1101 setFunctionName(ReadableByteStreamController.prototype.close, 'close');
1102 setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');
1103 setFunctionName(ReadableByteStreamController.prototype.error, 'error');
1104 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1105 Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, {
1106 value: 'ReadableByteStreamController',
1107 configurable: true
1108 });
1109 }
1110 // Abstract operations for the ReadableByteStreamController.
1111 function IsReadableByteStreamController(x) {
1112 if (!typeIsObject(x)) {
1113 return false;
1114 }
1115 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {
1116 return false;
1117 }
1118 return x instanceof ReadableByteStreamController;
1119 }
1120 function IsReadableStreamBYOBRequest(x) {
1121 if (!typeIsObject(x)) {
1122 return false;
1123 }
1124 if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {
1125 return false;
1126 }
1127 return x instanceof ReadableStreamBYOBRequest;
1128 }
1129 function ReadableByteStreamControllerCallPullIfNeeded(controller) {
1130 const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);
1131 if (!shouldPull) {
1132 return;
1133 }
1134 if (controller._pulling) {
1135 controller._pullAgain = true;
1136 return;
1137 }
1138 controller._pulling = true;
1139 // TODO: Test controller argument
1140 const pullPromise = controller._pullAlgorithm();
1141 uponPromise(pullPromise, () => {
1142 controller._pulling = false;
1143 if (controller._pullAgain) {
1144 controller._pullAgain = false;
1145 ReadableByteStreamControllerCallPullIfNeeded(controller);
1146 }
1147 return null;
1148 }, e => {
1149 ReadableByteStreamControllerError(controller, e);
1150 return null;
1151 });
1152 }
1153 function ReadableByteStreamControllerClearPendingPullIntos(controller) {
1154 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1155 controller._pendingPullIntos = new SimpleQueue();
1156 }
1157 function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) {
1158 let done = false;
1159 if (stream._state === 'closed') {
1160 done = true;
1161 }
1162 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
1163 if (pullIntoDescriptor.readerType === 'default') {
1164 ReadableStreamFulfillReadRequest(stream, filledView, done);
1165 }
1166 else {
1167 ReadableStreamFulfillReadIntoRequest(stream, filledView, done);
1168 }
1169 }
1170 function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) {
1171 const bytesFilled = pullIntoDescriptor.bytesFilled;
1172 const elementSize = pullIntoDescriptor.elementSize;
1173 return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize);
1174 }
1175 function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) {
1176 controller._queue.push({ buffer, byteOffset, byteLength });
1177 controller._queueTotalSize += byteLength;
1178 }
1179 function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) {
1180 let clonedChunk;
1181 try {
1182 clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);
1183 }
1184 catch (cloneE) {
1185 ReadableByteStreamControllerError(controller, cloneE);
1186 throw cloneE;
1187 }
1188 ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);
1189 }
1190 function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) {
1191 if (firstDescriptor.bytesFilled > 0) {
1192 ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled);
1193 }
1194 ReadableByteStreamControllerShiftPendingPullInto(controller);
1195 }
1196 function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) {
1197 const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);
1198 const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;
1199 let totalBytesToCopyRemaining = maxBytesToCopy;
1200 let ready = false;
1201 const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;
1202 const maxAlignedBytes = maxBytesFilled - remainderBytes;
1203 // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1204 // of the queue, so the underlying source can keep filling it.
1205 if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {
1206 totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;
1207 ready = true;
1208 }
1209 const queue = controller._queue;
1210 while (totalBytesToCopyRemaining > 0) {
1211 const headOfQueue = queue.peek();
1212 const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);
1213 const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
1214 CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);
1215 if (headOfQueue.byteLength === bytesToCopy) {
1216 queue.shift();
1217 }
1218 else {
1219 headOfQueue.byteOffset += bytesToCopy;
1220 headOfQueue.byteLength -= bytesToCopy;
1221 }
1222 controller._queueTotalSize -= bytesToCopy;
1223 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);
1224 totalBytesToCopyRemaining -= bytesToCopy;
1225 }
1226 return ready;
1227 }
1228 function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) {
1229 pullIntoDescriptor.bytesFilled += size;
1230 }
1231 function ReadableByteStreamControllerHandleQueueDrain(controller) {
1232 if (controller._queueTotalSize === 0 && controller._closeRequested) {
1233 ReadableByteStreamControllerClearAlgorithms(controller);
1234 ReadableStreamClose(controller._controlledReadableByteStream);
1235 }
1236 else {
1237 ReadableByteStreamControllerCallPullIfNeeded(controller);
1238 }
1239 }
1240 function ReadableByteStreamControllerInvalidateBYOBRequest(controller) {
1241 if (controller._byobRequest === null) {
1242 return;
1243 }
1244 controller._byobRequest._associatedReadableByteStreamController = undefined;
1245 controller._byobRequest._view = null;
1246 controller._byobRequest = null;
1247 }
1248 function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) {
1249 while (controller._pendingPullIntos.length > 0) {
1250 if (controller._queueTotalSize === 0) {
1251 return;
1252 }
1253 const pullIntoDescriptor = controller._pendingPullIntos.peek();
1254 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
1255 ReadableByteStreamControllerShiftPendingPullInto(controller);
1256 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
1257 }
1258 }
1259 }
1260 function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) {
1261 const reader = controller._controlledReadableByteStream._reader;
1262 while (reader._readRequests.length > 0) {
1263 if (controller._queueTotalSize === 0) {
1264 return;
1265 }
1266 const readRequest = reader._readRequests.shift();
1267 ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);
1268 }
1269 }
1270 function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) {
1271 const stream = controller._controlledReadableByteStream;
1272 const ctor = view.constructor;
1273 const elementSize = arrayBufferViewElementSize(ctor);
1274 const { byteOffset, byteLength } = view;
1275 const minimumFill = min * elementSize;
1276 let buffer;
1277 try {
1278 buffer = TransferArrayBuffer(view.buffer);
1279 }
1280 catch (e) {
1281 readIntoRequest._errorSteps(e);
1282 return;
1283 }
1284 const pullIntoDescriptor = {
1285 buffer,
1286 bufferByteLength: buffer.byteLength,
1287 byteOffset,
1288 byteLength,
1289 bytesFilled: 0,
1290 minimumFill,
1291 elementSize,
1292 viewConstructor: ctor,
1293 readerType: 'byob'
1294 };
1295 if (controller._pendingPullIntos.length > 0) {
1296 controller._pendingPullIntos.push(pullIntoDescriptor);
1297 // No ReadableByteStreamControllerCallPullIfNeeded() call since:
1298 // - No change happens on desiredSize
1299 // - The source has already been notified of that there's at least 1 pending read(view)
1300 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
1301 return;
1302 }
1303 if (stream._state === 'closed') {
1304 const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);
1305 readIntoRequest._closeSteps(emptyView);
1306 return;
1307 }
1308 if (controller._queueTotalSize > 0) {
1309 if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {
1310 const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);
1311 ReadableByteStreamControllerHandleQueueDrain(controller);
1312 readIntoRequest._chunkSteps(filledView);
1313 return;
1314 }
1315 if (controller._closeRequested) {
1316 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
1317 ReadableByteStreamControllerError(controller, e);
1318 readIntoRequest._errorSteps(e);
1319 return;
1320 }
1321 }
1322 controller._pendingPullIntos.push(pullIntoDescriptor);
1323 ReadableStreamAddReadIntoRequest(stream, readIntoRequest);
1324 ReadableByteStreamControllerCallPullIfNeeded(controller);
1325 }
1326 function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) {
1327 if (firstDescriptor.readerType === 'none') {
1328 ReadableByteStreamControllerShiftPendingPullInto(controller);
1329 }
1330 const stream = controller._controlledReadableByteStream;
1331 if (ReadableStreamHasBYOBReader(stream)) {
1332 while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {
1333 const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);
1334 ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);
1335 }
1336 }
1337 }
1338 function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) {
1339 ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);
1340 if (pullIntoDescriptor.readerType === 'none') {
1341 ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);
1342 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1343 return;
1344 }
1345 if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {
1346 // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head
1347 // of the queue, so the underlying source can keep filling it.
1348 return;
1349 }
1350 ReadableByteStreamControllerShiftPendingPullInto(controller);
1351 const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;
1352 if (remainderSize > 0) {
1353 const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;
1354 ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize);
1355 }
1356 pullIntoDescriptor.bytesFilled -= remainderSize;
1357 ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);
1358 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1359 }
1360 function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) {
1361 const firstDescriptor = controller._pendingPullIntos.peek();
1362 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1363 const state = controller._controlledReadableByteStream._state;
1364 if (state === 'closed') {
1365 ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);
1366 }
1367 else {
1368 ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);
1369 }
1370 ReadableByteStreamControllerCallPullIfNeeded(controller);
1371 }
1372 function ReadableByteStreamControllerShiftPendingPullInto(controller) {
1373 const descriptor = controller._pendingPullIntos.shift();
1374 return descriptor;
1375 }
1376 function ReadableByteStreamControllerShouldCallPull(controller) {
1377 const stream = controller._controlledReadableByteStream;
1378 if (stream._state !== 'readable') {
1379 return false;
1380 }
1381 if (controller._closeRequested) {
1382 return false;
1383 }
1384 if (!controller._started) {
1385 return false;
1386 }
1387 if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
1388 return true;
1389 }
1390 if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {
1391 return true;
1392 }
1393 const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);
1394 if (desiredSize > 0) {
1395 return true;
1396 }
1397 return false;
1398 }
1399 function ReadableByteStreamControllerClearAlgorithms(controller) {
1400 controller._pullAlgorithm = undefined;
1401 controller._cancelAlgorithm = undefined;
1402 }
1403 // A client of ReadableByteStreamController may use these functions directly to bypass state check.
1404 function ReadableByteStreamControllerClose(controller) {
1405 const stream = controller._controlledReadableByteStream;
1406 if (controller._closeRequested || stream._state !== 'readable') {
1407 return;
1408 }
1409 if (controller._queueTotalSize > 0) {
1410 controller._closeRequested = true;
1411 return;
1412 }
1413 if (controller._pendingPullIntos.length > 0) {
1414 const firstPendingPullInto = controller._pendingPullIntos.peek();
1415 if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {
1416 const e = new TypeError('Insufficient bytes to fill elements in the given buffer');
1417 ReadableByteStreamControllerError(controller, e);
1418 throw e;
1419 }
1420 }
1421 ReadableByteStreamControllerClearAlgorithms(controller);
1422 ReadableStreamClose(stream);
1423 }
1424 function ReadableByteStreamControllerEnqueue(controller, chunk) {
1425 const stream = controller._controlledReadableByteStream;
1426 if (controller._closeRequested || stream._state !== 'readable') {
1427 return;
1428 }
1429 const { buffer, byteOffset, byteLength } = chunk;
1430 if (IsDetachedBuffer(buffer)) {
1431 throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued');
1432 }
1433 const transferredBuffer = TransferArrayBuffer(buffer);
1434 if (controller._pendingPullIntos.length > 0) {
1435 const firstPendingPullInto = controller._pendingPullIntos.peek();
1436 if (IsDetachedBuffer(firstPendingPullInto.buffer)) {
1437 throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk');
1438 }
1439 ReadableByteStreamControllerInvalidateBYOBRequest(controller);
1440 firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);
1441 if (firstPendingPullInto.readerType === 'none') {
1442 ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);
1443 }
1444 }
1445 if (ReadableStreamHasDefaultReader(stream)) {
1446 ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);
1447 if (ReadableStreamGetNumReadRequests(stream) === 0) {
1448 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1449 }
1450 else {
1451 if (controller._pendingPullIntos.length > 0) {
1452 ReadableByteStreamControllerShiftPendingPullInto(controller);
1453 }
1454 const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);
1455 ReadableStreamFulfillReadRequest(stream, transferredView, false);
1456 }
1457 }
1458 else if (ReadableStreamHasBYOBReader(stream)) {
1459 // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.
1460 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1461 ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);
1462 }
1463 else {
1464 ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);
1465 }
1466 ReadableByteStreamControllerCallPullIfNeeded(controller);
1467 }
1468 function ReadableByteStreamControllerError(controller, e) {
1469 const stream = controller._controlledReadableByteStream;
1470 if (stream._state !== 'readable') {
1471 return;
1472 }
1473 ReadableByteStreamControllerClearPendingPullIntos(controller);
1474 ResetQueue(controller);
1475 ReadableByteStreamControllerClearAlgorithms(controller);
1476 ReadableStreamError(stream, e);
1477 }
1478 function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) {
1479 const entry = controller._queue.shift();
1480 controller._queueTotalSize -= entry.byteLength;
1481 ReadableByteStreamControllerHandleQueueDrain(controller);
1482 const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);
1483 readRequest._chunkSteps(view);
1484 }
1485 function ReadableByteStreamControllerGetBYOBRequest(controller) {
1486 if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {
1487 const firstDescriptor = controller._pendingPullIntos.peek();
1488 const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled);
1489 const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype);
1490 SetUpReadableStreamBYOBRequest(byobRequest, controller, view);
1491 controller._byobRequest = byobRequest;
1492 }
1493 return controller._byobRequest;
1494 }
1495 function ReadableByteStreamControllerGetDesiredSize(controller) {
1496 const state = controller._controlledReadableByteStream._state;
1497 if (state === 'errored') {
1498 return null;
1499 }
1500 if (state === 'closed') {
1501 return 0;
1502 }
1503 return controller._strategyHWM - controller._queueTotalSize;
1504 }
1505 function ReadableByteStreamControllerRespond(controller, bytesWritten) {
1506 const firstDescriptor = controller._pendingPullIntos.peek();
1507 const state = controller._controlledReadableByteStream._state;
1508 if (state === 'closed') {
1509 if (bytesWritten !== 0) {
1510 throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');
1511 }
1512 }
1513 else {
1514 if (bytesWritten === 0) {
1515 throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');
1516 }
1517 if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {
1518 throw new RangeError('bytesWritten out of range');
1519 }
1520 }
1521 firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);
1522 ReadableByteStreamControllerRespondInternal(controller, bytesWritten);
1523 }
1524 function ReadableByteStreamControllerRespondWithNewView(controller, view) {
1525 const firstDescriptor = controller._pendingPullIntos.peek();
1526 const state = controller._controlledReadableByteStream._state;
1527 if (state === 'closed') {
1528 if (view.byteLength !== 0) {
1529 throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream');
1530 }
1531 }
1532 else {
1533 if (view.byteLength === 0) {
1534 throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream');
1535 }
1536 }
1537 if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {
1538 throw new RangeError('The region specified by view does not match byobRequest');
1539 }
1540 if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {
1541 throw new RangeError('The buffer of view has different capacity than byobRequest');
1542 }
1543 if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {
1544 throw new RangeError('The region specified by view is larger than byobRequest');
1545 }
1546 const viewByteLength = view.byteLength;
1547 firstDescriptor.buffer = TransferArrayBuffer(view.buffer);
1548 ReadableByteStreamControllerRespondInternal(controller, viewByteLength);
1549 }
1550 function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) {
1551 controller._controlledReadableByteStream = stream;
1552 controller._pullAgain = false;
1553 controller._pulling = false;
1554 controller._byobRequest = null;
1555 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
1556 controller._queue = controller._queueTotalSize = undefined;
1557 ResetQueue(controller);
1558 controller._closeRequested = false;
1559 controller._started = false;
1560 controller._strategyHWM = highWaterMark;
1561 controller._pullAlgorithm = pullAlgorithm;
1562 controller._cancelAlgorithm = cancelAlgorithm;
1563 controller._autoAllocateChunkSize = autoAllocateChunkSize;
1564 controller._pendingPullIntos = new SimpleQueue();
1565 stream._readableStreamController = controller;
1566 const startResult = startAlgorithm();
1567 uponPromise(promiseResolvedWith(startResult), () => {
1568 controller._started = true;
1569 ReadableByteStreamControllerCallPullIfNeeded(controller);
1570 return null;
1571 }, r => {
1572 ReadableByteStreamControllerError(controller, r);
1573 return null;
1574 });
1575 }
1576 function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) {
1577 const controller = Object.create(ReadableByteStreamController.prototype);
1578 let startAlgorithm;
1579 let pullAlgorithm;
1580 let cancelAlgorithm;
1581 if (underlyingByteSource.start !== undefined) {
1582 startAlgorithm = () => underlyingByteSource.start(controller);
1583 }
1584 else {
1585 startAlgorithm = () => undefined;
1586 }
1587 if (underlyingByteSource.pull !== undefined) {
1588 pullAlgorithm = () => underlyingByteSource.pull(controller);
1589 }
1590 else {
1591 pullAlgorithm = () => promiseResolvedWith(undefined);
1592 }
1593 if (underlyingByteSource.cancel !== undefined) {
1594 cancelAlgorithm = reason => underlyingByteSource.cancel(reason);
1595 }
1596 else {
1597 cancelAlgorithm = () => promiseResolvedWith(undefined);
1598 }
1599 const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;
1600 if (autoAllocateChunkSize === 0) {
1601 throw new TypeError('autoAllocateChunkSize must be greater than 0');
1602 }
1603 SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize);
1604 }
1605 function SetUpReadableStreamBYOBRequest(request, controller, view) {
1606 request._associatedReadableByteStreamController = controller;
1607 request._view = view;
1608 }
1609 // Helper functions for the ReadableStreamBYOBRequest.
1610 function byobRequestBrandCheckException(name) {
1611 return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);
1612 }
1613 // Helper functions for the ReadableByteStreamController.
1614 function byteStreamControllerBrandCheckException(name) {
1615 return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);
1616 }
1617
1618 function convertReaderOptions(options, context) {
1619 assertDictionary(options, context);
1620 const mode = options === null || options === void 0 ? void 0 : options.mode;
1621 return {
1622 mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)
1623 };
1624 }
1625 function convertReadableStreamReaderMode(mode, context) {
1626 mode = `${mode}`;
1627 if (mode !== 'byob') {
1628 throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);
1629 }
1630 return mode;
1631 }
1632 function convertByobReadOptions(options, context) {
1633 var _a;
1634 assertDictionary(options, context);
1635 const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1;
1636 return {
1637 min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`)
1638 };
1639 }
1640
1641 // Abstract operations for the ReadableStream.
1642 function AcquireReadableStreamBYOBReader(stream) {
1643 return new ReadableStreamBYOBReader(stream);
1644 }
1645 // ReadableStream API exposed for controllers.
1646 function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) {
1647 stream._reader._readIntoRequests.push(readIntoRequest);
1648 }
1649 function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) {
1650 const reader = stream._reader;
1651 const readIntoRequest = reader._readIntoRequests.shift();
1652 if (done) {
1653 readIntoRequest._closeSteps(chunk);
1654 }
1655 else {
1656 readIntoRequest._chunkSteps(chunk);
1657 }
1658 }
1659 function ReadableStreamGetNumReadIntoRequests(stream) {
1660 return stream._reader._readIntoRequests.length;
1661 }
1662 function ReadableStreamHasBYOBReader(stream) {
1663 const reader = stream._reader;
1664 if (reader === undefined) {
1665 return false;
1666 }
1667 if (!IsReadableStreamBYOBReader(reader)) {
1668 return false;
1669 }
1670 return true;
1671 }
1672 /**
1673 * A BYOB reader vended by a {@link ReadableStream}.
1674 *
1675 * @public
1676 */
1677 class ReadableStreamBYOBReader {
1678 constructor(stream) {
1679 assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');
1680 assertReadableStream(stream, 'First parameter');
1681 if (IsReadableStreamLocked(stream)) {
1682 throw new TypeError('This stream has already been locked for exclusive reading by another reader');
1683 }
1684 if (!IsReadableByteStreamController(stream._readableStreamController)) {
1685 throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +
1686 'source');
1687 }
1688 ReadableStreamReaderGenericInitialize(this, stream);
1689 this._readIntoRequests = new SimpleQueue();
1690 }
1691 /**
1692 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
1693 * the reader's lock is released before the stream finishes closing.
1694 */
1695 get closed() {
1696 if (!IsReadableStreamBYOBReader(this)) {
1697 return promiseRejectedWith(byobReaderBrandCheckException('closed'));
1698 }
1699 return this._closedPromise;
1700 }
1701 /**
1702 * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
1703 */
1704 cancel(reason = undefined) {
1705 if (!IsReadableStreamBYOBReader(this)) {
1706 return promiseRejectedWith(byobReaderBrandCheckException('cancel'));
1707 }
1708 if (this._ownerReadableStream === undefined) {
1709 return promiseRejectedWith(readerLockException('cancel'));
1710 }
1711 return ReadableStreamReaderGenericCancel(this, reason);
1712 }
1713 read(view, rawOptions = {}) {
1714 if (!IsReadableStreamBYOBReader(this)) {
1715 return promiseRejectedWith(byobReaderBrandCheckException('read'));
1716 }
1717 if (!ArrayBuffer.isView(view)) {
1718 return promiseRejectedWith(new TypeError('view must be an array buffer view'));
1719 }
1720 if (view.byteLength === 0) {
1721 return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));
1722 }
1723 if (view.buffer.byteLength === 0) {
1724 return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));
1725 }
1726 if (IsDetachedBuffer(view.buffer)) {
1727 return promiseRejectedWith(new TypeError('view\'s buffer has been detached'));
1728 }
1729 let options;
1730 try {
1731 options = convertByobReadOptions(rawOptions, 'options');
1732 }
1733 catch (e) {
1734 return promiseRejectedWith(e);
1735 }
1736 const min = options.min;
1737 if (min === 0) {
1738 return promiseRejectedWith(new TypeError('options.min must be greater than 0'));
1739 }
1740 if (!isDataView(view)) {
1741 if (min > view.length) {
1742 return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length'));
1743 }
1744 }
1745 else if (min > view.byteLength) {
1746 return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength'));
1747 }
1748 if (this._ownerReadableStream === undefined) {
1749 return promiseRejectedWith(readerLockException('read from'));
1750 }
1751 let resolvePromise;
1752 let rejectPromise;
1753 const promise = newPromise((resolve, reject) => {
1754 resolvePromise = resolve;
1755 rejectPromise = reject;
1756 });
1757 const readIntoRequest = {
1758 _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),
1759 _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),
1760 _errorSteps: e => rejectPromise(e)
1761 };
1762 ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);
1763 return promise;
1764 }
1765 /**
1766 * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
1767 * If the associated stream is errored when the lock is released, the reader will appear errored in the same way
1768 * from now on; otherwise, the reader will appear closed.
1769 *
1770 * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
1771 * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
1772 * do so will throw a `TypeError` and leave the reader locked to the stream.
1773 */
1774 releaseLock() {
1775 if (!IsReadableStreamBYOBReader(this)) {
1776 throw byobReaderBrandCheckException('releaseLock');
1777 }
1778 if (this._ownerReadableStream === undefined) {
1779 return;
1780 }
1781 ReadableStreamBYOBReaderRelease(this);
1782 }
1783 }
1784 Object.defineProperties(ReadableStreamBYOBReader.prototype, {
1785 cancel: { enumerable: true },
1786 read: { enumerable: true },
1787 releaseLock: { enumerable: true },
1788 closed: { enumerable: true }
1789 });
1790 setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');
1791 setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');
1792 setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');
1793 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
1794 Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, {
1795 value: 'ReadableStreamBYOBReader',
1796 configurable: true
1797 });
1798 }
1799 // Abstract operations for the readers.
1800 function IsReadableStreamBYOBReader(x) {
1801 if (!typeIsObject(x)) {
1802 return false;
1803 }
1804 if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {
1805 return false;
1806 }
1807 return x instanceof ReadableStreamBYOBReader;
1808 }
1809 function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) {
1810 const stream = reader._ownerReadableStream;
1811 stream._disturbed = true;
1812 if (stream._state === 'errored') {
1813 readIntoRequest._errorSteps(stream._storedError);
1814 }
1815 else {
1816 ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest);
1817 }
1818 }
1819 function ReadableStreamBYOBReaderRelease(reader) {
1820 ReadableStreamReaderGenericRelease(reader);
1821 const e = new TypeError('Reader was released');
1822 ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
1823 }
1824 function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) {
1825 const readIntoRequests = reader._readIntoRequests;
1826 reader._readIntoRequests = new SimpleQueue();
1827 readIntoRequests.forEach(readIntoRequest => {
1828 readIntoRequest._errorSteps(e);
1829 });
1830 }
1831 // Helper functions for the ReadableStreamBYOBReader.
1832 function byobReaderBrandCheckException(name) {
1833 return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);
1834 }
1835
1836 function ExtractHighWaterMark(strategy, defaultHWM) {
1837 const { highWaterMark } = strategy;
1838 if (highWaterMark === undefined) {
1839 return defaultHWM;
1840 }
1841 if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {
1842 throw new RangeError('Invalid highWaterMark');
1843 }
1844 return highWaterMark;
1845 }
1846 function ExtractSizeAlgorithm(strategy) {
1847 const { size } = strategy;
1848 if (!size) {
1849 return () => 1;
1850 }
1851 return size;
1852 }
1853
1854 function convertQueuingStrategy(init, context) {
1855 assertDictionary(init, context);
1856 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
1857 const size = init === null || init === void 0 ? void 0 : init.size;
1858 return {
1859 highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),
1860 size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)
1861 };
1862 }
1863 function convertQueuingStrategySize(fn, context) {
1864 assertFunction(fn, context);
1865 return chunk => convertUnrestrictedDouble(fn(chunk));
1866 }
1867
1868 function convertUnderlyingSink(original, context) {
1869 assertDictionary(original, context);
1870 const abort = original === null || original === void 0 ? void 0 : original.abort;
1871 const close = original === null || original === void 0 ? void 0 : original.close;
1872 const start = original === null || original === void 0 ? void 0 : original.start;
1873 const type = original === null || original === void 0 ? void 0 : original.type;
1874 const write = original === null || original === void 0 ? void 0 : original.write;
1875 return {
1876 abort: abort === undefined ?
1877 undefined :
1878 convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`),
1879 close: close === undefined ?
1880 undefined :
1881 convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`),
1882 start: start === undefined ?
1883 undefined :
1884 convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`),
1885 write: write === undefined ?
1886 undefined :
1887 convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`),
1888 type
1889 };
1890 }
1891 function convertUnderlyingSinkAbortCallback(fn, original, context) {
1892 assertFunction(fn, context);
1893 return (reason) => promiseCall(fn, original, [reason]);
1894 }
1895 function convertUnderlyingSinkCloseCallback(fn, original, context) {
1896 assertFunction(fn, context);
1897 return () => promiseCall(fn, original, []);
1898 }
1899 function convertUnderlyingSinkStartCallback(fn, original, context) {
1900 assertFunction(fn, context);
1901 return (controller) => reflectCall(fn, original, [controller]);
1902 }
1903 function convertUnderlyingSinkWriteCallback(fn, original, context) {
1904 assertFunction(fn, context);
1905 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
1906 }
1907
1908 function assertWritableStream(x, context) {
1909 if (!IsWritableStream(x)) {
1910 throw new TypeError(`${context} is not a WritableStream.`);
1911 }
1912 }
1913
1914 function isAbortSignal(value) {
1915 if (typeof value !== 'object' || value === null) {
1916 return false;
1917 }
1918 try {
1919 return typeof value.aborted === 'boolean';
1920 }
1921 catch (_a) {
1922 // AbortSignal.prototype.aborted throws if its brand check fails
1923 return false;
1924 }
1925 }
1926 const supportsAbortController = typeof AbortController === 'function';
1927 /**
1928 * Construct a new AbortController, if supported by the platform.
1929 *
1930 * @internal
1931 */
1932 function createAbortController() {
1933 if (supportsAbortController) {
1934 return new AbortController();
1935 }
1936 return undefined;
1937 }
1938
1939 /**
1940 * A writable stream represents a destination for data, into which you can write.
1941 *
1942 * @public
1943 */
1944 class WritableStream {
1945 constructor(rawUnderlyingSink = {}, rawStrategy = {}) {
1946 if (rawUnderlyingSink === undefined) {
1947 rawUnderlyingSink = null;
1948 }
1949 else {
1950 assertObject(rawUnderlyingSink, 'First parameter');
1951 }
1952 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
1953 const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');
1954 InitializeWritableStream(this);
1955 const type = underlyingSink.type;
1956 if (type !== undefined) {
1957 throw new RangeError('Invalid type is specified');
1958 }
1959 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
1960 const highWaterMark = ExtractHighWaterMark(strategy, 1);
1961 SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);
1962 }
1963 /**
1964 * Returns whether or not the writable stream is locked to a writer.
1965 */
1966 get locked() {
1967 if (!IsWritableStream(this)) {
1968 throw streamBrandCheckException$2('locked');
1969 }
1970 return IsWritableStreamLocked(this);
1971 }
1972 /**
1973 * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
1974 * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
1975 * mechanism of the underlying sink.
1976 *
1977 * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
1978 * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
1979 * the stream) if the stream is currently locked.
1980 */
1981 abort(reason = undefined) {
1982 if (!IsWritableStream(this)) {
1983 return promiseRejectedWith(streamBrandCheckException$2('abort'));
1984 }
1985 if (IsWritableStreamLocked(this)) {
1986 return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));
1987 }
1988 return WritableStreamAbort(this, reason);
1989 }
1990 /**
1991 * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
1992 * close behavior. During this time any further attempts to write will fail (without erroring the stream).
1993 *
1994 * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
1995 * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
1996 * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
1997 */
1998 close() {
1999 if (!IsWritableStream(this)) {
2000 return promiseRejectedWith(streamBrandCheckException$2('close'));
2001 }
2002 if (IsWritableStreamLocked(this)) {
2003 return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));
2004 }
2005 if (WritableStreamCloseQueuedOrInFlight(this)) {
2006 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
2007 }
2008 return WritableStreamClose(this);
2009 }
2010 /**
2011 * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
2012 * is locked, no other writer can be acquired until this one is released.
2013 *
2014 * This functionality is especially useful for creating abstractions that desire the ability to write to a stream
2015 * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
2016 * the same time, which would cause the resulting written data to be unpredictable and probably useless.
2017 */
2018 getWriter() {
2019 if (!IsWritableStream(this)) {
2020 throw streamBrandCheckException$2('getWriter');
2021 }
2022 return AcquireWritableStreamDefaultWriter(this);
2023 }
2024 }
2025 Object.defineProperties(WritableStream.prototype, {
2026 abort: { enumerable: true },
2027 close: { enumerable: true },
2028 getWriter: { enumerable: true },
2029 locked: { enumerable: true }
2030 });
2031 setFunctionName(WritableStream.prototype.abort, 'abort');
2032 setFunctionName(WritableStream.prototype.close, 'close');
2033 setFunctionName(WritableStream.prototype.getWriter, 'getWriter');
2034 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2035 Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, {
2036 value: 'WritableStream',
2037 configurable: true
2038 });
2039 }
2040 // Abstract operations for the WritableStream.
2041 function AcquireWritableStreamDefaultWriter(stream) {
2042 return new WritableStreamDefaultWriter(stream);
2043 }
2044 // Throws if and only if startAlgorithm throws.
2045 function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
2046 const stream = Object.create(WritableStream.prototype);
2047 InitializeWritableStream(stream);
2048 const controller = Object.create(WritableStreamDefaultController.prototype);
2049 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
2050 return stream;
2051 }
2052 function InitializeWritableStream(stream) {
2053 stream._state = 'writable';
2054 // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is
2055 // 'erroring' or 'errored'. May be set to an undefined value.
2056 stream._storedError = undefined;
2057 stream._writer = undefined;
2058 // Initialize to undefined first because the constructor of the controller checks this
2059 // variable to validate the caller.
2060 stream._writableStreamController = undefined;
2061 // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data
2062 // producer without waiting for the queued writes to finish.
2063 stream._writeRequests = new SimpleQueue();
2064 // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents
2065 // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.
2066 stream._inFlightWriteRequest = undefined;
2067 // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer
2068 // has been detached.
2069 stream._closeRequest = undefined;
2070 // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it
2071 // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.
2072 stream._inFlightCloseRequest = undefined;
2073 // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.
2074 stream._pendingAbortRequest = undefined;
2075 // The backpressure signal set by the controller.
2076 stream._backpressure = false;
2077 }
2078 function IsWritableStream(x) {
2079 if (!typeIsObject(x)) {
2080 return false;
2081 }
2082 if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {
2083 return false;
2084 }
2085 return x instanceof WritableStream;
2086 }
2087 function IsWritableStreamLocked(stream) {
2088 if (stream._writer === undefined) {
2089 return false;
2090 }
2091 return true;
2092 }
2093 function WritableStreamAbort(stream, reason) {
2094 var _a;
2095 if (stream._state === 'closed' || stream._state === 'errored') {
2096 return promiseResolvedWith(undefined);
2097 }
2098 stream._writableStreamController._abortReason = reason;
2099 (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason);
2100 // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',
2101 // but it doesn't know that signaling abort runs author code that might have changed the state.
2102 // Widen the type again by casting to WritableStreamState.
2103 const state = stream._state;
2104 if (state === 'closed' || state === 'errored') {
2105 return promiseResolvedWith(undefined);
2106 }
2107 if (stream._pendingAbortRequest !== undefined) {
2108 return stream._pendingAbortRequest._promise;
2109 }
2110 let wasAlreadyErroring = false;
2111 if (state === 'erroring') {
2112 wasAlreadyErroring = true;
2113 // reason will not be used, so don't keep a reference to it.
2114 reason = undefined;
2115 }
2116 const promise = newPromise((resolve, reject) => {
2117 stream._pendingAbortRequest = {
2118 _promise: undefined,
2119 _resolve: resolve,
2120 _reject: reject,
2121 _reason: reason,
2122 _wasAlreadyErroring: wasAlreadyErroring
2123 };
2124 });
2125 stream._pendingAbortRequest._promise = promise;
2126 if (!wasAlreadyErroring) {
2127 WritableStreamStartErroring(stream, reason);
2128 }
2129 return promise;
2130 }
2131 function WritableStreamClose(stream) {
2132 const state = stream._state;
2133 if (state === 'closed' || state === 'errored') {
2134 return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`));
2135 }
2136 const promise = newPromise((resolve, reject) => {
2137 const closeRequest = {
2138 _resolve: resolve,
2139 _reject: reject
2140 };
2141 stream._closeRequest = closeRequest;
2142 });
2143 const writer = stream._writer;
2144 if (writer !== undefined && stream._backpressure && state === 'writable') {
2145 defaultWriterReadyPromiseResolve(writer);
2146 }
2147 WritableStreamDefaultControllerClose(stream._writableStreamController);
2148 return promise;
2149 }
2150 // WritableStream API exposed for controllers.
2151 function WritableStreamAddWriteRequest(stream) {
2152 const promise = newPromise((resolve, reject) => {
2153 const writeRequest = {
2154 _resolve: resolve,
2155 _reject: reject
2156 };
2157 stream._writeRequests.push(writeRequest);
2158 });
2159 return promise;
2160 }
2161 function WritableStreamDealWithRejection(stream, error) {
2162 const state = stream._state;
2163 if (state === 'writable') {
2164 WritableStreamStartErroring(stream, error);
2165 return;
2166 }
2167 WritableStreamFinishErroring(stream);
2168 }
2169 function WritableStreamStartErroring(stream, reason) {
2170 const controller = stream._writableStreamController;
2171 stream._state = 'erroring';
2172 stream._storedError = reason;
2173 const writer = stream._writer;
2174 if (writer !== undefined) {
2175 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);
2176 }
2177 if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {
2178 WritableStreamFinishErroring(stream);
2179 }
2180 }
2181 function WritableStreamFinishErroring(stream) {
2182 stream._state = 'errored';
2183 stream._writableStreamController[ErrorSteps]();
2184 const storedError = stream._storedError;
2185 stream._writeRequests.forEach(writeRequest => {
2186 writeRequest._reject(storedError);
2187 });
2188 stream._writeRequests = new SimpleQueue();
2189 if (stream._pendingAbortRequest === undefined) {
2190 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2191 return;
2192 }
2193 const abortRequest = stream._pendingAbortRequest;
2194 stream._pendingAbortRequest = undefined;
2195 if (abortRequest._wasAlreadyErroring) {
2196 abortRequest._reject(storedError);
2197 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2198 return;
2199 }
2200 const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);
2201 uponPromise(promise, () => {
2202 abortRequest._resolve();
2203 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2204 return null;
2205 }, (reason) => {
2206 abortRequest._reject(reason);
2207 WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);
2208 return null;
2209 });
2210 }
2211 function WritableStreamFinishInFlightWrite(stream) {
2212 stream._inFlightWriteRequest._resolve(undefined);
2213 stream._inFlightWriteRequest = undefined;
2214 }
2215 function WritableStreamFinishInFlightWriteWithError(stream, error) {
2216 stream._inFlightWriteRequest._reject(error);
2217 stream._inFlightWriteRequest = undefined;
2218 WritableStreamDealWithRejection(stream, error);
2219 }
2220 function WritableStreamFinishInFlightClose(stream) {
2221 stream._inFlightCloseRequest._resolve(undefined);
2222 stream._inFlightCloseRequest = undefined;
2223 const state = stream._state;
2224 if (state === 'erroring') {
2225 // The error was too late to do anything, so it is ignored.
2226 stream._storedError = undefined;
2227 if (stream._pendingAbortRequest !== undefined) {
2228 stream._pendingAbortRequest._resolve();
2229 stream._pendingAbortRequest = undefined;
2230 }
2231 }
2232 stream._state = 'closed';
2233 const writer = stream._writer;
2234 if (writer !== undefined) {
2235 defaultWriterClosedPromiseResolve(writer);
2236 }
2237 }
2238 function WritableStreamFinishInFlightCloseWithError(stream, error) {
2239 stream._inFlightCloseRequest._reject(error);
2240 stream._inFlightCloseRequest = undefined;
2241 // Never execute sink abort() after sink close().
2242 if (stream._pendingAbortRequest !== undefined) {
2243 stream._pendingAbortRequest._reject(error);
2244 stream._pendingAbortRequest = undefined;
2245 }
2246 WritableStreamDealWithRejection(stream, error);
2247 }
2248 // TODO(ricea): Fix alphabetical order.
2249 function WritableStreamCloseQueuedOrInFlight(stream) {
2250 if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {
2251 return false;
2252 }
2253 return true;
2254 }
2255 function WritableStreamHasOperationMarkedInFlight(stream) {
2256 if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {
2257 return false;
2258 }
2259 return true;
2260 }
2261 function WritableStreamMarkCloseRequestInFlight(stream) {
2262 stream._inFlightCloseRequest = stream._closeRequest;
2263 stream._closeRequest = undefined;
2264 }
2265 function WritableStreamMarkFirstWriteRequestInFlight(stream) {
2266 stream._inFlightWriteRequest = stream._writeRequests.shift();
2267 }
2268 function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) {
2269 if (stream._closeRequest !== undefined) {
2270 stream._closeRequest._reject(stream._storedError);
2271 stream._closeRequest = undefined;
2272 }
2273 const writer = stream._writer;
2274 if (writer !== undefined) {
2275 defaultWriterClosedPromiseReject(writer, stream._storedError);
2276 }
2277 }
2278 function WritableStreamUpdateBackpressure(stream, backpressure) {
2279 const writer = stream._writer;
2280 if (writer !== undefined && backpressure !== stream._backpressure) {
2281 if (backpressure) {
2282 defaultWriterReadyPromiseReset(writer);
2283 }
2284 else {
2285 defaultWriterReadyPromiseResolve(writer);
2286 }
2287 }
2288 stream._backpressure = backpressure;
2289 }
2290 /**
2291 * A default writer vended by a {@link WritableStream}.
2292 *
2293 * @public
2294 */
2295 class WritableStreamDefaultWriter {
2296 constructor(stream) {
2297 assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');
2298 assertWritableStream(stream, 'First parameter');
2299 if (IsWritableStreamLocked(stream)) {
2300 throw new TypeError('This stream has already been locked for exclusive writing by another writer');
2301 }
2302 this._ownerWritableStream = stream;
2303 stream._writer = this;
2304 const state = stream._state;
2305 if (state === 'writable') {
2306 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {
2307 defaultWriterReadyPromiseInitialize(this);
2308 }
2309 else {
2310 defaultWriterReadyPromiseInitializeAsResolved(this);
2311 }
2312 defaultWriterClosedPromiseInitialize(this);
2313 }
2314 else if (state === 'erroring') {
2315 defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);
2316 defaultWriterClosedPromiseInitialize(this);
2317 }
2318 else if (state === 'closed') {
2319 defaultWriterReadyPromiseInitializeAsResolved(this);
2320 defaultWriterClosedPromiseInitializeAsResolved(this);
2321 }
2322 else {
2323 const storedError = stream._storedError;
2324 defaultWriterReadyPromiseInitializeAsRejected(this, storedError);
2325 defaultWriterClosedPromiseInitializeAsRejected(this, storedError);
2326 }
2327 }
2328 /**
2329 * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
2330 * the writer’s lock is released before the stream finishes closing.
2331 */
2332 get closed() {
2333 if (!IsWritableStreamDefaultWriter(this)) {
2334 return promiseRejectedWith(defaultWriterBrandCheckException('closed'));
2335 }
2336 return this._closedPromise;
2337 }
2338 /**
2339 * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.
2340 * A producer can use this information to determine the right amount of data to write.
2341 *
2342 * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
2343 * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
2344 * the writer’s lock is released.
2345 */
2346 get desiredSize() {
2347 if (!IsWritableStreamDefaultWriter(this)) {
2348 throw defaultWriterBrandCheckException('desiredSize');
2349 }
2350 if (this._ownerWritableStream === undefined) {
2351 throw defaultWriterLockException('desiredSize');
2352 }
2353 return WritableStreamDefaultWriterGetDesiredSize(this);
2354 }
2355 /**
2356 * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions
2357 * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
2358 * back to zero or below, the getter will return a new promise that stays pending until the next transition.
2359 *
2360 * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become
2361 * rejected.
2362 */
2363 get ready() {
2364 if (!IsWritableStreamDefaultWriter(this)) {
2365 return promiseRejectedWith(defaultWriterBrandCheckException('ready'));
2366 }
2367 return this._readyPromise;
2368 }
2369 /**
2370 * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
2371 */
2372 abort(reason = undefined) {
2373 if (!IsWritableStreamDefaultWriter(this)) {
2374 return promiseRejectedWith(defaultWriterBrandCheckException('abort'));
2375 }
2376 if (this._ownerWritableStream === undefined) {
2377 return promiseRejectedWith(defaultWriterLockException('abort'));
2378 }
2379 return WritableStreamDefaultWriterAbort(this, reason);
2380 }
2381 /**
2382 * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
2383 */
2384 close() {
2385 if (!IsWritableStreamDefaultWriter(this)) {
2386 return promiseRejectedWith(defaultWriterBrandCheckException('close'));
2387 }
2388 const stream = this._ownerWritableStream;
2389 if (stream === undefined) {
2390 return promiseRejectedWith(defaultWriterLockException('close'));
2391 }
2392 if (WritableStreamCloseQueuedOrInFlight(stream)) {
2393 return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));
2394 }
2395 return WritableStreamDefaultWriterClose(this);
2396 }
2397 /**
2398 * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.
2399 * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
2400 * now on; otherwise, the writer will appear closed.
2401 *
2402 * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
2403 * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
2404 * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
2405 * other producers from writing in an interleaved manner.
2406 */
2407 releaseLock() {
2408 if (!IsWritableStreamDefaultWriter(this)) {
2409 throw defaultWriterBrandCheckException('releaseLock');
2410 }
2411 const stream = this._ownerWritableStream;
2412 if (stream === undefined) {
2413 return;
2414 }
2415 WritableStreamDefaultWriterRelease(this);
2416 }
2417 write(chunk = undefined) {
2418 if (!IsWritableStreamDefaultWriter(this)) {
2419 return promiseRejectedWith(defaultWriterBrandCheckException('write'));
2420 }
2421 if (this._ownerWritableStream === undefined) {
2422 return promiseRejectedWith(defaultWriterLockException('write to'));
2423 }
2424 return WritableStreamDefaultWriterWrite(this, chunk);
2425 }
2426 }
2427 Object.defineProperties(WritableStreamDefaultWriter.prototype, {
2428 abort: { enumerable: true },
2429 close: { enumerable: true },
2430 releaseLock: { enumerable: true },
2431 write: { enumerable: true },
2432 closed: { enumerable: true },
2433 desiredSize: { enumerable: true },
2434 ready: { enumerable: true }
2435 });
2436 setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');
2437 setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');
2438 setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');
2439 setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');
2440 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2441 Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, {
2442 value: 'WritableStreamDefaultWriter',
2443 configurable: true
2444 });
2445 }
2446 // Abstract operations for the WritableStreamDefaultWriter.
2447 function IsWritableStreamDefaultWriter(x) {
2448 if (!typeIsObject(x)) {
2449 return false;
2450 }
2451 if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {
2452 return false;
2453 }
2454 return x instanceof WritableStreamDefaultWriter;
2455 }
2456 // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.
2457 function WritableStreamDefaultWriterAbort(writer, reason) {
2458 const stream = writer._ownerWritableStream;
2459 return WritableStreamAbort(stream, reason);
2460 }
2461 function WritableStreamDefaultWriterClose(writer) {
2462 const stream = writer._ownerWritableStream;
2463 return WritableStreamClose(stream);
2464 }
2465 function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) {
2466 const stream = writer._ownerWritableStream;
2467 const state = stream._state;
2468 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
2469 return promiseResolvedWith(undefined);
2470 }
2471 if (state === 'errored') {
2472 return promiseRejectedWith(stream._storedError);
2473 }
2474 return WritableStreamDefaultWriterClose(writer);
2475 }
2476 function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) {
2477 if (writer._closedPromiseState === 'pending') {
2478 defaultWriterClosedPromiseReject(writer, error);
2479 }
2480 else {
2481 defaultWriterClosedPromiseResetToRejected(writer, error);
2482 }
2483 }
2484 function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) {
2485 if (writer._readyPromiseState === 'pending') {
2486 defaultWriterReadyPromiseReject(writer, error);
2487 }
2488 else {
2489 defaultWriterReadyPromiseResetToRejected(writer, error);
2490 }
2491 }
2492 function WritableStreamDefaultWriterGetDesiredSize(writer) {
2493 const stream = writer._ownerWritableStream;
2494 const state = stream._state;
2495 if (state === 'errored' || state === 'erroring') {
2496 return null;
2497 }
2498 if (state === 'closed') {
2499 return 0;
2500 }
2501 return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);
2502 }
2503 function WritableStreamDefaultWriterRelease(writer) {
2504 const stream = writer._ownerWritableStream;
2505 const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`);
2506 WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);
2507 // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not
2508 // rejected until afterwards. This means that simply testing state will not work.
2509 WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);
2510 stream._writer = undefined;
2511 writer._ownerWritableStream = undefined;
2512 }
2513 function WritableStreamDefaultWriterWrite(writer, chunk) {
2514 const stream = writer._ownerWritableStream;
2515 const controller = stream._writableStreamController;
2516 const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);
2517 if (stream !== writer._ownerWritableStream) {
2518 return promiseRejectedWith(defaultWriterLockException('write to'));
2519 }
2520 const state = stream._state;
2521 if (state === 'errored') {
2522 return promiseRejectedWith(stream._storedError);
2523 }
2524 if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {
2525 return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));
2526 }
2527 if (state === 'erroring') {
2528 return promiseRejectedWith(stream._storedError);
2529 }
2530 const promise = WritableStreamAddWriteRequest(stream);
2531 WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);
2532 return promise;
2533 }
2534 const closeSentinel = {};
2535 /**
2536 * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
2537 *
2538 * @public
2539 */
2540 class WritableStreamDefaultController {
2541 constructor() {
2542 throw new TypeError('Illegal constructor');
2543 }
2544 /**
2545 * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
2546 *
2547 * @deprecated
2548 * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
2549 * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
2550 */
2551 get abortReason() {
2552 if (!IsWritableStreamDefaultController(this)) {
2553 throw defaultControllerBrandCheckException$2('abortReason');
2554 }
2555 return this._abortReason;
2556 }
2557 /**
2558 * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
2559 */
2560 get signal() {
2561 if (!IsWritableStreamDefaultController(this)) {
2562 throw defaultControllerBrandCheckException$2('signal');
2563 }
2564 if (this._abortController === undefined) {
2565 // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.
2566 // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,
2567 // so instead we only implement support for `signal` if we find a global `AbortController` constructor.
2568 throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');
2569 }
2570 return this._abortController.signal;
2571 }
2572 /**
2573 * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
2574 *
2575 * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
2576 * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
2577 * normal lifecycle of interactions with the underlying sink.
2578 */
2579 error(e = undefined) {
2580 if (!IsWritableStreamDefaultController(this)) {
2581 throw defaultControllerBrandCheckException$2('error');
2582 }
2583 const state = this._controlledWritableStream._state;
2584 if (state !== 'writable') {
2585 // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so
2586 // just treat it as a no-op.
2587 return;
2588 }
2589 WritableStreamDefaultControllerError(this, e);
2590 }
2591 /** @internal */
2592 [AbortSteps](reason) {
2593 const result = this._abortAlgorithm(reason);
2594 WritableStreamDefaultControllerClearAlgorithms(this);
2595 return result;
2596 }
2597 /** @internal */
2598 [ErrorSteps]() {
2599 ResetQueue(this);
2600 }
2601 }
2602 Object.defineProperties(WritableStreamDefaultController.prototype, {
2603 abortReason: { enumerable: true },
2604 signal: { enumerable: true },
2605 error: { enumerable: true }
2606 });
2607 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
2608 Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
2609 value: 'WritableStreamDefaultController',
2610 configurable: true
2611 });
2612 }
2613 // Abstract operations implementing interface required by the WritableStream.
2614 function IsWritableStreamDefaultController(x) {
2615 if (!typeIsObject(x)) {
2616 return false;
2617 }
2618 if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {
2619 return false;
2620 }
2621 return x instanceof WritableStreamDefaultController;
2622 }
2623 function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) {
2624 controller._controlledWritableStream = stream;
2625 stream._writableStreamController = controller;
2626 // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.
2627 controller._queue = undefined;
2628 controller._queueTotalSize = undefined;
2629 ResetQueue(controller);
2630 controller._abortReason = undefined;
2631 controller._abortController = createAbortController();
2632 controller._started = false;
2633 controller._strategySizeAlgorithm = sizeAlgorithm;
2634 controller._strategyHWM = highWaterMark;
2635 controller._writeAlgorithm = writeAlgorithm;
2636 controller._closeAlgorithm = closeAlgorithm;
2637 controller._abortAlgorithm = abortAlgorithm;
2638 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
2639 WritableStreamUpdateBackpressure(stream, backpressure);
2640 const startResult = startAlgorithm();
2641 const startPromise = promiseResolvedWith(startResult);
2642 uponPromise(startPromise, () => {
2643 controller._started = true;
2644 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2645 return null;
2646 }, r => {
2647 controller._started = true;
2648 WritableStreamDealWithRejection(stream, r);
2649 return null;
2650 });
2651 }
2652 function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) {
2653 const controller = Object.create(WritableStreamDefaultController.prototype);
2654 let startAlgorithm;
2655 let writeAlgorithm;
2656 let closeAlgorithm;
2657 let abortAlgorithm;
2658 if (underlyingSink.start !== undefined) {
2659 startAlgorithm = () => underlyingSink.start(controller);
2660 }
2661 else {
2662 startAlgorithm = () => undefined;
2663 }
2664 if (underlyingSink.write !== undefined) {
2665 writeAlgorithm = chunk => underlyingSink.write(chunk, controller);
2666 }
2667 else {
2668 writeAlgorithm = () => promiseResolvedWith(undefined);
2669 }
2670 if (underlyingSink.close !== undefined) {
2671 closeAlgorithm = () => underlyingSink.close();
2672 }
2673 else {
2674 closeAlgorithm = () => promiseResolvedWith(undefined);
2675 }
2676 if (underlyingSink.abort !== undefined) {
2677 abortAlgorithm = reason => underlyingSink.abort(reason);
2678 }
2679 else {
2680 abortAlgorithm = () => promiseResolvedWith(undefined);
2681 }
2682 SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm);
2683 }
2684 // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.
2685 function WritableStreamDefaultControllerClearAlgorithms(controller) {
2686 controller._writeAlgorithm = undefined;
2687 controller._closeAlgorithm = undefined;
2688 controller._abortAlgorithm = undefined;
2689 controller._strategySizeAlgorithm = undefined;
2690 }
2691 function WritableStreamDefaultControllerClose(controller) {
2692 EnqueueValueWithSize(controller, closeSentinel, 0);
2693 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2694 }
2695 function WritableStreamDefaultControllerGetChunkSize(controller, chunk) {
2696 try {
2697 return controller._strategySizeAlgorithm(chunk);
2698 }
2699 catch (chunkSizeE) {
2700 WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);
2701 return 1;
2702 }
2703 }
2704 function WritableStreamDefaultControllerGetDesiredSize(controller) {
2705 return controller._strategyHWM - controller._queueTotalSize;
2706 }
2707 function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) {
2708 try {
2709 EnqueueValueWithSize(controller, chunk, chunkSize);
2710 }
2711 catch (enqueueE) {
2712 WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);
2713 return;
2714 }
2715 const stream = controller._controlledWritableStream;
2716 if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {
2717 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
2718 WritableStreamUpdateBackpressure(stream, backpressure);
2719 }
2720 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2721 }
2722 // Abstract operations for the WritableStreamDefaultController.
2723 function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) {
2724 const stream = controller._controlledWritableStream;
2725 if (!controller._started) {
2726 return;
2727 }
2728 if (stream._inFlightWriteRequest !== undefined) {
2729 return;
2730 }
2731 const state = stream._state;
2732 if (state === 'erroring') {
2733 WritableStreamFinishErroring(stream);
2734 return;
2735 }
2736 if (controller._queue.length === 0) {
2737 return;
2738 }
2739 const value = PeekQueueValue(controller);
2740 if (value === closeSentinel) {
2741 WritableStreamDefaultControllerProcessClose(controller);
2742 }
2743 else {
2744 WritableStreamDefaultControllerProcessWrite(controller, value);
2745 }
2746 }
2747 function WritableStreamDefaultControllerErrorIfNeeded(controller, error) {
2748 if (controller._controlledWritableStream._state === 'writable') {
2749 WritableStreamDefaultControllerError(controller, error);
2750 }
2751 }
2752 function WritableStreamDefaultControllerProcessClose(controller) {
2753 const stream = controller._controlledWritableStream;
2754 WritableStreamMarkCloseRequestInFlight(stream);
2755 DequeueValue(controller);
2756 const sinkClosePromise = controller._closeAlgorithm();
2757 WritableStreamDefaultControllerClearAlgorithms(controller);
2758 uponPromise(sinkClosePromise, () => {
2759 WritableStreamFinishInFlightClose(stream);
2760 return null;
2761 }, reason => {
2762 WritableStreamFinishInFlightCloseWithError(stream, reason);
2763 return null;
2764 });
2765 }
2766 function WritableStreamDefaultControllerProcessWrite(controller, chunk) {
2767 const stream = controller._controlledWritableStream;
2768 WritableStreamMarkFirstWriteRequestInFlight(stream);
2769 const sinkWritePromise = controller._writeAlgorithm(chunk);
2770 uponPromise(sinkWritePromise, () => {
2771 WritableStreamFinishInFlightWrite(stream);
2772 const state = stream._state;
2773 DequeueValue(controller);
2774 if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {
2775 const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);
2776 WritableStreamUpdateBackpressure(stream, backpressure);
2777 }
2778 WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);
2779 return null;
2780 }, reason => {
2781 if (stream._state === 'writable') {
2782 WritableStreamDefaultControllerClearAlgorithms(controller);
2783 }
2784 WritableStreamFinishInFlightWriteWithError(stream, reason);
2785 return null;
2786 });
2787 }
2788 function WritableStreamDefaultControllerGetBackpressure(controller) {
2789 const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);
2790 return desiredSize <= 0;
2791 }
2792 // A client of WritableStreamDefaultController may use these functions directly to bypass state check.
2793 function WritableStreamDefaultControllerError(controller, error) {
2794 const stream = controller._controlledWritableStream;
2795 WritableStreamDefaultControllerClearAlgorithms(controller);
2796 WritableStreamStartErroring(stream, error);
2797 }
2798 // Helper functions for the WritableStream.
2799 function streamBrandCheckException$2(name) {
2800 return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);
2801 }
2802 // Helper functions for the WritableStreamDefaultController.
2803 function defaultControllerBrandCheckException$2(name) {
2804 return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);
2805 }
2806 // Helper functions for the WritableStreamDefaultWriter.
2807 function defaultWriterBrandCheckException(name) {
2808 return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);
2809 }
2810 function defaultWriterLockException(name) {
2811 return new TypeError('Cannot ' + name + ' a stream using a released writer');
2812 }
2813 function defaultWriterClosedPromiseInitialize(writer) {
2814 writer._closedPromise = newPromise((resolve, reject) => {
2815 writer._closedPromise_resolve = resolve;
2816 writer._closedPromise_reject = reject;
2817 writer._closedPromiseState = 'pending';
2818 });
2819 }
2820 function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) {
2821 defaultWriterClosedPromiseInitialize(writer);
2822 defaultWriterClosedPromiseReject(writer, reason);
2823 }
2824 function defaultWriterClosedPromiseInitializeAsResolved(writer) {
2825 defaultWriterClosedPromiseInitialize(writer);
2826 defaultWriterClosedPromiseResolve(writer);
2827 }
2828 function defaultWriterClosedPromiseReject(writer, reason) {
2829 if (writer._closedPromise_reject === undefined) {
2830 return;
2831 }
2832 setPromiseIsHandledToTrue(writer._closedPromise);
2833 writer._closedPromise_reject(reason);
2834 writer._closedPromise_resolve = undefined;
2835 writer._closedPromise_reject = undefined;
2836 writer._closedPromiseState = 'rejected';
2837 }
2838 function defaultWriterClosedPromiseResetToRejected(writer, reason) {
2839 defaultWriterClosedPromiseInitializeAsRejected(writer, reason);
2840 }
2841 function defaultWriterClosedPromiseResolve(writer) {
2842 if (writer._closedPromise_resolve === undefined) {
2843 return;
2844 }
2845 writer._closedPromise_resolve(undefined);
2846 writer._closedPromise_resolve = undefined;
2847 writer._closedPromise_reject = undefined;
2848 writer._closedPromiseState = 'resolved';
2849 }
2850 function defaultWriterReadyPromiseInitialize(writer) {
2851 writer._readyPromise = newPromise((resolve, reject) => {
2852 writer._readyPromise_resolve = resolve;
2853 writer._readyPromise_reject = reject;
2854 });
2855 writer._readyPromiseState = 'pending';
2856 }
2857 function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) {
2858 defaultWriterReadyPromiseInitialize(writer);
2859 defaultWriterReadyPromiseReject(writer, reason);
2860 }
2861 function defaultWriterReadyPromiseInitializeAsResolved(writer) {
2862 defaultWriterReadyPromiseInitialize(writer);
2863 defaultWriterReadyPromiseResolve(writer);
2864 }
2865 function defaultWriterReadyPromiseReject(writer, reason) {
2866 if (writer._readyPromise_reject === undefined) {
2867 return;
2868 }
2869 setPromiseIsHandledToTrue(writer._readyPromise);
2870 writer._readyPromise_reject(reason);
2871 writer._readyPromise_resolve = undefined;
2872 writer._readyPromise_reject = undefined;
2873 writer._readyPromiseState = 'rejected';
2874 }
2875 function defaultWriterReadyPromiseReset(writer) {
2876 defaultWriterReadyPromiseInitialize(writer);
2877 }
2878 function defaultWriterReadyPromiseResetToRejected(writer, reason) {
2879 defaultWriterReadyPromiseInitializeAsRejected(writer, reason);
2880 }
2881 function defaultWriterReadyPromiseResolve(writer) {
2882 if (writer._readyPromise_resolve === undefined) {
2883 return;
2884 }
2885 writer._readyPromise_resolve(undefined);
2886 writer._readyPromise_resolve = undefined;
2887 writer._readyPromise_reject = undefined;
2888 writer._readyPromiseState = 'fulfilled';
2889 }
2890
2891 /// <reference lib="dom" />
2892 function getGlobals() {
2893 if (typeof globalThis !== 'undefined') {
2894 return globalThis;
2895 }
2896 else if (typeof self !== 'undefined') {
2897 return self;
2898 }
2899 else if (typeof global !== 'undefined') {
2900 return global;
2901 }
2902 return undefined;
2903 }
2904 const globals = getGlobals();
2905
2906 /// <reference types="node" />
2907 function isDOMExceptionConstructor(ctor) {
2908 if (!(typeof ctor === 'function' || typeof ctor === 'object')) {
2909 return false;
2910 }
2911 if (ctor.name !== 'DOMException') {
2912 return false;
2913 }
2914 try {
2915 new ctor();
2916 return true;
2917 }
2918 catch (_a) {
2919 return false;
2920 }
2921 }
2922 /**
2923 * Support:
2924 * - Web browsers
2925 * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)
2926 */
2927 function getFromGlobal() {
2928 const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException;
2929 return isDOMExceptionConstructor(ctor) ? ctor : undefined;
2930 }
2931 /**
2932 * Support:
2933 * - All platforms
2934 */
2935 function createPolyfill() {
2936 // eslint-disable-next-line @typescript-eslint/no-shadow
2937 const ctor = function DOMException(message, name) {
2938 this.message = message || '';
2939 this.name = name || 'Error';
2940 if (Error.captureStackTrace) {
2941 Error.captureStackTrace(this, this.constructor);
2942 }
2943 };
2944 setFunctionName(ctor, 'DOMException');
2945 ctor.prototype = Object.create(Error.prototype);
2946 Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });
2947 return ctor;
2948 }
2949 // eslint-disable-next-line @typescript-eslint/no-redeclare
2950 const DOMException = getFromGlobal() || createPolyfill();
2951
2952 function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) {
2953 const reader = AcquireReadableStreamDefaultReader(source);
2954 const writer = AcquireWritableStreamDefaultWriter(dest);
2955 source._disturbed = true;
2956 let shuttingDown = false;
2957 // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.
2958 let currentWrite = promiseResolvedWith(undefined);
2959 return newPromise((resolve, reject) => {
2960 let abortAlgorithm;
2961 if (signal !== undefined) {
2962 abortAlgorithm = () => {
2963 const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');
2964 const actions = [];
2965 if (!preventAbort) {
2966 actions.push(() => {
2967 if (dest._state === 'writable') {
2968 return WritableStreamAbort(dest, error);
2969 }
2970 return promiseResolvedWith(undefined);
2971 });
2972 }
2973 if (!preventCancel) {
2974 actions.push(() => {
2975 if (source._state === 'readable') {
2976 return ReadableStreamCancel(source, error);
2977 }
2978 return promiseResolvedWith(undefined);
2979 });
2980 }
2981 shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);
2982 };
2983 if (signal.aborted) {
2984 abortAlgorithm();
2985 return;
2986 }
2987 signal.addEventListener('abort', abortAlgorithm);
2988 }
2989 // Using reader and writer, read all chunks from this and write them to dest
2990 // - Backpressure must be enforced
2991 // - Shutdown must stop all activity
2992 function pipeLoop() {
2993 return newPromise((resolveLoop, rejectLoop) => {
2994 function next(done) {
2995 if (done) {
2996 resolveLoop();
2997 }
2998 else {
2999 // Use `PerformPromiseThen` instead of `uponPromise` to avoid
3000 // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers
3001 PerformPromiseThen(pipeStep(), next, rejectLoop);
3002 }
3003 }
3004 next(false);
3005 });
3006 }
3007 function pipeStep() {
3008 if (shuttingDown) {
3009 return promiseResolvedWith(true);
3010 }
3011 return PerformPromiseThen(writer._readyPromise, () => {
3012 return newPromise((resolveRead, rejectRead) => {
3013 ReadableStreamDefaultReaderRead(reader, {
3014 _chunkSteps: chunk => {
3015 currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);
3016 resolveRead(false);
3017 },
3018 _closeSteps: () => resolveRead(true),
3019 _errorSteps: rejectRead
3020 });
3021 });
3022 });
3023 }
3024 // Errors must be propagated forward
3025 isOrBecomesErrored(source, reader._closedPromise, storedError => {
3026 if (!preventAbort) {
3027 shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);
3028 }
3029 else {
3030 shutdown(true, storedError);
3031 }
3032 return null;
3033 });
3034 // Errors must be propagated backward
3035 isOrBecomesErrored(dest, writer._closedPromise, storedError => {
3036 if (!preventCancel) {
3037 shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);
3038 }
3039 else {
3040 shutdown(true, storedError);
3041 }
3042 return null;
3043 });
3044 // Closing must be propagated forward
3045 isOrBecomesClosed(source, reader._closedPromise, () => {
3046 if (!preventClose) {
3047 shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));
3048 }
3049 else {
3050 shutdown();
3051 }
3052 return null;
3053 });
3054 // Closing must be propagated backward
3055 if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {
3056 const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');
3057 if (!preventCancel) {
3058 shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);
3059 }
3060 else {
3061 shutdown(true, destClosed);
3062 }
3063 }
3064 setPromiseIsHandledToTrue(pipeLoop());
3065 function waitForWritesToFinish() {
3066 // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait
3067 // for that too.
3068 const oldCurrentWrite = currentWrite;
3069 return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined);
3070 }
3071 function isOrBecomesErrored(stream, promise, action) {
3072 if (stream._state === 'errored') {
3073 action(stream._storedError);
3074 }
3075 else {
3076 uponRejection(promise, action);
3077 }
3078 }
3079 function isOrBecomesClosed(stream, promise, action) {
3080 if (stream._state === 'closed') {
3081 action();
3082 }
3083 else {
3084 uponFulfillment(promise, action);
3085 }
3086 }
3087 function shutdownWithAction(action, originalIsError, originalError) {
3088 if (shuttingDown) {
3089 return;
3090 }
3091 shuttingDown = true;
3092 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
3093 uponFulfillment(waitForWritesToFinish(), doTheRest);
3094 }
3095 else {
3096 doTheRest();
3097 }
3098 function doTheRest() {
3099 uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError));
3100 return null;
3101 }
3102 }
3103 function shutdown(isError, error) {
3104 if (shuttingDown) {
3105 return;
3106 }
3107 shuttingDown = true;
3108 if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {
3109 uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));
3110 }
3111 else {
3112 finalize(isError, error);
3113 }
3114 }
3115 function finalize(isError, error) {
3116 WritableStreamDefaultWriterRelease(writer);
3117 ReadableStreamReaderGenericRelease(reader);
3118 if (signal !== undefined) {
3119 signal.removeEventListener('abort', abortAlgorithm);
3120 }
3121 if (isError) {
3122 reject(error);
3123 }
3124 else {
3125 resolve(undefined);
3126 }
3127 return null;
3128 }
3129 });
3130 }
3131
3132 /**
3133 * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
3134 *
3135 * @public
3136 */
3137 class ReadableStreamDefaultController {
3138 constructor() {
3139 throw new TypeError('Illegal constructor');
3140 }
3141 /**
3142 * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
3143 * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
3144 */
3145 get desiredSize() {
3146 if (!IsReadableStreamDefaultController(this)) {
3147 throw defaultControllerBrandCheckException$1('desiredSize');
3148 }
3149 return ReadableStreamDefaultControllerGetDesiredSize(this);
3150 }
3151 /**
3152 * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
3153 * the stream, but once those are read, the stream will become closed.
3154 */
3155 close() {
3156 if (!IsReadableStreamDefaultController(this)) {
3157 throw defaultControllerBrandCheckException$1('close');
3158 }
3159 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
3160 throw new TypeError('The stream is not in a state that permits close');
3161 }
3162 ReadableStreamDefaultControllerClose(this);
3163 }
3164 enqueue(chunk = undefined) {
3165 if (!IsReadableStreamDefaultController(this)) {
3166 throw defaultControllerBrandCheckException$1('enqueue');
3167 }
3168 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {
3169 throw new TypeError('The stream is not in a state that permits enqueue');
3170 }
3171 return ReadableStreamDefaultControllerEnqueue(this, chunk);
3172 }
3173 /**
3174 * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
3175 */
3176 error(e = undefined) {
3177 if (!IsReadableStreamDefaultController(this)) {
3178 throw defaultControllerBrandCheckException$1('error');
3179 }
3180 ReadableStreamDefaultControllerError(this, e);
3181 }
3182 /** @internal */
3183 [CancelSteps](reason) {
3184 ResetQueue(this);
3185 const result = this._cancelAlgorithm(reason);
3186 ReadableStreamDefaultControllerClearAlgorithms(this);
3187 return result;
3188 }
3189 /** @internal */
3190 [PullSteps](readRequest) {
3191 const stream = this._controlledReadableStream;
3192 if (this._queue.length > 0) {
3193 const chunk = DequeueValue(this);
3194 if (this._closeRequested && this._queue.length === 0) {
3195 ReadableStreamDefaultControllerClearAlgorithms(this);
3196 ReadableStreamClose(stream);
3197 }
3198 else {
3199 ReadableStreamDefaultControllerCallPullIfNeeded(this);
3200 }
3201 readRequest._chunkSteps(chunk);
3202 }
3203 else {
3204 ReadableStreamAddReadRequest(stream, readRequest);
3205 ReadableStreamDefaultControllerCallPullIfNeeded(this);
3206 }
3207 }
3208 /** @internal */
3209 [ReleaseSteps]() {
3210 // Do nothing.
3211 }
3212 }
3213 Object.defineProperties(ReadableStreamDefaultController.prototype, {
3214 close: { enumerable: true },
3215 enqueue: { enumerable: true },
3216 error: { enumerable: true },
3217 desiredSize: { enumerable: true }
3218 });
3219 setFunctionName(ReadableStreamDefaultController.prototype.close, 'close');
3220 setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');
3221 setFunctionName(ReadableStreamDefaultController.prototype.error, 'error');
3222 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
3223 Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
3224 value: 'ReadableStreamDefaultController',
3225 configurable: true
3226 });
3227 }
3228 // Abstract operations for the ReadableStreamDefaultController.
3229 function IsReadableStreamDefaultController(x) {
3230 if (!typeIsObject(x)) {
3231 return false;
3232 }
3233 if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {
3234 return false;
3235 }
3236 return x instanceof ReadableStreamDefaultController;
3237 }
3238 function ReadableStreamDefaultControllerCallPullIfNeeded(controller) {
3239 const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);
3240 if (!shouldPull) {
3241 return;
3242 }
3243 if (controller._pulling) {
3244 controller._pullAgain = true;
3245 return;
3246 }
3247 controller._pulling = true;
3248 const pullPromise = controller._pullAlgorithm();
3249 uponPromise(pullPromise, () => {
3250 controller._pulling = false;
3251 if (controller._pullAgain) {
3252 controller._pullAgain = false;
3253 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
3254 }
3255 return null;
3256 }, e => {
3257 ReadableStreamDefaultControllerError(controller, e);
3258 return null;
3259 });
3260 }
3261 function ReadableStreamDefaultControllerShouldCallPull(controller) {
3262 const stream = controller._controlledReadableStream;
3263 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
3264 return false;
3265 }
3266 if (!controller._started) {
3267 return false;
3268 }
3269 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
3270 return true;
3271 }
3272 const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);
3273 if (desiredSize > 0) {
3274 return true;
3275 }
3276 return false;
3277 }
3278 function ReadableStreamDefaultControllerClearAlgorithms(controller) {
3279 controller._pullAlgorithm = undefined;
3280 controller._cancelAlgorithm = undefined;
3281 controller._strategySizeAlgorithm = undefined;
3282 }
3283 // A client of ReadableStreamDefaultController may use these functions directly to bypass state check.
3284 function ReadableStreamDefaultControllerClose(controller) {
3285 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
3286 return;
3287 }
3288 const stream = controller._controlledReadableStream;
3289 controller._closeRequested = true;
3290 if (controller._queue.length === 0) {
3291 ReadableStreamDefaultControllerClearAlgorithms(controller);
3292 ReadableStreamClose(stream);
3293 }
3294 }
3295 function ReadableStreamDefaultControllerEnqueue(controller, chunk) {
3296 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {
3297 return;
3298 }
3299 const stream = controller._controlledReadableStream;
3300 if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {
3301 ReadableStreamFulfillReadRequest(stream, chunk, false);
3302 }
3303 else {
3304 let chunkSize;
3305 try {
3306 chunkSize = controller._strategySizeAlgorithm(chunk);
3307 }
3308 catch (chunkSizeE) {
3309 ReadableStreamDefaultControllerError(controller, chunkSizeE);
3310 throw chunkSizeE;
3311 }
3312 try {
3313 EnqueueValueWithSize(controller, chunk, chunkSize);
3314 }
3315 catch (enqueueE) {
3316 ReadableStreamDefaultControllerError(controller, enqueueE);
3317 throw enqueueE;
3318 }
3319 }
3320 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
3321 }
3322 function ReadableStreamDefaultControllerError(controller, e) {
3323 const stream = controller._controlledReadableStream;
3324 if (stream._state !== 'readable') {
3325 return;
3326 }
3327 ResetQueue(controller);
3328 ReadableStreamDefaultControllerClearAlgorithms(controller);
3329 ReadableStreamError(stream, e);
3330 }
3331 function ReadableStreamDefaultControllerGetDesiredSize(controller) {
3332 const state = controller._controlledReadableStream._state;
3333 if (state === 'errored') {
3334 return null;
3335 }
3336 if (state === 'closed') {
3337 return 0;
3338 }
3339 return controller._strategyHWM - controller._queueTotalSize;
3340 }
3341 // This is used in the implementation of TransformStream.
3342 function ReadableStreamDefaultControllerHasBackpressure(controller) {
3343 if (ReadableStreamDefaultControllerShouldCallPull(controller)) {
3344 return false;
3345 }
3346 return true;
3347 }
3348 function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) {
3349 const state = controller._controlledReadableStream._state;
3350 if (!controller._closeRequested && state === 'readable') {
3351 return true;
3352 }
3353 return false;
3354 }
3355 function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) {
3356 controller._controlledReadableStream = stream;
3357 controller._queue = undefined;
3358 controller._queueTotalSize = undefined;
3359 ResetQueue(controller);
3360 controller._started = false;
3361 controller._closeRequested = false;
3362 controller._pullAgain = false;
3363 controller._pulling = false;
3364 controller._strategySizeAlgorithm = sizeAlgorithm;
3365 controller._strategyHWM = highWaterMark;
3366 controller._pullAlgorithm = pullAlgorithm;
3367 controller._cancelAlgorithm = cancelAlgorithm;
3368 stream._readableStreamController = controller;
3369 const startResult = startAlgorithm();
3370 uponPromise(promiseResolvedWith(startResult), () => {
3371 controller._started = true;
3372 ReadableStreamDefaultControllerCallPullIfNeeded(controller);
3373 return null;
3374 }, r => {
3375 ReadableStreamDefaultControllerError(controller, r);
3376 return null;
3377 });
3378 }
3379 function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) {
3380 const controller = Object.create(ReadableStreamDefaultController.prototype);
3381 let startAlgorithm;
3382 let pullAlgorithm;
3383 let cancelAlgorithm;
3384 if (underlyingSource.start !== undefined) {
3385 startAlgorithm = () => underlyingSource.start(controller);
3386 }
3387 else {
3388 startAlgorithm = () => undefined;
3389 }
3390 if (underlyingSource.pull !== undefined) {
3391 pullAlgorithm = () => underlyingSource.pull(controller);
3392 }
3393 else {
3394 pullAlgorithm = () => promiseResolvedWith(undefined);
3395 }
3396 if (underlyingSource.cancel !== undefined) {
3397 cancelAlgorithm = reason => underlyingSource.cancel(reason);
3398 }
3399 else {
3400 cancelAlgorithm = () => promiseResolvedWith(undefined);
3401 }
3402 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
3403 }
3404 // Helper functions for the ReadableStreamDefaultController.
3405 function defaultControllerBrandCheckException$1(name) {
3406 return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);
3407 }
3408
3409 function ReadableStreamTee(stream, cloneForBranch2) {
3410 if (IsReadableByteStreamController(stream._readableStreamController)) {
3411 return ReadableByteStreamTee(stream);
3412 }
3413 return ReadableStreamDefaultTee(stream);
3414 }
3415 function ReadableStreamDefaultTee(stream, cloneForBranch2) {
3416 const reader = AcquireReadableStreamDefaultReader(stream);
3417 let reading = false;
3418 let readAgain = false;
3419 let canceled1 = false;
3420 let canceled2 = false;
3421 let reason1;
3422 let reason2;
3423 let branch1;
3424 let branch2;
3425 let resolveCancelPromise;
3426 const cancelPromise = newPromise(resolve => {
3427 resolveCancelPromise = resolve;
3428 });
3429 function pullAlgorithm() {
3430 if (reading) {
3431 readAgain = true;
3432 return promiseResolvedWith(undefined);
3433 }
3434 reading = true;
3435 const readRequest = {
3436 _chunkSteps: chunk => {
3437 // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3438 // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3439 // successful synchronously-available reads get ahead of asynchronously-available errors.
3440 _queueMicrotask(() => {
3441 readAgain = false;
3442 const chunk1 = chunk;
3443 const chunk2 = chunk;
3444 // There is no way to access the cloning code right now in the reference implementation.
3445 // If we add one then we'll need an implementation for serializable objects.
3446 // if (!canceled2 && cloneForBranch2) {
3447 // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));
3448 // }
3449 if (!canceled1) {
3450 ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);
3451 }
3452 if (!canceled2) {
3453 ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);
3454 }
3455 reading = false;
3456 if (readAgain) {
3457 pullAlgorithm();
3458 }
3459 });
3460 },
3461 _closeSteps: () => {
3462 reading = false;
3463 if (!canceled1) {
3464 ReadableStreamDefaultControllerClose(branch1._readableStreamController);
3465 }
3466 if (!canceled2) {
3467 ReadableStreamDefaultControllerClose(branch2._readableStreamController);
3468 }
3469 if (!canceled1 || !canceled2) {
3470 resolveCancelPromise(undefined);
3471 }
3472 },
3473 _errorSteps: () => {
3474 reading = false;
3475 }
3476 };
3477 ReadableStreamDefaultReaderRead(reader, readRequest);
3478 return promiseResolvedWith(undefined);
3479 }
3480 function cancel1Algorithm(reason) {
3481 canceled1 = true;
3482 reason1 = reason;
3483 if (canceled2) {
3484 const compositeReason = CreateArrayFromList([reason1, reason2]);
3485 const cancelResult = ReadableStreamCancel(stream, compositeReason);
3486 resolveCancelPromise(cancelResult);
3487 }
3488 return cancelPromise;
3489 }
3490 function cancel2Algorithm(reason) {
3491 canceled2 = true;
3492 reason2 = reason;
3493 if (canceled1) {
3494 const compositeReason = CreateArrayFromList([reason1, reason2]);
3495 const cancelResult = ReadableStreamCancel(stream, compositeReason);
3496 resolveCancelPromise(cancelResult);
3497 }
3498 return cancelPromise;
3499 }
3500 function startAlgorithm() {
3501 // do nothing
3502 }
3503 branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);
3504 branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);
3505 uponRejection(reader._closedPromise, (r) => {
3506 ReadableStreamDefaultControllerError(branch1._readableStreamController, r);
3507 ReadableStreamDefaultControllerError(branch2._readableStreamController, r);
3508 if (!canceled1 || !canceled2) {
3509 resolveCancelPromise(undefined);
3510 }
3511 return null;
3512 });
3513 return [branch1, branch2];
3514 }
3515 function ReadableByteStreamTee(stream) {
3516 let reader = AcquireReadableStreamDefaultReader(stream);
3517 let reading = false;
3518 let readAgainForBranch1 = false;
3519 let readAgainForBranch2 = false;
3520 let canceled1 = false;
3521 let canceled2 = false;
3522 let reason1;
3523 let reason2;
3524 let branch1;
3525 let branch2;
3526 let resolveCancelPromise;
3527 const cancelPromise = newPromise(resolve => {
3528 resolveCancelPromise = resolve;
3529 });
3530 function forwardReaderError(thisReader) {
3531 uponRejection(thisReader._closedPromise, r => {
3532 if (thisReader !== reader) {
3533 return null;
3534 }
3535 ReadableByteStreamControllerError(branch1._readableStreamController, r);
3536 ReadableByteStreamControllerError(branch2._readableStreamController, r);
3537 if (!canceled1 || !canceled2) {
3538 resolveCancelPromise(undefined);
3539 }
3540 return null;
3541 });
3542 }
3543 function pullWithDefaultReader() {
3544 if (IsReadableStreamBYOBReader(reader)) {
3545 ReadableStreamReaderGenericRelease(reader);
3546 reader = AcquireReadableStreamDefaultReader(stream);
3547 forwardReaderError(reader);
3548 }
3549 const readRequest = {
3550 _chunkSteps: chunk => {
3551 // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3552 // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3553 // successful synchronously-available reads get ahead of asynchronously-available errors.
3554 _queueMicrotask(() => {
3555 readAgainForBranch1 = false;
3556 readAgainForBranch2 = false;
3557 const chunk1 = chunk;
3558 let chunk2 = chunk;
3559 if (!canceled1 && !canceled2) {
3560 try {
3561 chunk2 = CloneAsUint8Array(chunk);
3562 }
3563 catch (cloneE) {
3564 ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);
3565 ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);
3566 resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
3567 return;
3568 }
3569 }
3570 if (!canceled1) {
3571 ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);
3572 }
3573 if (!canceled2) {
3574 ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);
3575 }
3576 reading = false;
3577 if (readAgainForBranch1) {
3578 pull1Algorithm();
3579 }
3580 else if (readAgainForBranch2) {
3581 pull2Algorithm();
3582 }
3583 });
3584 },
3585 _closeSteps: () => {
3586 reading = false;
3587 if (!canceled1) {
3588 ReadableByteStreamControllerClose(branch1._readableStreamController);
3589 }
3590 if (!canceled2) {
3591 ReadableByteStreamControllerClose(branch2._readableStreamController);
3592 }
3593 if (branch1._readableStreamController._pendingPullIntos.length > 0) {
3594 ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);
3595 }
3596 if (branch2._readableStreamController._pendingPullIntos.length > 0) {
3597 ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);
3598 }
3599 if (!canceled1 || !canceled2) {
3600 resolveCancelPromise(undefined);
3601 }
3602 },
3603 _errorSteps: () => {
3604 reading = false;
3605 }
3606 };
3607 ReadableStreamDefaultReaderRead(reader, readRequest);
3608 }
3609 function pullWithBYOBReader(view, forBranch2) {
3610 if (IsReadableStreamDefaultReader(reader)) {
3611 ReadableStreamReaderGenericRelease(reader);
3612 reader = AcquireReadableStreamBYOBReader(stream);
3613 forwardReaderError(reader);
3614 }
3615 const byobBranch = forBranch2 ? branch2 : branch1;
3616 const otherBranch = forBranch2 ? branch1 : branch2;
3617 const readIntoRequest = {
3618 _chunkSteps: chunk => {
3619 // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using
3620 // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let
3621 // successful synchronously-available reads get ahead of asynchronously-available errors.
3622 _queueMicrotask(() => {
3623 readAgainForBranch1 = false;
3624 readAgainForBranch2 = false;
3625 const byobCanceled = forBranch2 ? canceled2 : canceled1;
3626 const otherCanceled = forBranch2 ? canceled1 : canceled2;
3627 if (!otherCanceled) {
3628 let clonedChunk;
3629 try {
3630 clonedChunk = CloneAsUint8Array(chunk);
3631 }
3632 catch (cloneE) {
3633 ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);
3634 ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);
3635 resolveCancelPromise(ReadableStreamCancel(stream, cloneE));
3636 return;
3637 }
3638 if (!byobCanceled) {
3639 ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
3640 }
3641 ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);
3642 }
3643 else if (!byobCanceled) {
3644 ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
3645 }
3646 reading = false;
3647 if (readAgainForBranch1) {
3648 pull1Algorithm();
3649 }
3650 else if (readAgainForBranch2) {
3651 pull2Algorithm();
3652 }
3653 });
3654 },
3655 _closeSteps: chunk => {
3656 reading = false;
3657 const byobCanceled = forBranch2 ? canceled2 : canceled1;
3658 const otherCanceled = forBranch2 ? canceled1 : canceled2;
3659 if (!byobCanceled) {
3660 ReadableByteStreamControllerClose(byobBranch._readableStreamController);
3661 }
3662 if (!otherCanceled) {
3663 ReadableByteStreamControllerClose(otherBranch._readableStreamController);
3664 }
3665 if (chunk !== undefined) {
3666 if (!byobCanceled) {
3667 ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);
3668 }
3669 if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {
3670 ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);
3671 }
3672 }
3673 if (!byobCanceled || !otherCanceled) {
3674 resolveCancelPromise(undefined);
3675 }
3676 },
3677 _errorSteps: () => {
3678 reading = false;
3679 }
3680 };
3681 ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);
3682 }
3683 function pull1Algorithm() {
3684 if (reading) {
3685 readAgainForBranch1 = true;
3686 return promiseResolvedWith(undefined);
3687 }
3688 reading = true;
3689 const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);
3690 if (byobRequest === null) {
3691 pullWithDefaultReader();
3692 }
3693 else {
3694 pullWithBYOBReader(byobRequest._view, false);
3695 }
3696 return promiseResolvedWith(undefined);
3697 }
3698 function pull2Algorithm() {
3699 if (reading) {
3700 readAgainForBranch2 = true;
3701 return promiseResolvedWith(undefined);
3702 }
3703 reading = true;
3704 const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);
3705 if (byobRequest === null) {
3706 pullWithDefaultReader();
3707 }
3708 else {
3709 pullWithBYOBReader(byobRequest._view, true);
3710 }
3711 return promiseResolvedWith(undefined);
3712 }
3713 function cancel1Algorithm(reason) {
3714 canceled1 = true;
3715 reason1 = reason;
3716 if (canceled2) {
3717 const compositeReason = CreateArrayFromList([reason1, reason2]);
3718 const cancelResult = ReadableStreamCancel(stream, compositeReason);
3719 resolveCancelPromise(cancelResult);
3720 }
3721 return cancelPromise;
3722 }
3723 function cancel2Algorithm(reason) {
3724 canceled2 = true;
3725 reason2 = reason;
3726 if (canceled1) {
3727 const compositeReason = CreateArrayFromList([reason1, reason2]);
3728 const cancelResult = ReadableStreamCancel(stream, compositeReason);
3729 resolveCancelPromise(cancelResult);
3730 }
3731 return cancelPromise;
3732 }
3733 function startAlgorithm() {
3734 return;
3735 }
3736 branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);
3737 branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);
3738 forwardReaderError(reader);
3739 return [branch1, branch2];
3740 }
3741
3742 function isReadableStreamLike(stream) {
3743 return typeIsObject(stream) && typeof stream.getReader !== 'undefined';
3744 }
3745
3746 function ReadableStreamFrom(source) {
3747 if (isReadableStreamLike(source)) {
3748 return ReadableStreamFromDefaultReader(source.getReader());
3749 }
3750 return ReadableStreamFromIterable(source);
3751 }
3752 function ReadableStreamFromIterable(asyncIterable) {
3753 let stream;
3754 const iteratorRecord = GetIterator(asyncIterable, 'async');
3755 const startAlgorithm = noop;
3756 function pullAlgorithm() {
3757 let nextResult;
3758 try {
3759 nextResult = IteratorNext(iteratorRecord);
3760 }
3761 catch (e) {
3762 return promiseRejectedWith(e);
3763 }
3764 const nextPromise = promiseResolvedWith(nextResult);
3765 return transformPromiseWith(nextPromise, iterResult => {
3766 if (!typeIsObject(iterResult)) {
3767 throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');
3768 }
3769 const done = IteratorComplete(iterResult);
3770 if (done) {
3771 ReadableStreamDefaultControllerClose(stream._readableStreamController);
3772 }
3773 else {
3774 const value = IteratorValue(iterResult);
3775 ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3776 }
3777 });
3778 }
3779 function cancelAlgorithm(reason) {
3780 const iterator = iteratorRecord.iterator;
3781 let returnMethod;
3782 try {
3783 returnMethod = GetMethod(iterator, 'return');
3784 }
3785 catch (e) {
3786 return promiseRejectedWith(e);
3787 }
3788 if (returnMethod === undefined) {
3789 return promiseResolvedWith(undefined);
3790 }
3791 let returnResult;
3792 try {
3793 returnResult = reflectCall(returnMethod, iterator, [reason]);
3794 }
3795 catch (e) {
3796 return promiseRejectedWith(e);
3797 }
3798 const returnPromise = promiseResolvedWith(returnResult);
3799 return transformPromiseWith(returnPromise, iterResult => {
3800 if (!typeIsObject(iterResult)) {
3801 throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');
3802 }
3803 return undefined;
3804 });
3805 }
3806 stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3807 return stream;
3808 }
3809 function ReadableStreamFromDefaultReader(reader) {
3810 let stream;
3811 const startAlgorithm = noop;
3812 function pullAlgorithm() {
3813 let readPromise;
3814 try {
3815 readPromise = reader.read();
3816 }
3817 catch (e) {
3818 return promiseRejectedWith(e);
3819 }
3820 return transformPromiseWith(readPromise, readResult => {
3821 if (!typeIsObject(readResult)) {
3822 throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');
3823 }
3824 if (readResult.done) {
3825 ReadableStreamDefaultControllerClose(stream._readableStreamController);
3826 }
3827 else {
3828 const value = readResult.value;
3829 ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);
3830 }
3831 });
3832 }
3833 function cancelAlgorithm(reason) {
3834 try {
3835 return promiseResolvedWith(reader.cancel(reason));
3836 }
3837 catch (e) {
3838 return promiseRejectedWith(e);
3839 }
3840 }
3841 stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);
3842 return stream;
3843 }
3844
3845 function convertUnderlyingDefaultOrByteSource(source, context) {
3846 assertDictionary(source, context);
3847 const original = source;
3848 const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize;
3849 const cancel = original === null || original === void 0 ? void 0 : original.cancel;
3850 const pull = original === null || original === void 0 ? void 0 : original.pull;
3851 const start = original === null || original === void 0 ? void 0 : original.start;
3852 const type = original === null || original === void 0 ? void 0 : original.type;
3853 return {
3854 autoAllocateChunkSize: autoAllocateChunkSize === undefined ?
3855 undefined :
3856 convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`),
3857 cancel: cancel === undefined ?
3858 undefined :
3859 convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`),
3860 pull: pull === undefined ?
3861 undefined :
3862 convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`),
3863 start: start === undefined ?
3864 undefined :
3865 convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`),
3866 type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)
3867 };
3868 }
3869 function convertUnderlyingSourceCancelCallback(fn, original, context) {
3870 assertFunction(fn, context);
3871 return (reason) => promiseCall(fn, original, [reason]);
3872 }
3873 function convertUnderlyingSourcePullCallback(fn, original, context) {
3874 assertFunction(fn, context);
3875 return (controller) => promiseCall(fn, original, [controller]);
3876 }
3877 function convertUnderlyingSourceStartCallback(fn, original, context) {
3878 assertFunction(fn, context);
3879 return (controller) => reflectCall(fn, original, [controller]);
3880 }
3881 function convertReadableStreamType(type, context) {
3882 type = `${type}`;
3883 if (type !== 'bytes') {
3884 throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);
3885 }
3886 return type;
3887 }
3888
3889 function convertIteratorOptions(options, context) {
3890 assertDictionary(options, context);
3891 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
3892 return { preventCancel: Boolean(preventCancel) };
3893 }
3894
3895 function convertPipeOptions(options, context) {
3896 assertDictionary(options, context);
3897 const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort;
3898 const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel;
3899 const preventClose = options === null || options === void 0 ? void 0 : options.preventClose;
3900 const signal = options === null || options === void 0 ? void 0 : options.signal;
3901 if (signal !== undefined) {
3902 assertAbortSignal(signal, `${context} has member 'signal' that`);
3903 }
3904 return {
3905 preventAbort: Boolean(preventAbort),
3906 preventCancel: Boolean(preventCancel),
3907 preventClose: Boolean(preventClose),
3908 signal
3909 };
3910 }
3911 function assertAbortSignal(signal, context) {
3912 if (!isAbortSignal(signal)) {
3913 throw new TypeError(`${context} is not an AbortSignal.`);
3914 }
3915 }
3916
3917 function convertReadableWritablePair(pair, context) {
3918 assertDictionary(pair, context);
3919 const readable = pair === null || pair === void 0 ? void 0 : pair.readable;
3920 assertRequiredField(readable, 'readable', 'ReadableWritablePair');
3921 assertReadableStream(readable, `${context} has member 'readable' that`);
3922 const writable = pair === null || pair === void 0 ? void 0 : pair.writable;
3923 assertRequiredField(writable, 'writable', 'ReadableWritablePair');
3924 assertWritableStream(writable, `${context} has member 'writable' that`);
3925 return { readable, writable };
3926 }
3927
3928 /**
3929 * A readable stream represents a source of data, from which you can read.
3930 *
3931 * @public
3932 */
3933 class ReadableStream {
3934 constructor(rawUnderlyingSource = {}, rawStrategy = {}) {
3935 if (rawUnderlyingSource === undefined) {
3936 rawUnderlyingSource = null;
3937 }
3938 else {
3939 assertObject(rawUnderlyingSource, 'First parameter');
3940 }
3941 const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');
3942 const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');
3943 InitializeReadableStream(this);
3944 if (underlyingSource.type === 'bytes') {
3945 if (strategy.size !== undefined) {
3946 throw new RangeError('The strategy for a byte stream cannot have a size function');
3947 }
3948 const highWaterMark = ExtractHighWaterMark(strategy, 0);
3949 SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark);
3950 }
3951 else {
3952 const sizeAlgorithm = ExtractSizeAlgorithm(strategy);
3953 const highWaterMark = ExtractHighWaterMark(strategy, 1);
3954 SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm);
3955 }
3956 }
3957 /**
3958 * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
3959 */
3960 get locked() {
3961 if (!IsReadableStream(this)) {
3962 throw streamBrandCheckException$1('locked');
3963 }
3964 return IsReadableStreamLocked(this);
3965 }
3966 /**
3967 * Cancels the stream, signaling a loss of interest in the stream by a consumer.
3968 *
3969 * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
3970 * method, which might or might not use it.
3971 */
3972 cancel(reason = undefined) {
3973 if (!IsReadableStream(this)) {
3974 return promiseRejectedWith(streamBrandCheckException$1('cancel'));
3975 }
3976 if (IsReadableStreamLocked(this)) {
3977 return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));
3978 }
3979 return ReadableStreamCancel(this, reason);
3980 }
3981 getReader(rawOptions = undefined) {
3982 if (!IsReadableStream(this)) {
3983 throw streamBrandCheckException$1('getReader');
3984 }
3985 const options = convertReaderOptions(rawOptions, 'First parameter');
3986 if (options.mode === undefined) {
3987 return AcquireReadableStreamDefaultReader(this);
3988 }
3989 return AcquireReadableStreamBYOBReader(this);
3990 }
3991 pipeThrough(rawTransform, rawOptions = {}) {
3992 if (!IsReadableStream(this)) {
3993 throw streamBrandCheckException$1('pipeThrough');
3994 }
3995 assertRequiredArgument(rawTransform, 1, 'pipeThrough');
3996 const transform = convertReadableWritablePair(rawTransform, 'First parameter');
3997 const options = convertPipeOptions(rawOptions, 'Second parameter');
3998 if (IsReadableStreamLocked(this)) {
3999 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');
4000 }
4001 if (IsWritableStreamLocked(transform.writable)) {
4002 throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');
4003 }
4004 const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
4005 setPromiseIsHandledToTrue(promise);
4006 return transform.readable;
4007 }
4008 pipeTo(destination, rawOptions = {}) {
4009 if (!IsReadableStream(this)) {
4010 return promiseRejectedWith(streamBrandCheckException$1('pipeTo'));
4011 }
4012 if (destination === undefined) {
4013 return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);
4014 }
4015 if (!IsWritableStream(destination)) {
4016 return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`));
4017 }
4018 let options;
4019 try {
4020 options = convertPipeOptions(rawOptions, 'Second parameter');
4021 }
4022 catch (e) {
4023 return promiseRejectedWith(e);
4024 }
4025 if (IsReadableStreamLocked(this)) {
4026 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream'));
4027 }
4028 if (IsWritableStreamLocked(destination)) {
4029 return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream'));
4030 }
4031 return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal);
4032 }
4033 /**
4034 * Tees this readable stream, returning a two-element array containing the two resulting branches as
4035 * new {@link ReadableStream} instances.
4036 *
4037 * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
4038 * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
4039 * propagated to the stream's underlying source.
4040 *
4041 * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
4042 * this could allow interference between the two branches.
4043 */
4044 tee() {
4045 if (!IsReadableStream(this)) {
4046 throw streamBrandCheckException$1('tee');
4047 }
4048 const branches = ReadableStreamTee(this);
4049 return CreateArrayFromList(branches);
4050 }
4051 values(rawOptions = undefined) {
4052 if (!IsReadableStream(this)) {
4053 throw streamBrandCheckException$1('values');
4054 }
4055 const options = convertIteratorOptions(rawOptions, 'First parameter');
4056 return AcquireReadableStreamAsyncIterator(this, options.preventCancel);
4057 }
4058 /**
4059 * Creates a new ReadableStream wrapping the provided iterable or async iterable.
4060 *
4061 * This can be used to adapt various kinds of objects into a readable stream,
4062 * such as an array, an async generator, or a Node.js readable stream.
4063 */
4064 static from(asyncIterable) {
4065 return ReadableStreamFrom(asyncIterable);
4066 }
4067 }
4068 Object.defineProperties(ReadableStream, {
4069 from: { enumerable: true }
4070 });
4071 Object.defineProperties(ReadableStream.prototype, {
4072 cancel: { enumerable: true },
4073 getReader: { enumerable: true },
4074 pipeThrough: { enumerable: true },
4075 pipeTo: { enumerable: true },
4076 tee: { enumerable: true },
4077 values: { enumerable: true },
4078 locked: { enumerable: true }
4079 });
4080 setFunctionName(ReadableStream.from, 'from');
4081 setFunctionName(ReadableStream.prototype.cancel, 'cancel');
4082 setFunctionName(ReadableStream.prototype.getReader, 'getReader');
4083 setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');
4084 setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');
4085 setFunctionName(ReadableStream.prototype.tee, 'tee');
4086 setFunctionName(ReadableStream.prototype.values, 'values');
4087 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4088 Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, {
4089 value: 'ReadableStream',
4090 configurable: true
4091 });
4092 }
4093 if (typeof SymbolPolyfill.asyncIterator === 'symbol') {
4094 Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, {
4095 value: ReadableStream.prototype.values,
4096 writable: true,
4097 configurable: true
4098 });
4099 }
4100 // Abstract operations for the ReadableStream.
4101 // Throws if and only if startAlgorithm throws.
4102 function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) {
4103 const stream = Object.create(ReadableStream.prototype);
4104 InitializeReadableStream(stream);
4105 const controller = Object.create(ReadableStreamDefaultController.prototype);
4106 SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm);
4107 return stream;
4108 }
4109 // Throws if and only if startAlgorithm throws.
4110 function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) {
4111 const stream = Object.create(ReadableStream.prototype);
4112 InitializeReadableStream(stream);
4113 const controller = Object.create(ReadableByteStreamController.prototype);
4114 SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);
4115 return stream;
4116 }
4117 function InitializeReadableStream(stream) {
4118 stream._state = 'readable';
4119 stream._reader = undefined;
4120 stream._storedError = undefined;
4121 stream._disturbed = false;
4122 }
4123 function IsReadableStream(x) {
4124 if (!typeIsObject(x)) {
4125 return false;
4126 }
4127 if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {
4128 return false;
4129 }
4130 return x instanceof ReadableStream;
4131 }
4132 function IsReadableStreamLocked(stream) {
4133 if (stream._reader === undefined) {
4134 return false;
4135 }
4136 return true;
4137 }
4138 // ReadableStream API exposed for controllers.
4139 function ReadableStreamCancel(stream, reason) {
4140 stream._disturbed = true;
4141 if (stream._state === 'closed') {
4142 return promiseResolvedWith(undefined);
4143 }
4144 if (stream._state === 'errored') {
4145 return promiseRejectedWith(stream._storedError);
4146 }
4147 ReadableStreamClose(stream);
4148 const reader = stream._reader;
4149 if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {
4150 const readIntoRequests = reader._readIntoRequests;
4151 reader._readIntoRequests = new SimpleQueue();
4152 readIntoRequests.forEach(readIntoRequest => {
4153 readIntoRequest._closeSteps(undefined);
4154 });
4155 }
4156 const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);
4157 return transformPromiseWith(sourceCancelPromise, noop);
4158 }
4159 function ReadableStreamClose(stream) {
4160 stream._state = 'closed';
4161 const reader = stream._reader;
4162 if (reader === undefined) {
4163 return;
4164 }
4165 defaultReaderClosedPromiseResolve(reader);
4166 if (IsReadableStreamDefaultReader(reader)) {
4167 const readRequests = reader._readRequests;
4168 reader._readRequests = new SimpleQueue();
4169 readRequests.forEach(readRequest => {
4170 readRequest._closeSteps();
4171 });
4172 }
4173 }
4174 function ReadableStreamError(stream, e) {
4175 stream._state = 'errored';
4176 stream._storedError = e;
4177 const reader = stream._reader;
4178 if (reader === undefined) {
4179 return;
4180 }
4181 defaultReaderClosedPromiseReject(reader, e);
4182 if (IsReadableStreamDefaultReader(reader)) {
4183 ReadableStreamDefaultReaderErrorReadRequests(reader, e);
4184 }
4185 else {
4186 ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);
4187 }
4188 }
4189 // Helper functions for the ReadableStream.
4190 function streamBrandCheckException$1(name) {
4191 return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);
4192 }
4193
4194 function convertQueuingStrategyInit(init, context) {
4195 assertDictionary(init, context);
4196 const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark;
4197 assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');
4198 return {
4199 highWaterMark: convertUnrestrictedDouble(highWaterMark)
4200 };
4201 }
4202
4203 // The size function must not have a prototype property nor be a constructor
4204 const byteLengthSizeFunction = (chunk) => {
4205 return chunk.byteLength;
4206 };
4207 setFunctionName(byteLengthSizeFunction, 'size');
4208 /**
4209 * A queuing strategy that counts the number of bytes in each chunk.
4210 *
4211 * @public
4212 */
4213 class ByteLengthQueuingStrategy {
4214 constructor(options) {
4215 assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');
4216 options = convertQueuingStrategyInit(options, 'First parameter');
4217 this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;
4218 }
4219 /**
4220 * Returns the high water mark provided to the constructor.
4221 */
4222 get highWaterMark() {
4223 if (!IsByteLengthQueuingStrategy(this)) {
4224 throw byteLengthBrandCheckException('highWaterMark');
4225 }
4226 return this._byteLengthQueuingStrategyHighWaterMark;
4227 }
4228 /**
4229 * Measures the size of `chunk` by returning the value of its `byteLength` property.
4230 */
4231 get size() {
4232 if (!IsByteLengthQueuingStrategy(this)) {
4233 throw byteLengthBrandCheckException('size');
4234 }
4235 return byteLengthSizeFunction;
4236 }
4237 }
4238 Object.defineProperties(ByteLengthQueuingStrategy.prototype, {
4239 highWaterMark: { enumerable: true },
4240 size: { enumerable: true }
4241 });
4242 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4243 Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
4244 value: 'ByteLengthQueuingStrategy',
4245 configurable: true
4246 });
4247 }
4248 // Helper functions for the ByteLengthQueuingStrategy.
4249 function byteLengthBrandCheckException(name) {
4250 return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);
4251 }
4252 function IsByteLengthQueuingStrategy(x) {
4253 if (!typeIsObject(x)) {
4254 return false;
4255 }
4256 if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {
4257 return false;
4258 }
4259 return x instanceof ByteLengthQueuingStrategy;
4260 }
4261
4262 // The size function must not have a prototype property nor be a constructor
4263 const countSizeFunction = () => {
4264 return 1;
4265 };
4266 setFunctionName(countSizeFunction, 'size');
4267 /**
4268 * A queuing strategy that counts the number of chunks.
4269 *
4270 * @public
4271 */
4272 class CountQueuingStrategy {
4273 constructor(options) {
4274 assertRequiredArgument(options, 1, 'CountQueuingStrategy');
4275 options = convertQueuingStrategyInit(options, 'First parameter');
4276 this._countQueuingStrategyHighWaterMark = options.highWaterMark;
4277 }
4278 /**
4279 * Returns the high water mark provided to the constructor.
4280 */
4281 get highWaterMark() {
4282 if (!IsCountQueuingStrategy(this)) {
4283 throw countBrandCheckException('highWaterMark');
4284 }
4285 return this._countQueuingStrategyHighWaterMark;
4286 }
4287 /**
4288 * Measures the size of `chunk` by always returning 1.
4289 * This ensures that the total queue size is a count of the number of chunks in the queue.
4290 */
4291 get size() {
4292 if (!IsCountQueuingStrategy(this)) {
4293 throw countBrandCheckException('size');
4294 }
4295 return countSizeFunction;
4296 }
4297 }
4298 Object.defineProperties(CountQueuingStrategy.prototype, {
4299 highWaterMark: { enumerable: true },
4300 size: { enumerable: true }
4301 });
4302 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4303 Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, {
4304 value: 'CountQueuingStrategy',
4305 configurable: true
4306 });
4307 }
4308 // Helper functions for the CountQueuingStrategy.
4309 function countBrandCheckException(name) {
4310 return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);
4311 }
4312 function IsCountQueuingStrategy(x) {
4313 if (!typeIsObject(x)) {
4314 return false;
4315 }
4316 if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {
4317 return false;
4318 }
4319 return x instanceof CountQueuingStrategy;
4320 }
4321
4322 function convertTransformer(original, context) {
4323 assertDictionary(original, context);
4324 const cancel = original === null || original === void 0 ? void 0 : original.cancel;
4325 const flush = original === null || original === void 0 ? void 0 : original.flush;
4326 const readableType = original === null || original === void 0 ? void 0 : original.readableType;
4327 const start = original === null || original === void 0 ? void 0 : original.start;
4328 const transform = original === null || original === void 0 ? void 0 : original.transform;
4329 const writableType = original === null || original === void 0 ? void 0 : original.writableType;
4330 return {
4331 cancel: cancel === undefined ?
4332 undefined :
4333 convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`),
4334 flush: flush === undefined ?
4335 undefined :
4336 convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`),
4337 readableType,
4338 start: start === undefined ?
4339 undefined :
4340 convertTransformerStartCallback(start, original, `${context} has member 'start' that`),
4341 transform: transform === undefined ?
4342 undefined :
4343 convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`),
4344 writableType
4345 };
4346 }
4347 function convertTransformerFlushCallback(fn, original, context) {
4348 assertFunction(fn, context);
4349 return (controller) => promiseCall(fn, original, [controller]);
4350 }
4351 function convertTransformerStartCallback(fn, original, context) {
4352 assertFunction(fn, context);
4353 return (controller) => reflectCall(fn, original, [controller]);
4354 }
4355 function convertTransformerTransformCallback(fn, original, context) {
4356 assertFunction(fn, context);
4357 return (chunk, controller) => promiseCall(fn, original, [chunk, controller]);
4358 }
4359 function convertTransformerCancelCallback(fn, original, context) {
4360 assertFunction(fn, context);
4361 return (reason) => promiseCall(fn, original, [reason]);
4362 }
4363
4364 // Class TransformStream
4365 /**
4366 * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
4367 * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
4368 * In a manner specific to the transform stream in question, writes to the writable side result in new data being
4369 * made available for reading from the readable side.
4370 *
4371 * @public
4372 */
4373 class TransformStream {
4374 constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) {
4375 if (rawTransformer === undefined) {
4376 rawTransformer = null;
4377 }
4378 const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');
4379 const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');
4380 const transformer = convertTransformer(rawTransformer, 'First parameter');
4381 if (transformer.readableType !== undefined) {
4382 throw new RangeError('Invalid readableType specified');
4383 }
4384 if (transformer.writableType !== undefined) {
4385 throw new RangeError('Invalid writableType specified');
4386 }
4387 const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);
4388 const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);
4389 const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);
4390 const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);
4391 let startPromise_resolve;
4392 const startPromise = newPromise(resolve => {
4393 startPromise_resolve = resolve;
4394 });
4395 InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
4396 SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);
4397 if (transformer.start !== undefined) {
4398 startPromise_resolve(transformer.start(this._transformStreamController));
4399 }
4400 else {
4401 startPromise_resolve(undefined);
4402 }
4403 }
4404 /**
4405 * The readable side of the transform stream.
4406 */
4407 get readable() {
4408 if (!IsTransformStream(this)) {
4409 throw streamBrandCheckException('readable');
4410 }
4411 return this._readable;
4412 }
4413 /**
4414 * The writable side of the transform stream.
4415 */
4416 get writable() {
4417 if (!IsTransformStream(this)) {
4418 throw streamBrandCheckException('writable');
4419 }
4420 return this._writable;
4421 }
4422 }
4423 Object.defineProperties(TransformStream.prototype, {
4424 readable: { enumerable: true },
4425 writable: { enumerable: true }
4426 });
4427 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4428 Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, {
4429 value: 'TransformStream',
4430 configurable: true
4431 });
4432 }
4433 function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) {
4434 function startAlgorithm() {
4435 return startPromise;
4436 }
4437 function writeAlgorithm(chunk) {
4438 return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);
4439 }
4440 function abortAlgorithm(reason) {
4441 return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);
4442 }
4443 function closeAlgorithm() {
4444 return TransformStreamDefaultSinkCloseAlgorithm(stream);
4445 }
4446 stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm);
4447 function pullAlgorithm() {
4448 return TransformStreamDefaultSourcePullAlgorithm(stream);
4449 }
4450 function cancelAlgorithm(reason) {
4451 return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);
4452 }
4453 stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm);
4454 // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.
4455 stream._backpressure = undefined;
4456 stream._backpressureChangePromise = undefined;
4457 stream._backpressureChangePromise_resolve = undefined;
4458 TransformStreamSetBackpressure(stream, true);
4459 stream._transformStreamController = undefined;
4460 }
4461 function IsTransformStream(x) {
4462 if (!typeIsObject(x)) {
4463 return false;
4464 }
4465 if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {
4466 return false;
4467 }
4468 return x instanceof TransformStream;
4469 }
4470 // This is a no-op if both sides are already errored.
4471 function TransformStreamError(stream, e) {
4472 ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);
4473 TransformStreamErrorWritableAndUnblockWrite(stream, e);
4474 }
4475 function TransformStreamErrorWritableAndUnblockWrite(stream, e) {
4476 TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);
4477 WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);
4478 TransformStreamUnblockWrite(stream);
4479 }
4480 function TransformStreamUnblockWrite(stream) {
4481 if (stream._backpressure) {
4482 // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()
4483 // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time
4484 // _backpressure is set.
4485 TransformStreamSetBackpressure(stream, false);
4486 }
4487 }
4488 function TransformStreamSetBackpressure(stream, backpressure) {
4489 // Passes also when called during construction.
4490 if (stream._backpressureChangePromise !== undefined) {
4491 stream._backpressureChangePromise_resolve();
4492 }
4493 stream._backpressureChangePromise = newPromise(resolve => {
4494 stream._backpressureChangePromise_resolve = resolve;
4495 });
4496 stream._backpressure = backpressure;
4497 }
4498 // Class TransformStreamDefaultController
4499 /**
4500 * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
4501 *
4502 * @public
4503 */
4504 class TransformStreamDefaultController {
4505 constructor() {
4506 throw new TypeError('Illegal constructor');
4507 }
4508 /**
4509 * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.
4510 */
4511 get desiredSize() {
4512 if (!IsTransformStreamDefaultController(this)) {
4513 throw defaultControllerBrandCheckException('desiredSize');
4514 }
4515 const readableController = this._controlledTransformStream._readable._readableStreamController;
4516 return ReadableStreamDefaultControllerGetDesiredSize(readableController);
4517 }
4518 enqueue(chunk = undefined) {
4519 if (!IsTransformStreamDefaultController(this)) {
4520 throw defaultControllerBrandCheckException('enqueue');
4521 }
4522 TransformStreamDefaultControllerEnqueue(this, chunk);
4523 }
4524 /**
4525 * Errors both the readable side and the writable side of the controlled transform stream, making all future
4526 * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
4527 */
4528 error(reason = undefined) {
4529 if (!IsTransformStreamDefaultController(this)) {
4530 throw defaultControllerBrandCheckException('error');
4531 }
4532 TransformStreamDefaultControllerError(this, reason);
4533 }
4534 /**
4535 * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
4536 * transformer only needs to consume a portion of the chunks written to the writable side.
4537 */
4538 terminate() {
4539 if (!IsTransformStreamDefaultController(this)) {
4540 throw defaultControllerBrandCheckException('terminate');
4541 }
4542 TransformStreamDefaultControllerTerminate(this);
4543 }
4544 }
4545 Object.defineProperties(TransformStreamDefaultController.prototype, {
4546 enqueue: { enumerable: true },
4547 error: { enumerable: true },
4548 terminate: { enumerable: true },
4549 desiredSize: { enumerable: true }
4550 });
4551 setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');
4552 setFunctionName(TransformStreamDefaultController.prototype.error, 'error');
4553 setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');
4554 if (typeof SymbolPolyfill.toStringTag === 'symbol') {
4555 Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, {
4556 value: 'TransformStreamDefaultController',
4557 configurable: true
4558 });
4559 }
4560 // Transform Stream Default Controller Abstract Operations
4561 function IsTransformStreamDefaultController(x) {
4562 if (!typeIsObject(x)) {
4563 return false;
4564 }
4565 if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {
4566 return false;
4567 }
4568 return x instanceof TransformStreamDefaultController;
4569 }
4570 function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) {
4571 controller._controlledTransformStream = stream;
4572 stream._transformStreamController = controller;
4573 controller._transformAlgorithm = transformAlgorithm;
4574 controller._flushAlgorithm = flushAlgorithm;
4575 controller._cancelAlgorithm = cancelAlgorithm;
4576 controller._finishPromise = undefined;
4577 controller._finishPromise_resolve = undefined;
4578 controller._finishPromise_reject = undefined;
4579 }
4580 function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) {
4581 const controller = Object.create(TransformStreamDefaultController.prototype);
4582 let transformAlgorithm;
4583 let flushAlgorithm;
4584 let cancelAlgorithm;
4585 if (transformer.transform !== undefined) {
4586 transformAlgorithm = chunk => transformer.transform(chunk, controller);
4587 }
4588 else {
4589 transformAlgorithm = chunk => {
4590 try {
4591 TransformStreamDefaultControllerEnqueue(controller, chunk);
4592 return promiseResolvedWith(undefined);
4593 }
4594 catch (transformResultE) {
4595 return promiseRejectedWith(transformResultE);
4596 }
4597 };
4598 }
4599 if (transformer.flush !== undefined) {
4600 flushAlgorithm = () => transformer.flush(controller);
4601 }
4602 else {
4603 flushAlgorithm = () => promiseResolvedWith(undefined);
4604 }
4605 if (transformer.cancel !== undefined) {
4606 cancelAlgorithm = reason => transformer.cancel(reason);
4607 }
4608 else {
4609 cancelAlgorithm = () => promiseResolvedWith(undefined);
4610 }
4611 SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);
4612 }
4613 function TransformStreamDefaultControllerClearAlgorithms(controller) {
4614 controller._transformAlgorithm = undefined;
4615 controller._flushAlgorithm = undefined;
4616 controller._cancelAlgorithm = undefined;
4617 }
4618 function TransformStreamDefaultControllerEnqueue(controller, chunk) {
4619 const stream = controller._controlledTransformStream;
4620 const readableController = stream._readable._readableStreamController;
4621 if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {
4622 throw new TypeError('Readable side is not in a state that permits enqueue');
4623 }
4624 // We throttle transform invocations based on the backpressure of the ReadableStream, but we still
4625 // accept TransformStreamDefaultControllerEnqueue() calls.
4626 try {
4627 ReadableStreamDefaultControllerEnqueue(readableController, chunk);
4628 }
4629 catch (e) {
4630 // This happens when readableStrategy.size() throws.
4631 TransformStreamErrorWritableAndUnblockWrite(stream, e);
4632 throw stream._readable._storedError;
4633 }
4634 const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);
4635 if (backpressure !== stream._backpressure) {
4636 TransformStreamSetBackpressure(stream, true);
4637 }
4638 }
4639 function TransformStreamDefaultControllerError(controller, e) {
4640 TransformStreamError(controller._controlledTransformStream, e);
4641 }
4642 function TransformStreamDefaultControllerPerformTransform(controller, chunk) {
4643 const transformPromise = controller._transformAlgorithm(chunk);
4644 return transformPromiseWith(transformPromise, undefined, r => {
4645 TransformStreamError(controller._controlledTransformStream, r);
4646 throw r;
4647 });
4648 }
4649 function TransformStreamDefaultControllerTerminate(controller) {
4650 const stream = controller._controlledTransformStream;
4651 const readableController = stream._readable._readableStreamController;
4652 ReadableStreamDefaultControllerClose(readableController);
4653 const error = new TypeError('TransformStream terminated');
4654 TransformStreamErrorWritableAndUnblockWrite(stream, error);
4655 }
4656 // TransformStreamDefaultSink Algorithms
4657 function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) {
4658 const controller = stream._transformStreamController;
4659 if (stream._backpressure) {
4660 const backpressureChangePromise = stream._backpressureChangePromise;
4661 return transformPromiseWith(backpressureChangePromise, () => {
4662 const writable = stream._writable;
4663 const state = writable._state;
4664 if (state === 'erroring') {
4665 throw writable._storedError;
4666 }
4667 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
4668 });
4669 }
4670 return TransformStreamDefaultControllerPerformTransform(controller, chunk);
4671 }
4672 function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) {
4673 const controller = stream._transformStreamController;
4674 if (controller._finishPromise !== undefined) {
4675 return controller._finishPromise;
4676 }
4677 // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4678 const readable = stream._readable;
4679 // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,
4680 // we don't run the _cancelAlgorithm again.
4681 controller._finishPromise = newPromise((resolve, reject) => {
4682 controller._finishPromise_resolve = resolve;
4683 controller._finishPromise_reject = reject;
4684 });
4685 const cancelPromise = controller._cancelAlgorithm(reason);
4686 TransformStreamDefaultControllerClearAlgorithms(controller);
4687 uponPromise(cancelPromise, () => {
4688 if (readable._state === 'errored') {
4689 defaultControllerFinishPromiseReject(controller, readable._storedError);
4690 }
4691 else {
4692 ReadableStreamDefaultControllerError(readable._readableStreamController, reason);
4693 defaultControllerFinishPromiseResolve(controller);
4694 }
4695 return null;
4696 }, r => {
4697 ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4698 defaultControllerFinishPromiseReject(controller, r);
4699 return null;
4700 });
4701 return controller._finishPromise;
4702 }
4703 function TransformStreamDefaultSinkCloseAlgorithm(stream) {
4704 const controller = stream._transformStreamController;
4705 if (controller._finishPromise !== undefined) {
4706 return controller._finishPromise;
4707 }
4708 // stream._readable cannot change after construction, so caching it across a call to user code is safe.
4709 const readable = stream._readable;
4710 // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,
4711 // we don't also run the _cancelAlgorithm.
4712 controller._finishPromise = newPromise((resolve, reject) => {
4713 controller._finishPromise_resolve = resolve;
4714 controller._finishPromise_reject = reject;
4715 });
4716 const flushPromise = controller._flushAlgorithm();
4717 TransformStreamDefaultControllerClearAlgorithms(controller);
4718 uponPromise(flushPromise, () => {
4719 if (readable._state === 'errored') {
4720 defaultControllerFinishPromiseReject(controller, readable._storedError);
4721 }
4722 else {
4723 ReadableStreamDefaultControllerClose(readable._readableStreamController);
4724 defaultControllerFinishPromiseResolve(controller);
4725 }
4726 return null;
4727 }, r => {
4728 ReadableStreamDefaultControllerError(readable._readableStreamController, r);
4729 defaultControllerFinishPromiseReject(controller, r);
4730 return null;
4731 });
4732 return controller._finishPromise;
4733 }
4734 // TransformStreamDefaultSource Algorithms
4735 function TransformStreamDefaultSourcePullAlgorithm(stream) {
4736 // Invariant. Enforced by the promises returned by start() and pull().
4737 TransformStreamSetBackpressure(stream, false);
4738 // Prevent the next pull() call until there is backpressure.
4739 return stream._backpressureChangePromise;
4740 }
4741 function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) {
4742 const controller = stream._transformStreamController;
4743 if (controller._finishPromise !== undefined) {
4744 return controller._finishPromise;
4745 }
4746 // stream._writable cannot change after construction, so caching it across a call to user code is safe.
4747 const writable = stream._writable;
4748 // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or
4749 // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the
4750 // _flushAlgorithm.
4751 controller._finishPromise = newPromise((resolve, reject) => {
4752 controller._finishPromise_resolve = resolve;
4753 controller._finishPromise_reject = reject;
4754 });
4755 const cancelPromise = controller._cancelAlgorithm(reason);
4756 TransformStreamDefaultControllerClearAlgorithms(controller);
4757 uponPromise(cancelPromise, () => {
4758 if (writable._state === 'errored') {
4759 defaultControllerFinishPromiseReject(controller, writable._storedError);
4760 }
4761 else {
4762 WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);
4763 TransformStreamUnblockWrite(stream);
4764 defaultControllerFinishPromiseResolve(controller);
4765 }
4766 return null;
4767 }, r => {
4768 WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);
4769 TransformStreamUnblockWrite(stream);
4770 defaultControllerFinishPromiseReject(controller, r);
4771 return null;
4772 });
4773 return controller._finishPromise;
4774 }
4775 // Helper functions for the TransformStreamDefaultController.
4776 function defaultControllerBrandCheckException(name) {
4777 return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);
4778 }
4779 function defaultControllerFinishPromiseResolve(controller) {
4780 if (controller._finishPromise_resolve === undefined) {
4781 return;
4782 }
4783 controller._finishPromise_resolve();
4784 controller._finishPromise_resolve = undefined;
4785 controller._finishPromise_reject = undefined;
4786 }
4787 function defaultControllerFinishPromiseReject(controller, reason) {
4788 if (controller._finishPromise_reject === undefined) {
4789 return;
4790 }
4791 setPromiseIsHandledToTrue(controller._finishPromise);
4792 controller._finishPromise_reject(reason);
4793 controller._finishPromise_resolve = undefined;
4794 controller._finishPromise_reject = undefined;
4795 }
4796 // Helper functions for the TransformStream.
4797 function streamBrandCheckException(name) {
4798 return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`);
4799 }
4800
4801 exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy;
4802 exports.CountQueuingStrategy = CountQueuingStrategy;
4803 exports.ReadableByteStreamController = ReadableByteStreamController;
4804 exports.ReadableStream = ReadableStream;
4805 exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader;
4806 exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest;
4807 exports.ReadableStreamDefaultController = ReadableStreamDefaultController;
4808 exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader;
4809 exports.TransformStream = TransformStream;
4810 exports.TransformStreamDefaultController = TransformStreamDefaultController;
4811 exports.WritableStream = WritableStream;
4812 exports.WritableStreamDefaultController = WritableStreamDefaultController;
4813 exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter;
4814
4815}));
4816//# sourceMappingURL=ponyfill.es6.js.map
Note: See TracBrowser for help on using the repository browser.