<pre class=metadata>
Group: WHATWG
H1: Streams
Shortname: streams
Text Macro: TWITTER streamsstandard
Abstract: This specification provides APIs for creating, composing, and consuming streams of data that map efficiently
Abstract: to low-level I/O primitives.
Translation: ja https://triple-underscore.github.io/Streams-ja.html
!Demos: <a href="https://streams.spec.whatwg.org/demos/">streams.spec.whatwg.org/demos</a>
Opaque Elements: emu-alg
</pre>

<pre class=link-defaults>
spec:webidl; type:dfn;
    text:resolve
</pre>

<pre class="anchors">
urlPrefix: https://tc39.github.io/ecma262/; spec: ECMASCRIPT
    text: %Uint8Array%; url: #sec-typedarray-objects; type: constructor
    text: %AsyncIteratorPrototype%; url: #sec-asynciteratorprototype; type: interface
    text: AsyncIterator; url: #sec-asynciterator-interface; type: interface
    text: ArrayBuffer; url: #sec-arraybuffer-objects; type: interface
    text: DataView; url: #sec-dataview-objects; type: interface
    text: Number; url: #sec-ecmascript-language-types-number-type; type: interface
    text: Uint8Array; url: #sec-typedarray-objects; type: interface
    text: typed array; url: #sec-typedarray-objects; type: dfn
    text: the typed array constructors table; url: #table-49; type: dfn
    text: TypeError; url: #sec-native-error-types-used-in-this-standard-typeerror; type: exception
    text: Invoke; url: #sec-invoke; type: abstract-op
    text: DestructuringAssignmentEvaluation; url: #sec-runtime-semantics-destructuringassignmentevaluation; type: abstract-op
    text: map; url: #sec-array.prototype.map; type: method; for: Array.prototype
    text: CreateIterResultObject; url: #sec-createiterresultobject; type: abstract-op
</pre>

<style>
  emu-val { font-weight: bold; }
  emu-alg > ol, emu-alg > ol ol ol ol { list-style-type: decimal; }
  emu-alg > ol ol, emu-alg > ol ol ol ol ol { list-style-type: lower-alpha; }
  emu-alg > ol ol ol, emu-alg > ol ol ol ol ol ol { list-style-type: lower-roman; }
  emu-alg li { margin: 0; }

  .heading .annotation {
    background-color: beige;
    border: 1px solid black;
    border-radius: 3px;
    cursor: help;
    display: inline-block;
    font-size: 70%;
    font-weight: normal;
    padding: 1px 2px;
  }
</style>

<h2 id="intro">Introduction</h2>

<div class="non-normative">

<em>This section is non-normative.</em>

Large swathes of the web platform are built on streaming data: that is, data that is created, processed, and consumed
in an incremental fashion, without ever reading all of it into memory. The Streams Standard provides a common set of
APIs for creating and interfacing with such streaming data, embodied in <a>readable streams</a>,
<a>writable streams</a>, and <a>transform streams</a>.

These APIs have been designed to efficiently map to low-level I/O primitives, including specializations for byte streams
where appropriate. They allow easy composition of multiple streams into <a>pipe chains</a>, or can be used directly via
<a>readers</a> and <a>writers</a>. Finally, they are designed to automatically provide <a>backpressure</a> and queuing.

This standard provides the base stream primitives which other parts of the web platform can use to expose their
streaming data. For example, [[FETCH]] exposes {{Response}} bodies as {{ReadableStream}} instances. More generally, the
platform is full of streaming abstractions waiting to be expressed as streams: multimedia streams, file streams,
inter-global communication, and more benefit from being able to process data incrementally instead of buffering it all
into memory and processing it in one go. By providing the foundation for these streams to be exposed to developers, the
Streams Standard enables use cases like:

<ul>
  <li> Video effects: piping a readable video stream through a transform stream that applies effects in real time.
  <li> Decompression: piping a file stream through a transform stream that selectively decompresses files from a
    <kbd>.tgz</kbd> archive, turning them into <{img}> elements as the user scrolls through an image gallery.
  <li> Image decoding: piping an HTTP response stream through a transform stream that decodes bytes into bitmap data,
    and then through another transform that translates bitmaps into PNGs. If installed inside the
    {{ServiceWorkerGlobalScope/fetch}} hook of a service worker, this would allow developers to
    transparently polyfill new image formats. [[SERVICE-WORKERS]]
</ul>

Web developers can also use the APIs described here to create their own streams, with the same APIs as those provided by
the platform. Other developers can then transparently compose platform-provided streams with those supplied by
libraries. In this way, the APIs described here provide unifying abstraction for all streams, encouraging an
ecosystem to grow around these shared and composable interfaces.

</div>

<h2 id="model">Model</h2>

A <dfn export>chunk</dfn> is a single piece of data that is written to or read from a stream. It can be of any type;
streams can even contain chunks of different types. A chunk will often not be the most atomic unit of data for a given
stream; for example a byte stream might contain chunks consisting of 16 KiB {{Uint8Array}}s, instead of single bytes.

<h3 id="rs-model">Readable streams</h3>

A <dfn export>readable stream</dfn> represents a source of data, from which you can read. In other words, data comes
<em>out</em> of a readable stream. Concretely, a readable stream is an instance of the {{ReadableStream}} class.

Although a readable stream can be created with arbitrary behavior, most readable streams wrap a lower-level I/O source,
called the <dfn>underlying source</dfn>. There are two types of underlying source: push sources and pull sources.

<dfn lt="push source">Push sources</dfn> push data at you, whether or not you are listening for it. They may also
provide a mechanism for pausing and resuming the flow of data. An example push source is a TCP socket, where data is
constantly being pushed from the OS level, at a rate that can be controlled by changing the TCP window size.

<dfn lt="pull source">Pull sources</dfn> require you to request data from them. The data may be available
synchronously, e.g. if it is held by the operating system's in-memory buffers, or asynchronously, e.g. if it has to be
read from disk. An example pull source is a file handle, where you seek to specific locations and read specific amounts.

Readable streams are designed to wrap both types of sources behind a single, unified interface. For web
developer–created streams, the implementation details of a source are provided by <a href="#underlying-source-api">an
object with certain methods and properties</a> that is passed to the {{ReadableStream()}} constructor.

<a>Chunks</a> are enqueued into the stream by the stream's <a>underlying source</a>. They can then be read one at a
time via the stream's public interface, in particular by using a <a>readable stream reader</a> acquired using the
stream's {{ReadableStream/getReader()}} method.

Code that reads from a readable stream using its public interface is known as a <dfn>consumer</dfn>.

Consumers also have the ability to <dfn lt="cancel a readable stream">cancel</dfn> a readable stream, using its
{{ReadableStream/cancel()}} method. This indicates that the consumer has lost interest in the stream, and will
immediately close the stream, throw away any queued <a>chunks</a>, and execute any cancellation mechanism of the
<a>underlying source</a>.

Consumers can also <dfn lt="tee a readable stream">tee</dfn> a readable stream using its {{ReadableStream/tee()}}
method. This will <a lt="locked to a reader">lock</a> the stream, making it no longer directly usable; however, it will
create two new streams, called <dfn lt="branches of a readable stream tee">branches</dfn>, which can be consumed
independently.

For streams representing bytes, an extended version of the <a>readable stream</a> is provided to handle bytes
efficiently, in particular by minimizing copies. The <a>underlying source</a> for such a readable stream is called
an <dfn>underlying byte source</dfn>. A readable stream whose underlying source is an underlying byte source is
sometimes called a <dfn>readable byte stream</dfn>. Consumers of a readable byte stream can acquire a <a>BYOB reader</a>
using the stream's {{ReadableStream/getReader()}} method.

<h3 id="ws-model">Writable streams</h3>

A <dfn export>writable stream</dfn> represents a destination for data, into which you can write. In other words, data
goes <em>in</em> to a writable stream. Concretely, a writable stream is an instance of the {{WritableStream}} class.

Analogously to readable streams, most writable streams wrap a lower-level I/O sink, called the
<dfn>underlying sink</dfn>. Writable streams work to abstract away some of the complexity of the underlying sink, by
queuing subsequent writes and only delivering them to the underlying sink one by one.

<a>Chunks</a> are written to the stream via its public interface, and are passed one at a time to the stream's
<a>underlying sink</a>. For web developer-created streams, the implementation details of the sink are provided by <a
href="#underlying-sink-api">an object with certain methods</a> that is passed to the {{WritableStream()}} constructor.

Code that writes into a writable stream using its public interface is known as a <dfn>producer</dfn>.

Producers also have the ability to <dfn lt="abort a writable stream">abort</dfn> a writable stream, using its
{{WritableStream/abort()}} method. This indicates that the producer believes something has gone wrong, and that future
writes should be discontinued. It puts the stream in an errored state, even without a signal from the <a>underlying
sink</a>, and it discards all writes in the stream's <a>internal queue</a>.

<h3 id="ts-model">Transform streams</h3>

A <dfn export>transform stream</dfn> consists of a pair of streams: a <a>writable stream</a>, known as its <dfn
export>writable side</dfn>, and a <a>readable stream</a>, known as its <dfn export>readable side</dfn>. In a manner
specific to the transform stream in question, writes to the writable side result in new data being made available for
reading from the readable side.

Concretely, any object with a <code>writable</code> property and a <code>readable</code> property can serve as a
transform stream. However, the standard {{TransformStream}} class makes it much easier to create such a pair that is
properly entangled. It wraps a <dfn>transformer</dfn>, which defines algorithms for the specific transformation to be
performed. For web developer–created streams, the implementation details of a transformer are provided by <a
href="#transformer-api">an object with certain methods and properties</a> that is passed to the {{TransformStream()}} constructor.

An <dfn export>identity transform stream</dfn> is a type of transform stream which forwards all <a>chunks</a> written
to its <a>writable side</a> to its <a>readable side</a>, without any changes. This can be useful in <a
href="#example-transform-identity">a variety of scenarios</a>. By default, the {{TransformStream}} constructor will
create an identity transform stream, when no {{transformer/transform()}} method is present on the <a>transformer</a>
object.

Some examples of potential transform streams include:

<ul>
  <li>A GZIP compressor, to which uncompressed bytes are written and from which compressed bytes are read;</li>
  <li>A video decoder, to which encoded bytes are written and from which uncompressed video frames are read;</li>
  <li>A text decoder, to which bytes are written and from which strings are read;</li>
  <li>A CSV-to-JSON converter, to which strings representing lines of a CSV file are written and from which
    corresponding JavaScript objects are read.
</ul>

<h3 id="pipe-chains">Pipe chains and backpressure</h3>

Streams are primarily used by <dfn>piping</dfn> them to each other. A readable stream can be piped directly to a
writable stream, using its {{ReadableStream/pipeTo()}} method, or it can be piped through one or more transform streams
first, using its {{ReadableStream/pipeThrough()}} method.

A set of streams piped together in this way is referred to as a <dfn>pipe chain</dfn>. In a pipe chain, the
<dfn>original source</dfn> is the <a>underlying source</a> of the first readable stream in the chain; the
<dfn>ultimate sink</dfn> is the <a>underlying sink</a> of the final writable stream in the chain.

Once a pipe chain is constructed, it will propagate signals regarding how fast <a>chunks</a> should flow through it. If
any step in the chain cannot yet accept chunks, it propagates a signal backwards through the pipe chain, until
eventually the original source is told to stop producing chunks so fast. This process of normalizing flow from the
original source according to how fast the chain can process chunks is called <dfn>backpressure</dfn>.

Concretely, the <a>original source</a> is given the
{{ReadableStreamDefaultController/desiredSize|controller.desiredSize}} (or
{{ReadableByteStreamController/desiredSize|byteController.desiredSize}}) value, and can then adjust its rate of data
flow accordingly. This value is derived from the {{WritableStreamDefaultWriter/desiredSize|writer.desiredSize}}
corresponding to the <a>ultimate sink</a>, which gets updated as the ultimate sink finishes writing <a>chunks</a>. The
{{ReadableStream/pipeTo()}} method used to construct the chain automatically ensures this information propagates back
through the <a>pipe chain</a>.

When <a lt="tee a readable stream">teeing</a> a readable stream, the <a>backpressure</a> signals from its two
<a lt="branches of a readable stream tee">branches</a> will aggregate, such that if neither branch is read from, a
backpressure signal will be sent to the <a>underlying source</a> of the original stream.

Piping <a>locks</a> the readable and writable streams, preventing them from being manipulated for the duration of the
pipe operation. This allows the implementation to perform important optimizations, such as directly shuttling data from
the underlying source to the underlying sink while bypassing many of the intermediate queues.

<h3 id="queuing-strategies">Internal queues and queuing strategies</h3>

Both readable and writable streams maintain <dfn>internal queues</dfn>, which they use for similar purposes. In the
case of a readable stream, the internal queue contains <a>chunks</a> that have been enqueued by the <a>underlying
source</a>, but not yet read by the consumer. In the case of a writable stream, the internal queue contains
<a>chunks</a> which have been written to the stream by the producer, but not yet processed and acknowledged by the
<a>underlying sink</a>.

A <dfn>queuing strategy</dfn> is an object that determines how a stream should signal <a>backpressure</a> based on
the state of its <a>internal queue</a>. The queuing strategy assigns a size to each <a>chunk</a>, and compares the
total size of all chunks in the queue to a specified number, known as the <dfn>high water mark</dfn>. The resulting
difference, high water mark minus total size, is used to determine the
<dfn lt="desired size to fill a stream's internal queue">desired size to fill the stream's queue</dfn>.

For readable streams, an underlying source can use this desired size as a backpressure signal, slowing down chunk
generation so as to try to keep the desired size above or at zero. For writable streams, a producer can behave
similarly, avoiding writes that would cause the desired size to go negative.

<a href="#qs-api">Concretely</a>, a queuing strategy for web developer–created streams is given by any JavaScript object
with a <code><a for="queuing strategy">highWaterMark</a></code> property. For byte streams the <code><a for="queuing
strategy">highWaterMark</a></code> always has units of bytes. For other streams the default unit is <a>chunks</a>, but a
<code><a for="queuing strategy">size()</a></code> function can be included in the strategy object which returns the size
for a given chunk. This permits the <code><a for="queuing strategy">highWaterMark</a></code> to be specified in
arbitrary floating-point units.
<!-- TODO: https://github.com/whatwg/streams/issues/427 -->

<div class="example" id="example-simple-queuing-strategy">
  A simple example of a queuing strategy would be one that assigns a size of one to each chunk, and has a high water
  mark of three. This would mean that up to three chunks could be enqueued in a readable stream, or three chunks
  written to a writable stream, before the streams are considered to be applying backpressure.

  In JavaScript, such a strategy could be written manually as <code>{ highWaterMark: 3, size() { return 1; }}</code>,
  or using the built-in {{CountQueuingStrategy}} class, as <code>new CountQueuingStrategy({ highWaterMark: 3 })</code>.
</div>

<h3 id="locking">Locking</h3>

A <dfn lt="reader|readable stream reader">readable stream reader</dfn>, or simply reader, is an object that allows
direct reading of <a>chunks</a> from a <a>readable stream</a>. Without a reader, a <a>consumer</a> can only perform
high-level operations on the readable stream: <a lt="cancel a readable stream">canceling</a> the stream, or
<a>piping</a> the readable stream to a writable stream. A reader is acquired via the stream's
{{ReadableStream/getReader()}} method.

A <a>readable byte stream</a> has the ability to vend two types of readers: <dfn>default readers</dfn> and <dfn>BYOB
readers</dfn>. BYOB ("bring your own buffer") readers allow reading into a developer-supplied buffer, thus minimizing
copies. A non-byte readable stream can only vend default readers. Default readers are instances of the
{{ReadableStreamDefaultReader}} class, while BYOB readers are instances of {{ReadableStreamBYOBReader}}.

Similarly, a <dfn lt="writer|writable stream writer">writable stream writer</dfn>, or simply writer, is an object that
allows direct writing of <a>chunks</a> to a <a>writable stream</a>. Without a writer, a <a>producer</a> can only perform
the high-level operations of <a lt="abort a writable stream">aborting</a> the stream or <a>piping</a> a readable stream
to the writable stream. Writers are represented by the {{WritableStreamDefaultWriter}} class.

<p class="note">Under the covers, these high-level operations actually use a reader or writer themselves.</p>

A given readable or writable stream only has at most one reader or writer at a time. We say in this case the stream is
<dfn lt="lock|locked to a reader|locked to a writer">locked</dfn>, and that the reader or writer is <dfn
lt="active|active reader|active writer">active</dfn>. This state can be determined using the
{{ReadableStream/locked|readableStream.locked}} or {{WritableStream/locked|writableStream.locked}} properties.

A reader or writer also has the capability to <dfn lt="release a lock|release a read lock|release a write lock">release
its lock</dfn>, which makes it no longer active, and allows further readers or writers to be acquired. This is done via
the {{ReadableStreamDefaultReader/releaseLock()|defaultReader.releaseLock()}},
{{ReadableStreamBYOBReader/releaseLock()|byobReader.releaseLock()}}, or
{{WritableStreamDefaultWriter/releaseLock()|writer.releaseLock()}} method, as appropriate.

<h2 id="rs">Readable streams</h2>

<h3 id="rs-intro">Using readable streams</h3>

<div class="example" id="example-basic-pipe-to">
  The simplest way to consume a readable stream is to simply <a lt="piping">pipe</a> it to a <a>writable stream</a>.
  This ensures that <a>backpressure</a> is respected, and any errors (either writing or reading) are propagated through
  the chain:

  <pre><code class="lang-javascript">
    readableStream.pipeTo(writableStream)
      .then(() => console.log("All data successfully written!"))
      .catch(e => console.error("Something went wrong!", e));
  </code></pre>
</div>

<div class="example" id="example-pipe-as-chunks-receiver">
  If you simply want to be alerted of each new chunk from a readable stream, you can <a lt="piping">pipe</a> it to a
  new <a>writable stream</a> that you custom-create for that purpose:

  <pre><code class="lang-javascript">
    readableStream.pipeTo(new WritableStream({
      write(chunk) {
        console.log("Chunk received", chunk);
      },
      close() {
        console.log("All data successfully read!");
      },
      abort(e) {
        console.error("Something went wrong!", e);
      }
    }));
  </code></pre>

  By returning promises from your {{underlying sink/write()}} implementation, you can signal <a>backpressure</a> to the
  readable stream.
</div>

<div class="example" id="example-manual-read">
  Although readable streams will usually be used by piping them to a writable stream, you can also read them directly by
  acquiring a <a>reader</a> and using its <code>read()</code> method to get successive chunks. For example, this code
  logs the next <a>chunk</a> in the stream, if available:

  <pre><code class="lang-javascript">
    const reader = readableStream.getReader();

    reader.read().then(
      ({ value, done }) => {
        if (done) {
          console.log("The stream was already closed!");
        } else {
          console.log(value);
        }
      },
      e => console.error("The stream became errored and cannot be read from!", e)
    );
  </code></pre>

  This more manual method of reading a stream is mainly useful for library authors building new high-level operations
  on streams, beyond the provided ones of <a>piping</a> and <a lt="tee a readable stream">teeing</a>.
</div>

<div class="example" id="example-manual-read-bytes">
  The above example showed using the readable stream's <a>default reader</a>. If the stream is a <a>readable byte
  stream</a>, you can also acquire a <a>BYOB reader</a> for it, which allows more precise control over buffer
  allocation in order to avoid copies. For example, this code reads the first 1024 bytes from the stream into a single
  memory buffer:

  <pre><code class="lang-javascript">
    const reader = readableStream.getReader({ mode: "byob" });

    let startingAB = new ArrayBuffer(1024);
    readInto(startingAB)
      .then(buffer => console.log("The first 1024 bytes:", buffer))
      .catch(e => console.error("Something went wrong!", e));

    function readInto(buffer, offset = 0) {
      if (offset === buffer.byteLength) {
        return Promise.resolve(buffer);
      }

      const view = new Uint8Array(buffer, offset, buffer.byteLength - offset);
      return reader.read(view).then(newView => {
        return readInto(newView.buffer, offset + newView.byteLength);
      });
    }
  </code></pre>

  An important thing to note here is that the final <code>buffer</code> value is different from the
  <code>startingAB</code>, but it (and all intermediate buffers) shares the same backing memory allocation. At each
  step, the buffer is <a href="#transfer-array-buffer">transferred</a> to a new {{ArrayBuffer}} object. The
  <code>newView</code> is a new {{Uint8Array}}, with that {{ArrayBuffer}} object as its <code>buffer</code> property,
  the offset that bytes were written to as its <code>byteOffset</code> property, and the number of bytes that were
  written as its <code>byteLength</code> property.
</div>

<h3 id="rs-class" interface lt="ReadableStream">Class <code>ReadableStream</code></h3>

The {{ReadableStream}} class is a concrete instance of the general <a>readable stream</a> concept. It is
adaptable to any <a>chunk</a> type, and maintains an internal queue to keep track of data supplied by the <a>underlying
source</a> but not yet read by any consumer.

<h4 id="rs-class-definition">Class definition</h4>

<em>This section is non-normative.</em>

If one were to write the {{ReadableStream}} class in something close to the syntax of [[!ECMASCRIPT]], it would look
like

<pre><code class="lang-javascript">
  class ReadableStream {
    <a href="#rs-constructor">constructor</a>(<a href="#underlying-source-api">underlyingSource</a> = {}, <a href="#qs-api">strategy</a> = {})

    get <a href="#rs-locked">locked</a>()

    <a href="#rs-cancel">cancel</a>(reason)
    <a href="#rs-get-iterator">getIterator</a>({ preventCancel } = {})
    <a href="#rs-get-reader">getReader</a>({ mode } = {})
    <a href="#rs-pipe-through">pipeThrough</a>({ writable, readable },
                { preventClose, preventAbort, preventCancel, signal } = {})
    <a href="#rs-pipe-to">pipeTo</a>(dest, { preventClose, preventAbort, preventCancel, signal } = {})
    <a href="#rs-tee">tee</a>()

    <a href="#rs-asynciterator">[@@asyncIterator]</a>({ preventCancel } = {})
  }
</code></pre>

<h4 id="rs-internal-slots">Internal slots</h4>

Instances of {{ReadableStream}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[disturbed]]
    <td class="non-normative">A boolean flag set to <emu-val>true</emu-val> when the stream has been read from or
      canceled
  </tr>
  <tr>
    <td>\[[readableStreamController]]
    <td class="non-normative">A {{ReadableStreamDefaultController}} or {{ReadableByteStreamController}} created with
    the ability to control the state and queue of this stream; also used for the <a
    href="#is-readable-stream">IsReadableStream</a> brand check
  </tr>
  <tr>
    <td>\[[reader]]
    <td class="non-normative">A {{ReadableStreamDefaultReader}} or {{ReadableStreamBYOBReader}} instance, if the stream
    is <a>locked to a reader</a>, or <emu-val>undefined</emu-val> if it is not
  </tr>
  <tr>
    <td>\[[state]]
    <td class="non-normative">A string containing the stream's current state, used internally; one of
      <code>"readable"</code>, <code>"closed"</code>, or <code>"errored"</code>
  </tr>
  <tr>
    <td>\[[storedError]]
    <td class="non-normative">A value indicating how the stream failed, to be given as a failure reason or exception
      when trying to operate on an errored stream
  </tr>
</table>

<h4 id="rs-constructor" constructor for="ReadableStream" lt="ReadableStream(underlyingSource, strategy)">new
ReadableStream(<var>underlyingSource</var> = {}, <var>strategy</var> = {})</h4>

<div class="note">
  The <code>underlyingSource</code> argument represents the <a>underlying source</a>, as described in
  [[#underlying-source-api]].

  The <code>strategy</code> argument represents the stream's <a>queuing strategy</a>, as described in [[#qs-api]]. If it
  is not provided, the default behavior will be the same as a {{CountQueuingStrategy}} with a <a>high water mark</a>
  of 1.
</div>

<emu-alg>
  1. Perform ! InitializeReadableStream(*this*).
  1. Let _size_ be ? GetV(_strategy_, `"size"`).
  1. Let _highWaterMark_ be ? GetV(_strategy_, `"highWaterMark"`).
  1. Let _type_ be ? GetV(_underlyingSource_, `"type"`).
  1. Let _typeString_ be ? ToString(_type_).
  1. If _typeString_ is `"bytes"`,
    1. If _size_ is not *undefined*, throw a *RangeError* exception.
    1. If _highWaterMark_ is *undefined*, let _highWaterMark_ be *0*.
    1. Set _highWaterMark_ to ? ValidateAndNormalizeHighWaterMark(_highWaterMark_).
    1. Perform ? SetUpReadableByteStreamControllerFromUnderlyingSource(*this*, _underlyingSource_, _highWaterMark_).
  1. Otherwise, if _type_ is *undefined*,
    1. Let _sizeAlgorithm_ be ? MakeSizeAlgorithmFromSizeFunction(_size_).
    1. If _highWaterMark_ is *undefined*, let _highWaterMark_ be *1*.
    1. Set _highWaterMark_ to ? ValidateAndNormalizeHighWaterMark(_highWaterMark_).
    1. Perform ? SetUpReadableStreamDefaultControllerFromUnderlyingSource(*this*, _underlyingSource_, _highWaterMark_,
       _sizeAlgorithm_).
  1. Otherwise, throw a *RangeError* exception.
</emu-alg>

<h4 id="underlying-source-api">Underlying source API</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

The {{ReadableStream()}} constructor accepts as its first argument a JavaScript object representing the <a>underlying
source</a>. Such objects can contain any of the following properties:

<dl>
  <dt><dfn method for="underlying source">start(<var>controller</var>)</dfn></dt>
  <dd>
    <p>A function that is called immediately during creation of the {{ReadableStream}}.</p>

    <p>Typically this is used adapt a <a>push source</a> by setting up relevant event listeners, as in the example of
    [[#example-rs-push-no-backpressure]], or to acquire access to a <a>pull source</a>, as in [[#example-rs-pull]].</p>

    <p>If this setup process is asynchronous, it can return a promise to signal success or failure; a rejected promise
    will error the stream. Any thrown exceptions will be re-thrown by the {{ReadableStream()}} constructor.</p>
  </dd>

  <dt><dfn method for="underlying source">pull(<var>controller</var>)</dfn></dt>
  <dd>
    <p>A function that is called whenever the stream's <a>internal queue</a> of chunks becomes not full, i.e. whenever
    the queue's <a lt="desired size to fill a stream's internal queue">desired size</a> becomes positive. Generally, it
    will be called repeatedly until the queue reaches its <a>high water mark</a> (i.e. until the <a lt="desired size to
    fill a stream's internal queue">desired size</a> becomes non-positive).</p>

    <p>For <a>push sources</a>, this can be used to resume a paused flow, as in [[#example-rs-push-backpressure]]. For
    <a>pull sources</a>, it is used to acquire new <a>chunks</a> to enqueue into the stream, as in
    [[#example-rs-pull]].</p>

    <p>This function will not be called until {{underlying source/start()}} successfully completes. Additionally, it
    will only be called repeatedly if it enqueues at least one chunk or fulfills a BYOB request; a no-op
    {{underlying source/pull()}} implementation will not be continually called.</p>

    <p>If the function returns a promise, then it will not be called again until that promise fulfills. (If the
    promise rejects, the stream will become errored.) This is mainly used in the case of pull sources, where the
    promise returned represents the process of acquiring a new chunk. Throwing an exception is treated the same as
    returning a rejected promise.</p>
  </dd>

  <dt><dfn method for="underlying source">cancel(<var>reason</var>)</dfn></dt>
  <dd>
    <p>A function that is called whenever the <a>consumer</a> <a lt="cancel a readable stream">cancels</a> the stream,
    via {{ReadableStream/cancel()|stream.cancel()}}, {{ReadableStreamDefaultReader/cancel()|defaultReader.cancel()}}, or
    {{ReadableStreamBYOBReader/cancel()|byobReader.cancel()}}. It takes as its argument the same value as was passed to
    those methods by the consumer.</p>

    <p>Readable streams can additionally be canceled under certain conditions during <a>piping</a>; see the definition
    of the {{ReadableStream/pipeTo()}} method for more details.</p>

    <p>For all streams, this is generally used to release access to the underlying resource; see for example
    [[#example-rs-push-no-backpressure]].</p>

    <p>If the shutdown process is asynchronous, it can return a promise to signal success or failure; the result will be
    communicated via the return value of the <code>cancel()</code> method that was called. Additionally, a rejected
    promise will error the stream, instead of letting it close. Throwing an exception is treated the same as returning
    a rejected promise.</p>
  </dd>

  <dt><dfn for="underlying source"><code>type</code></dfn> (byte streams only)</dt>
  <dd>
    <p>Can be set to <code>"bytes"</code> to signal that the constructed {{ReadableStream}} is a <a>readable byte
    stream</a>. This ensures that the resulting {{ReadableStream}} will successfully be able to vend <a>BYOB readers</a>
    via its {{ReadableStream/getReader()}} method. It also affects the <code>controller</code> argument passed to the
    {{underlying source/start()}} and {{underlying source/pull()}} methods; see below.</p>

    <p>For an example of how to set up a readable byte stream, including using the different controller interface, see
    [[#example-rbs-push]].</p>

    <p>Setting any value other than <code>"bytes"</code> or <emu-val>undefined</emu-val> will cause the
    {{ReadableStream()}} constructor to throw an exception.</p>
  </dd>

  <dt><dfn for="underlying source"><code>autoAllocateChunkSize</code></dfn> (byte streams only)</dt>
  <dd>
    <p>Can be set to a positive integer to cause the implementation to automatically allocate buffers for the
    underlying source code to write into. In this case, when a <a>consumer</a> is using a <a>default reader</a>, the
    stream implementation will automatically allocate an {{ArrayBuffer}} of the given size, so that
    {{ReadableByteStreamController/byobRequest|controller.byobRequest}} is always present, as if the consumer was using
    a <a>BYOB reader</a>.</p>

    <p>This is generally used to cut down on the amount of code needed to handle consumers that use default readers, as
    can be seen by comparing [[#example-rbs-push]] without auto-allocation to [[#example-rbs-pull]] with
    auto-allocation.</p>
  </dd>
</dl>

The type of the <code>controller</code> argument passed to the {{underlying source/start()}} and
{{underlying source/pull()}} methods depends on the value of the <code><a for="underlying source">type</a></code>
option. If <code><a for="underlying source">type</a></code> is set to <code>undefined</code> (including via omission),
<code>controller</code> will be a {{ReadableStreamDefaultController}}. If it's set to <code>"bytes"</code>,
<code>controller</code> will be a {{ReadableByteStreamController}}.

</div>

<h4 id="rs-prototype">Properties of the {{ReadableStream}} prototype</h4>

<h5 id="rs-locked" attribute for="ReadableStream" lt="locked">get locked</h5>

<div class="note">
  The <code>locked</code> getter returns whether or not the readable stream is <a>locked to a reader</a>.
</div>

<emu-alg>
  1. If ! IsReadableStream(*this*) is *false*, throw a *TypeError* exception.
  1. Return ! IsReadableStreamLocked(*this*).
</emu-alg>

<h5 id="rs-cancel" method for="ReadableStream">cancel(<var>reason</var>)</h5>

<div class="note">
  The <code>cancel</code> method <a lt="cancel a readable stream">cancels</a> the stream, signaling a loss of interest
  in the stream by a consumer. The supplied <code>reason</code> argument will be given to the underlying source's
  {{underlying source/cancel()}} method, which might or might not use it.
</div>

<emu-alg>
  1. If ! IsReadableStream(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If ! IsReadableStreamLocked(*this*) is *true*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return ! ReadableStreamCancel(*this*, _reason_).
</emu-alg>

<h5 id="rs-get-iterator" method for="ReadableStream">getIterator({ <var>preventCancel</var> } = {})</h5>

<div class="note">
  The <code>getIterator</code> method returns an async iterator which can be used to consume the stream. The
  {{ReadableStreamAsyncIteratorPrototype/return()}} method of this iterator object will, by default,
  <a lt="cancel a readable stream">cancel</a> the stream; it will also release the reader.
</div>

<emu-alg>
  1. If ! IsReadableStream(*this*) is *false*, throw a *TypeError* exception.
  1. Let _reader_ be ? AcquireReadableStreamDefaultReader(*this*).
  1. Let _iterator_ be ! ObjectCreate(`<a idl>ReadableStreamAsyncIteratorPrototype</a>`).
  1. Set _iterator_.[[asyncIteratorReader]] to _reader_.
  1. Set _iterator_.[[preventCancel]] to ! ToBoolean(_preventCancel_).
  1. Return _iterator_.
</emu-alg>

<h5 id="rs-get-reader" method for="ReadableStream">getReader({ <var ignore>mode</var> } = {})</h5>

<div class="note">
  The <code>getReader</code> method creates a reader of the type specified by the <code>mode</code> option and <a
  lt="locked to a reader">locks</a> the stream to the new reader. While the stream is locked, no other reader can be
  acquired until this one is <a lt="release a read lock">released</a>.

  This functionality is especially useful for creating abstractions that desire the ability to consume a stream in its
  entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours or cancel
  the stream, which would interfere with your abstraction.

  When <code>mode</code> is <emu-val>undefined</emu-val>, the method creates a <a>default reader</a> (an instance of
  {{ReadableStreamDefaultReader}}). The reader provides the ability to directly read individual <a>chunks</a> from the
  stream via the reader's {{ReadableStreamDefaultReader/read()}} method.

  When <code>mode</code> is <code>"byob"</code>, the <code>getReader</code> method creates a <a>BYOB reader</a> (an
  instance of {{ReadableStreamBYOBReader}}). This feature only works on <a>readable byte streams</a>, i.e. streams which
  were constructed specifically with the ability to handle "bring your own buffer" reading. The reader provides the
  ability to directly read individual <a>chunks</a> from the stream via the reader's {{ReadableStreamBYOBReader/read()}}
  method, into developer-supplied buffers, allowing more precise control over allocation.
</div>

<emu-alg>
  1. If ! IsReadableStream(*this*) is *false*, throw a *TypeError* exception.
  1. If _mode_ is *undefined*, return ? AcquireReadableStreamDefaultReader(*this*, *true*).
  1. Set _mode_ to ? ToString(_mode_).
  1. If _mode_ is `"byob"`, return ? AcquireReadableStreamBYOBReader(*this*, *true*).
  1. Throw a *RangeError* exception.
</emu-alg>

<div class="example" id="example-read-all-chunks">
  An example of an abstraction that might benefit from using a reader is a function like the following, which is
  designed to read an entire readable stream into memory as an array of <a>chunks</a>.

  <pre><code class="lang-javascript">
    function readAllChunks(readableStream) {
      const reader = readableStream.getReader();
      const chunks = [];

      return pump();

      function pump() {
        return reader.read().then(({ value, done }) => {
          if (done) {
            return chunks;
          }

          chunks.push(value);
          return pump();
        });
      }
    }
  </code></pre>

  Note how the first thing it does is obtain a reader, and from then on it uses the reader exclusively. This ensures
  that no other consumer can interfere with the stream, either by reading chunks or by
  <a lt="cancel a readable stream">canceling</a> the stream.
</div>

<h5 id="rs-pipe-through" method for="ReadableStream" lt="pipeThrough(transform, options)">pipeThrough({
<var ignore>writable</var>, <var ignore>readable</var> }, { <var>preventClose</var>, <var>preventAbort</var>,
<var>preventCancel</var>, <var>signal</var> } = {})</h5>

<div class="note">
  The <code>pipeThrough</code> method provides a convenient, chainable way of <a>piping</a> this <a>readable stream</a>
  through a <a>transform stream</a> (or any other <code>{ writable, readable }</code> pair). It simply pipes the stream
  into the writable side of the supplied pair, and returns the readable side for further use.

  Piping a stream will <a lt="locked to a reader">lock</a> it for the duration of the pipe, preventing any other
  consumer from acquiring a reader.
</div>

<emu-alg>
  1. If ! IsReadableStream(*this*) is *false*, throw a *TypeError* exception.
  1. If ! IsWritableStream(_writable_) is *false*, throw a *TypeError* exception.
  1. If ! IsReadableStream(_readable_) is *false*, throw a *TypeError* exception.
  1. Set _preventClose_ to ! ToBoolean(_preventClose_), set _preventAbort_ to ! ToBoolean(_preventAbort_), and set
     _preventCancel_ to ! ToBoolean(_preventCancel_).
  1. If _signal_ is not *undefined*, and _signal_ is not an instance of the `<a idl>AbortSignal</a>` interface, throw a
     *TypeError* exception.
  1. If ! IsReadableStreamLocked(*this*) is *true*, throw a *TypeError* exception.
  1. If ! IsWritableStreamLocked(_writable_) is *true*, throw a *TypeError* exception.
  1. Let _promise_ be ! ReadableStreamPipeTo(*this*, _writable_, _preventClose_, _preventAbort_, _preventCancel_,
     _signal_).
  1. Set _promise_.[[PromiseIsHandled]] to *true*.
  1. Return _readable_.
</emu-alg>

<div class="example" id="example-pipe-chain">
  A typical example of constructing <a>pipe chain</a> using {{ReadableStream/pipeThrough(transform, options)}} would
  look like

  <pre><code class="lang-javascript">
    httpResponseBody
      .pipeThrough(decompressorTransform)
      .pipeThrough(ignoreNonImageFilesTransform)
      .pipeTo(mediaGallery);
  </code></pre>
</div>

<h5 id="rs-pipe-to" method for="ReadableStream" lt="pipeTo(dest, options)">pipeTo(<var>dest</var>,
{ <var>preventClose</var>, <var>preventAbort</var>, <var>preventCancel</var>, <var>signal</var> } = {})</h5>

<div class="note">
  The <code>pipeTo</code> method <a lt="piping">pipes</a> this <a>readable stream</a> to a given <a>writable
  stream</a>. The way in which the piping process behaves under various error conditions can be customized with a
  number of passed options. It returns a promise that fulfills when the piping process completes successfully, or
  rejects if any errors were encountered.

  Piping a stream will <a lt="locked to a reader">lock</a> it for the duration of the pipe, preventing any other
  consumer from acquiring a reader.

  Errors and closures of the source and destination streams propagate as follows:

  <ul>
    <li><p>An error in the source <a>readable stream</a> will <a lt="abort a writable stream">abort</a> the destination
    <a>writable stream</a>, unless <code>preventAbort</code> is truthy. The returned promise will be rejected with the
    source's error, or with any error that occurs during aborting the destination.</p></li>

    <li><p>An error in the destination <a>writable stream</a> will <a lt="cancel a readable stream">cancel</a> the
    source <a>readable stream</a>, unless <code>preventCancel</code> is truthy. The returned promise will be rejected
    with the destination's error, or with any error that occurs during canceling the source.</p></li>

    <li><p>When the source <a>readable stream</a> closes, the destination <a>writable stream</a> will be closed, unless
    <code>preventClose</code> is true. The returned promise will be fulfilled once this process completes, unless an
    error is encountered while closing the destination, in which case it will be rejected with that error.</p></li>

    <li><p>If the destination <a>writable stream</a> starts out closed or closing, the source <a>readable stream</a>
    will be <a lt="cancel a readable stream">canceled</a>, unless <code>preventCancel</code> is true. The returned
    promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs
    during canceling the source.</p></li>
  </ul>

  The <code>signal</code> option can be set to an {{AbortSignal}} to allow aborting an ongoing pipe operation via the
  corresponding {{AbortController}}. In this case, the source <a>readable stream</a> will be <a lt="cancel a readable
  stream">canceled</a>, and the destination <a>writable stream</a> <a lt="abort a writable stream">aborted</a>, unless
  the respective options <code>preventCancel</code> or <code>preventAbort</code> are set.

</div>

<emu-alg>
  1. If ! IsReadableStream(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If ! IsWritableStream(_dest_) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Set _preventClose_ to ! ToBoolean(_preventClose_), set _preventAbort_ to ! ToBoolean(_preventAbort_), and set
     _preventCancel_ to ! ToBoolean(_preventCancel_).
  1. If _signal_ is not *undefined*, and _signal_ is not an instance of the `<a idl>AbortSignal</a>` interface, return
     <a>a promise rejected with</a> a *TypeError* exception.
  1. If ! IsReadableStreamLocked(*this*) is *true*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If ! IsWritableStreamLocked(_dest_) is *true*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return ! ReadableStreamPipeTo(*this*, _dest_, _preventClose_, _preventAbort_, _preventCancel_, _signal_).
</emu-alg>

<h5 id="rs-tee" method for="ReadableStream">tee()</h5>

<div class="note">
  The <code>tee</code> method <a lt="tee a readable stream">tees</a> this readable stream, returning a two-element
  array containing the two resulting branches as new {{ReadableStream}} instances.

  Teeing a stream will <a lt="locked to a reader">lock</a> it, preventing any other consumer from acquiring a reader.
  To <a lt="cancel a readable stream">cancel</a> the stream, cancel both of the resulting branches; a composite
  cancellation reason will then be propagated to the stream's <a>underlying source</a>.

  Note that the <a>chunks</a> seen in each branch will be the same object. If the chunks are not immutable, this could
  allow interference between the two branches.
</div>

<emu-alg>
  1. If ! IsReadableStream(*this*) is *false*, throw a *TypeError* exception.
  1. Let _branches_ be ? ReadableStreamTee(*this*, *false*).
  1. Return ! CreateArrayFromList(_branches_).
</emu-alg>

<div class="example" id="example-tee-and-pipe">
  Teeing a stream is most useful when you wish to let two independent consumers read from the stream in parallel,
  perhaps even at different speeds. For example, given a writable stream <code>cacheEntry</code> representing an
  on-disk file, and another writable stream <code>httpRequestBody</code> representing an upload to a remote server,
  you could pipe the same readable stream to both destinations at once:

  <pre><code class="lang-javascript">
    const [forLocal, forRemote] = readableStream.tee();

    Promise.all([
      forLocal.pipeTo(cacheEntry),
      forRemote.pipeTo(httpRequestBody)
    ])
    .then(() => console.log("Saved the stream to the cache and also uploaded it!"))
    .catch(e => console.error("Either caching or uploading failed: ", e));
  </code></pre>
</div>

<!-- Bikeshed doesn't let us mark this up correctly: https://github.com/tabatkins/bikeshed/issues/1344 -->
<h5 id="rs-asynciterator" iterator for="ReadableStream">[@@asyncIterator]({ <var>preventCancel</var> } = {})</h5>

<p class="note">
  The <code>@@asyncIterator</code> method is an alias of {{ReadableStream/getIterator()}}.
</p>

The initial value of the <code>@@asyncIterator</code> method is the same function object as the initial value of the
{{ReadableStream/getIterator()}} method.

<h3 id="rs-asynciterator-prototype" interface
lt="ReadableStreamAsyncIteratorPrototype">ReadableStreamAsyncIteratorPrototype</h3>

{{ReadableStreamAsyncIteratorPrototype}} is an ordinary object that is used by {{ReadableStream/getIterator()}} to
construct the objects it returns. Instances of {{ReadableStreamAsyncIteratorPrototype}} implement the {{AsyncIterator}}
abstract interface from the JavaScript specification. [[!ECMASCRIPT]]

The {{ReadableStreamAsyncIteratorPrototype}} object must have its \[[Prototype]] internal slot set to
{{%AsyncIteratorPrototype%}}.

<h4 id="default-reader-asynciterator-prototype-internal-slots">Internal slots</h4>

Objects created by {{ReadableStream/getIterator()}}, using {{ReadableStreamAsyncIteratorPrototype}} as their
prototype, are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[asyncIteratorReader]]
    <td class="non-normative">A {{ReadableStreamDefaultReader}} instance
  </tr>
  <tr>
    <td>\[[preventCancel]]
    <td class="non-normative">A boolean value indicating if the stream will be <a lt="cancel a readable
    stream">canceled</a> when the async iterator's {{ReadableStreamAsyncIteratorPrototype/return()}} method is called
  </tr>
</table>

<h4 id="rs-asynciterator-prototype-next" method for="ReadableStreamAsyncIteratorPrototype">next()</h4>

<emu-alg>
  1. If ! IsReadableStreamAsyncIterator(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Let _reader_ be *this*.[[asyncIteratorReader]].
  1. If _reader_.[[ownerReadableStream]] is *undefined*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return the result of <a>reacting</a> to ! ReadableStreamDefaultReaderRead(_reader_) with the following fulfillment
     steps given the argument _result_:
    1. Assert: Type(_result_) is Object.
    1. Let _done_ be ! Get(_result_, `"done"`).
    1. Assert: Type(_done_) is Boolean.
    1. If _done_ is *true*, perform ! ReadableStreamReaderGenericRelease(_reader_).
    1. Let _value_ be ! Get(_result_, `"value"`).
    1. Return ! ReadableStreamCreateReadResult(_value_, _done_, *true*).
</emu-alg>

<h4 id="rs-asynciterator-prototype-return" method
for="ReadableStreamAsyncIteratorPrototype">return( <var>value</var> )</h4>

<emu-alg>
  1. If ! IsReadableStreamAsyncIterator(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Let _reader_ be *this*.[[asyncIteratorReader]].
  1. If _reader_.[[ownerReadableStream]] is *undefined*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If _reader_.[[readRequests]] is not empty, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If *this*.[[preventCancel]] is *false*, then:
    1. Let _result_ be ! ReadableStreamReaderGenericCancel(_reader_, _value_).
    1. Perform ! ReadableStreamReaderGenericRelease(_reader_).
    1. Return the result of <a>reacting</a> to _result_ with a fulfillment step that returns !
    ReadableStreamCreateReadResult(_value_, *true*, *true*).
  1. Perform ! ReadableStreamReaderGenericRelease(_reader_).
  1. Return <a>a promise resolved with</a> ! ReadableStreamCreateReadResult(_value_, *true*, *true*).
</emu-alg>

<h3 id="rs-abstract-ops">General readable stream abstract operations</h3>

The following abstract operations, unlike most in this specification, are meant to be generally useful by other
specifications, instead of just being part of the implementation of this spec's classes.

<h4 id="acquire-readable-stream-byob-reader" aoid="AcquireReadableStreamBYOBReader"
throws>AcquireReadableStreamBYOBReader ( <var>stream</var>[, <var>forAuthorCode</var> ] )</h4>

This abstract operation is meant to be called from other specifications that may wish to acquire a <a>BYOB reader</a>
for a given stream.

<emu-alg>
  1. If _forAuthorCode_ was not passed, set it to *false*.
  1. Let _reader_ be ? Construct(`<a idl>ReadableStreamBYOBReader</a>`, « _stream_ »).
  1. Set _reader_.[[forAuthorCode]] to _forAuthorCode_.
  1. Return _reader_.
</emu-alg>

<h4 id="acquire-readable-stream-reader" aoid="AcquireReadableStreamDefaultReader" throws
export>AcquireReadableStreamDefaultReader ( <var>stream</var>[, <var>forAuthorCode</var> ] )</h4>

This abstract operation is meant to be called from other specifications that may wish to acquire a <a>default
reader</a> for a given stream.

<p class="note">Other specifications ought to leave <var>forAuthorCode</var> as its default value of
<emu-val>false</emu-val>, unless they are planning to directly expose the resulting <code>{ value, done }</code> object
to authors. See <a href="#rs-read-result-for-author-code">the note regarding ReadableStreamCreateReadResult</a> for more
information.</p>

<emu-alg>
  1. If _forAuthorCode_ was not passed, set it to *false*.
  1. Let _reader_ be ? Construct(`<a idl>ReadableStreamDefaultReader</a>`, « _stream_ »).
  1. Set _reader_.[[forAuthorCode]] to _forAuthorCode_.
  1. Return _reader_.
</emu-alg>

<h4 id="create-readable-stream" aoid="CreateReadableStream" throws export>CreateReadableStream (
<var>startAlgorithm</var>, <var>pullAlgorithm</var>, <var>cancelAlgorithm</var> [, <var>highWaterMark</var> [,
<var>sizeAlgorithm</var> ] ] )</h4>

This abstract operation is meant to be called from other specifications that wish to create {{ReadableStream}}
instances. The <var>pullAlgorithm</var> and <var>cancelAlgorithm</var> algorithms must return
promises; if supplied, <var>sizeAlgorithm</var> must be an algorithm accepting <a>chunk</a> objects and returning a
number; and if supplied, <var>highWaterMark</var> must be a non-negative, non-NaN number.

<p class="note">CreateReadableStream throws an exception if and only if the supplied <var>startAlgorithm</var>
throws.</p>

<emu-alg>
  1. If _highWaterMark_ was not passed, set it to *1*.
  1. If _sizeAlgorithm_ was not passed, set it to an algorithm that returns *1*.
  1. Assert: ! IsNonNegativeNumber(_highWaterMark_) is *true*.
  1. Let _stream_ be ObjectCreate(the original value of `<a idl>ReadableStream</a>`'s `prototype` property).
  1. Perform ! InitializeReadableStream(_stream_).
  1. Let _controller_ be ObjectCreate(the original value of `<a idl>ReadableStreamDefaultController</a>`'s `prototype`
     property).
  1. Perform ? SetUpReadableStreamDefaultController(_stream_, _controller_, _startAlgorithm_, _pullAlgorithm_,
     _cancelAlgorithm_, _highWaterMark_, _sizeAlgorithm_).
  1. Return _stream_.
</emu-alg>

<h4 id="create-readable-byte-stream" aoid="CreateReadableByteStream" throws export>CreateReadableByteStream (
<var>startAlgorithm</var>, <var>pullAlgorithm</var>, <var>cancelAlgorithm</var> [, <var>highWaterMark</var> [,
<var>autoAllocateChunkSize</var> ] ] )</h4>

This abstract operation is meant to be called from other specifications that wish to create {{ReadableStream}}
instances of type "bytes". The <var>pullAlgorithm</var> and <var>cancelAlgorithm</var> algorithms must return
promises; if supplied, <var>highWaterMark</var> must be a non-negative, non-NaN number, and if supplied,
<var>autoAllocateChunkSize</var> must be a positive integer.

<p class="note">CreateReadableByteStream throws an exception if and only if the supplied <var>startAlgorithm</var>
throws.</p>

<emu-alg>
  1. If _highWaterMark_ was not passed, set it to *0*.
  1. If _autoAllocateChunkSize_ was not passed, set it to *undefined*.
  1. Assert: ! IsNonNegativeNumber(_highWaterMark_) is *true*.
  1. If _autoAllocateChunkSize_ is not *undefined*,
    1. Assert: ! IsInteger(_autoAllocateChunkSize_) is *true*.
    1. Assert: _autoAllocateChunkSize_ is positive.
  1. Let _stream_ be ObjectCreate(the original value of `<a idl>ReadableStream</a>`'s `prototype` property).
  1. Perform ! InitializeReadableStream(_stream_).
  1. Let _controller_ be ObjectCreate(the original value of `<a idl>ReadableByteStreamController</a>`'s `prototype`
     property).
  1. Perform ? SetUpReadableByteStreamController(_stream_, _controller_, _startAlgorithm_, _pullAlgorithm_,
     _cancelAlgorithm_, _highWaterMark_, _autoAllocateChunkSize_).
  1. Return _stream_.
</emu-alg>

<h4 id="initialize-readable-stream" aoid="InitializeReadableStream" nothrow>InitializeReadableStream (
<var>stream</var> )</h4>

<emu-alg>
  1. Set _stream_.[[state]] to `"readable"`.
  1. Set _stream_.[[reader]] and _stream_.[[storedError]] to *undefined*.
  1. Set _stream_.[[disturbed]] to *false*.
</emu-alg>

<h4 id="is-readable-stream" aoid="IsReadableStream" nothrow>IsReadableStream ( <var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have a [[readableStreamController]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="is-readable-stream-disturbed" aoid="IsReadableStreamDisturbed" nothrow export>IsReadableStreamDisturbed (
<var>stream</var> )</h4>

This abstract operation is meant to be called from other specifications that may wish to query whether or not a
readable stream has ever been read from or canceled.

<emu-alg>
  1. Assert: ! IsReadableStream(_stream_) is *true*.
  1. Return _stream_.[[disturbed]].
</emu-alg>

<h4 id="is-readable-stream-locked" aoid="IsReadableStreamLocked" nothrow export>IsReadableStreamLocked (
<var>stream</var> )</h4>

This abstract operation is meant to be called from other specifications that may wish to query whether or not a
readable stream is <a>locked to a reader</a>.

<emu-alg>
  1. Assert: ! IsReadableStream(_stream_) is *true*.
  1. If _stream_.[[reader]] is *undefined*, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="is-readable-stream-asynciterator" aoid="IsReadableStreamAsyncIterator" nothrow
export>IsReadableStreamAsyncIterator ( <var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have a [[asyncIteratorReader]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="readable-stream-tee" aoid="ReadableStreamTee" throws export>ReadableStreamTee ( <var>stream</var>,
<var>cloneForBranch2</var> )</h4>

This abstract operation is meant to be called from other specifications that may wish to <a lt="tee a readable
stream">tee</a> a given readable stream.

The second argument, <var>cloneForBranch2</var>, governs whether or not the data from the original stream will be cloned
(using HTML's <a>serializable objects</a> framework) before appearing in the second of the returned branches. This is
useful for scenarios where both branches are to be consumed in such a way that they might otherwise interfere with each
other, such as by <a lt="transferable objects">transferring</a> their <a>chunks</a>. However, it does introduce a
noticeable asymmetry between the two branches, and limits the possible <a>chunks</a> to serializable ones. [[!HTML]]

<p class="note">In this standard ReadableStreamTee is always called with <var>cloneForBranch2</var> set to
<emu-val>false</emu-val>; other specifications pass <emu-val>true</emu-val>.</p>

<emu-alg>
  1. Assert: ! IsReadableStream(_stream_) is *true*.
  1. Assert: Type(_cloneForBranch2_) is Boolean.
  1. Let _reader_ be ? AcquireReadableStreamDefaultReader(_stream_).
  1. Let _reading_ be *false*.
  1. Let _canceled1_ be *false*.
  1. Let _canceled2_ be *false*.
  1. Let _reason1_ be *undefined*.
  1. Let _reason2_ be *undefined*.
  1. Let _branch1_ be *undefined*.
  1. Let _branch2_ be *undefined*.
  1. Let _cancelPromise_ be <a>a new promise</a>.
  1. Let _pullAlgorithm_ be the following steps:
    1. If _reading_ is *true*, return <a>a promise resolved with</a> *undefined*.
    1. Set _reading_ to *true*.
    1. Let _readPromise_ be the result of <a>reacting</a> to ! ReadableStreamDefaultReaderRead(_reader_) with the
       following fulfillment steps given the argument _result_:
      1. Set _reading_ to *false*.
      1. Assert: Type(_result_) is Object.
      1. Let _done_ be ! Get(_result_, `"done"`).
      1. Assert: Type(_done_) is Boolean.
      1. If _done_ is *true*,
        1. If _canceled1_ is *false*,
          1. Perform ! ReadableStreamDefaultControllerClose(_branch1_.[[readableStreamController]]).
        1. If _canceled2_ is *false*,
          1. Perform ! ReadableStreamDefaultControllerClose(_branch2_.[[readableStreamController]]).
        1. Return.
      1. Let _value_ be ! Get(_result_, `"value"`).
      1. Let _value1_ and _value2_ be _value_.
      1. If _canceled2_ is *false* and _cloneForBranch2_ is *true*, set _value2_ to ? <a
         abstract-op>StructuredDeserialize</a>(? <a abstract-op>StructuredSerialize</a>(_value2_), the current Realm
         Record).
      1. If _canceled1_ is *false*, perform ?
         ReadableStreamDefaultControllerEnqueue(_branch1_.[[readableStreamController]], _value1_).
      1. If _canceled2_ is *false*, perform ?
         ReadableStreamDefaultControllerEnqueue(_branch2_.[[readableStreamController]], _value2_).
    1. Set _readPromise_.[[PromiseIsHandled]] to *true*.
    1. Return <a>a promise resolved with</a> *undefined*.
  1. Let _cancel1Algorithm_ be the following steps, taking a _reason_ argument:
    1. Set _canceled1_ to *true*.
    1. Set _reason1_ to _reason_.
    1. If _canceled2_ is *true*,
      1. Let _compositeReason_ be ! CreateArrayFromList(« _reason1_, _reason2_ »).
      1. Let _cancelResult_ be ! ReadableStreamCancel(_stream_, _compositeReason_).
      1. <a>Resolve</a> _cancelPromise_ with _cancelResult_.
    1. Return _cancelPromise_.
  1. Let _cancel2Algorithm_ be the following steps, taking a _reason_ argument:
    1. Set _canceled2_ to *true*.
    1. Set _reason2_ to _reason_.
    1. If _canceled1_ is *true*,
      1. Let _compositeReason_ be ! CreateArrayFromList(« _reason1_, _reason2_ »).
      1. Let _cancelResult_ be ! ReadableStreamCancel(_stream_, _compositeReason_).
      1. <a>Resolve</a> _cancelPromise_ with _cancelResult_.
    1. Return _cancelPromise_.
  1. Let _startAlgorithm_ be an algorithm that returns *undefined*.
  1. Set _branch1_ to ! CreateReadableStream(_startAlgorithm_, _pullAlgorithm_, _cancel1Algorithm_).
  1. Set _branch2_ to ! CreateReadableStream(_startAlgorithm_, _pullAlgorithm_, _cancel2Algorithm_).
  1. <a>Upon rejection</a> of _reader_.[[closedPromise]] with reason _r_,
    1. Perform ! ReadableStreamDefaultControllerError(_branch1_.[[readableStreamController]], _r_).
    1. Perform ! ReadableStreamDefaultControllerError(_branch2_.[[readableStreamController]], _r_).
  1. Return « _branch1_, _branch2_ ».
</emu-alg>

<h4 id="readable-stream-pipe-to" aoid="ReadableStreamPipeTo" nothrow export>ReadableStreamPipeTo (
<var ignore>source</var>, <var>dest</var>, <var>preventClose</var>, <var>preventAbort</var>, <var>preventCancel</var>,
<var>signal</var> )</h4>

<emu-alg>
  1. Assert: ! IsReadableStream(_source_) is *true*.
  1. Assert: ! IsWritableStream(_dest_) is *true*.
  1. Assert: Type(_preventClose_) is Boolean, Type(_preventAbort_) is Boolean, and Type(_preventCancel_) is Boolean.
  1. Assert: _signal_ is *undefined* or _signal_ is an instance of the `<a idl>AbortSignal</a>` interface.
  1. Assert: ! IsReadableStreamLocked(_source_) is *false*.
  1. Assert: ! IsWritableStreamLocked(_dest_) is *false*.
  1. If ! IsReadableByteStreamController(_source_.[[readableStreamController]]) is *true*, let _reader_ be either !
     AcquireReadableStreamBYOBReader(_source_) or ! AcquireReadableStreamDefaultReader(_source_), at the user agent's
     discretion.
  1. Otherwise, let _reader_ be ! AcquireReadableStreamDefaultReader(_source_).
  1. Let _writer_ be ! AcquireWritableStreamDefaultWriter(_dest_).
  1. Set _source_.[[disturbed]] to *true*.
  1. Let _shuttingDown_ be *false*.
  1. Let _promise_ be <a>a new promise</a>.
  1. If _signal_ is not *undefined*,
    1. Let _abortAlgorithm_ be the following steps:
      1. Let _error_ be a new "`<a idl>AbortError</a>`" `<a idl>DOMException</a>`.
      1. Let _actions_ be an empty <a>ordered set</a>.
      1. If _preventAbort_ is *false*, <a for="set">append</a> the following action to _actions_:
        1. If _dest_.[[state]] is `"writable"`, return ! WritableStreamAbort(_dest_, _error_).
        1. Otherwise, return <a>a promise resolved with</a> *undefined*.
      1. If _preventCancel_ is *false*, <a for="set">append</a> the following action action to _actions_:
        1. If _source_.[[state]] is `"readable"`, return ! ReadableStreamCancel(_source_, _error_).
        1. Otherwise, return <a>a promise resolved with</a> *undefined*.
      1. <a href="#rs-pipeTo-shutdown-with-action">Shutdown with an action</a> consisting of
         <a>getting a promise to wait for all</a> of the actions in _actions_, and with _error_.
    1. If _signal_'s <a for=AbortSignal>aborted flag</a> is set, perform _abortAlgorithm_ and return _promise_.
    1. <a for="AbortSignal">Add</a> _abortAlgorithm_ to _signal_.
  1. <a>In parallel</a> <span class="XXX">but not really; see <a
     href="https://github.com/whatwg/streams/issues/905">#905</a></span>, using _reader_ and _writer_, read all
     <a>chunks</a> from _source_ and write them to _dest_. Due to the locking provided by the reader and writer, the exact
     manner in which this happens is not observable to author code, and so there is flexibility in how this is done. The
     following constraints apply regardless of the exact algorithm used:
     * <strong>Public API must not be used:</strong> while reading or writing, or performing any of the operations
       below, the JavaScript-modifiable reader, writer, and stream APIs (i.e. methods on the appropriate prototypes)
       must not be used. Instead, the streams must be manipulated directly.
     * <strong>Backpressure must be enforced:</strong>
       * While WritableStreamDefaultWriterGetDesiredSize(_writer_) is ≤ *0* or is *null*, the user agent must not read
         from _reader_.
       * If _reader_ is a <a>BYOB reader</a>, WritableStreamDefaultWriterGetDesiredSize(_writer_) should be used as a
         basis to determine the size of the chunks read from _reader_.
         <p class="note">It's frequently inefficient to read chunks that are too small or too large. Other information
         might be factored in to determine the optimal chunk size.</p>
       * Reads or writes should not be delayed for reasons other than these backpressure signals.
         <p class="example" id="example-bad-backpressure">An implementation that waits for each write to successfully
         complete before proceeding to the next read/write operation violates this recommendation. In doing so, such an
         implementation makes the <a>internal queue</a> of _dest_ useless, as it ensures _dest_ always contains at most
         one queued <a>chunk</a>.</p>
     * <strong>Shutdown must stop activity:</strong> if _shuttingDown_ becomes *true*, the user agent must not
       initiate further reads from _reader_, and must only perform writes of already-read <a>chunks</a>, as described
       below. In particular, the user agent must check the below conditions before performing any reads or writes,
       since they might lead to immediate shutdown.
     * <strong>Error and close states must be propagated:</strong> the following conditions must be applied in order.
       1. <strong>Errors must be propagated forward:</strong> if _source_.[[state]] is or becomes `"errored"`, then
         1. If _preventAbort_ is *false*, <a href="#rs-pipeTo-shutdown-with-action">shutdown with an action</a> of !
            WritableStreamAbort(_dest_, _source_.[[storedError]]) and with _source_.[[storedError]].
         1. Otherwise, <a href="#rs-pipeTo-shutdown">shutdown</a> with _source_.[[storedError]].
       1. <strong>Errors must be propagated backward:</strong> if _dest_.[[state]] is or becomes `"errored"`, then
         1. If _preventCancel_ is *false*, <a href="#rs-pipeTo-shutdown-with-action">shutdown with an action</a> of !
            ReadableStreamCancel(_source_, _dest_.[[storedError]]) and with _dest_.[[storedError]].
         1. Otherwise, <a href="#rs-pipeTo-shutdown">shutdown</a> with _dest_.[[storedError]].
       1. <strong>Closing must be propagated forward:</strong> if _source_.[[state]] is or becomes `"closed"`, then
         1. If _preventClose_ is *false*, <a href="#rs-pipeTo-shutdown-with-action">shutdown with an action</a> of !
            WritableStreamDefaultWriterCloseWithErrorPropagation(_writer_).
         1. Otherwise, <a href="#rs-pipeTo-shutdown">shutdown</a>.
       1. <strong>Closing must be propagated backward:</strong> if ! WritableStreamCloseQueuedOrInFlight(_dest_) is *true*
         or _dest_.[[state]] is `"closed"`, then
         1. Assert: no <a>chunks</a> have been read or written.
         1. Let _destClosed_ be a new *TypeError*.
         1. If _preventCancel_ is *false*, <a href="#rs-pipeTo-shutdown-with-action">shutdown with an action</a> of !
            ReadableStreamCancel(_source_, _destClosed_) and with _destClosed_.
         1. Otherwise, <a href="#rs-pipeTo-shutdown">shutdown</a> with _destClosed_.
     * <i id="rs-pipeTo-shutdown-with-action">Shutdown with an action</i>: if any of the above requirements ask to
       shutdown with an action _action_, optionally with an error _originalError_, then:
       1. If _shuttingDown_ is *true*, abort these substeps.
       1. Set _shuttingDown_ to *true*.
       1. If _dest_.[[state]] is `"writable"` and ! WritableStreamCloseQueuedOrInFlight(_dest_) is *false*,
         1. If any <a>chunks</a> have been read but not yet written, write them to _dest_.
         1. Wait until every <a>chunk</a> that has been read has been written (i.e. the corresponding promises have
            settled).
       1. Let _p_ be the result of performing _action_.
       1. <a>Upon fulfillment</a> of _p_, <a href="#rs-pipeTo-finalize">finalize</a>, passing along _originalError_ if
          it was given.
       1. <a>Upon rejection</a> of _p_ with reason _newError_, <a href="#rs-pipeTo-finalize">finalize</a> with
          _newError_.
     * <i id="rs-pipeTo-shutdown">Shutdown</i>: if any of the above requirements or steps ask to shutdown, optionally
       with an error _error_, then:
       1. If _shuttingDown_ is *true*, abort these substeps.
       1. Set _shuttingDown_ to *true*.
       1. If _dest_.[[state]] is `"writable"` and ! WritableStreamCloseQueuedOrInFlight(_dest_) is *false*,
         1. If any <a>chunks</a> have been read but not yet written, write them to _dest_.
         1. Wait until every <a>chunk</a> that has been read has been written (i.e. the corresponding promises have
            settled).
       1. <a href="#rs-pipeTo-finalize">Finalize</a>, passing along _error_ if it was given.
     * <i id="rs-pipeTo-finalize">Finalize</i>: both forms of shutdown will eventually ask to finalize, optionally with
       an error _error_, which means to perform the following steps:
       1. Perform ! WritableStreamDefaultWriterRelease(_writer_).
       1. Perform ! ReadableStreamReaderGenericRelease(_reader_).
       1. If _signal_ is not *undefined*, <a for="AbortSignal">remove</a> _abortAlgorithm_ from _signal_.
       1. If _error_ was given, <a>reject</a> _promise_ with _error_.
       1. Otherwise, <a>resolve</a> _promise_ with *undefined*.
  1. Return _promise_.
</emu-alg>

<p class="note">
  Various abstract operations performed here include object creation (often of promises), which usually would require
  specifying a realm for the created object. However, because of the locking, none of these objects can be observed by
  author code. As such, the realm used to create them does not matter.
</p>

<h3 id="rs-abstract-ops-used-by-controllers">The interface between readable streams and controllers</h3>

In terms of specification factoring, the way that the {{ReadableStream}} class encapsulates the behavior of
both simple readable streams and <a>readable byte streams</a> into a single class is by centralizing most of the
potentially-varying logic inside the two controller classes, {{ReadableStreamDefaultController}} and
{{ReadableByteStreamController}}. Those classes define most of the stateful internal slots and abstract
operations for how a stream's <a>internal queue</a> is managed and how it interfaces with its <a>underlying source</a>
or <a>underlying byte source</a>.

Each controller class defines two internal methods, which are called by the {{ReadableStream}} algorithms:

<dl>
  <dt><dfn abstract-op lt="[[CancelSteps]]">\[[CancelSteps]](<var>reason</var>)</dfn></dt>
  <dd>The controller's steps that run in reaction to the stream being <a lt="cancel a readable stream">canceled</a>,
  used to clean up the state stored in the controller and inform the <a>underlying source</a>.</dd>

  <dt><dfn abstract-op lt="[[PullSteps]]">\[[PullSteps]]()</dfn></dt>
  <dd>The controller's steps that run when a <a>default reader</a> is read from, used to pull from the controller any
  queued <a>chunks</a>, or pull from the <a>underlying source</a> to get more chunks.</dd>
</dl>

(These are defined as internal methods, instead of as abstract operations, so that they can be called polymorphically by
the {{ReadableStream}} algorithms, without having to branch on which type of controller is present.)

The rest of this section concerns abstract operations that go in the other direction: they are  used by the controller
implementations to affect their associated {{ReadableStream}} object. This translates internal state changes of the
controller into developer-facing results visible through the {{ReadableStream}}'s public API.

<h4 id="readable-stream-add-read-into-request" aoid="ReadableStreamAddReadIntoRequest"
nothrow>ReadableStreamAddReadIntoRequest ( <var>stream</var> )</h4>

<emu-alg>
  1. Assert: ! IsReadableStreamBYOBReader(_stream_.[[reader]]) is *true*.
  1. Assert: _stream_.[[state]] is `"readable"` or `"closed"`.
  1. Let _promise_ be <a>a new promise</a>.
  1. Let _readIntoRequest_ be Record {[[promise]]: _promise_}.
  1. Append _readIntoRequest_ as the last element of _stream_.[[reader]].[[readIntoRequests]].
  1. Return _promise_.
</emu-alg>

<h4 id="readable-stream-add-read-request" aoid="ReadableStreamAddReadRequest" nothrow>ReadableStreamAddReadRequest (
<var>stream</var> )</h4>

<emu-alg>
  1. Assert: ! IsReadableStreamDefaultReader(_stream_.[[reader]]) is *true*.
  1. Assert: _stream_.[[state]] is `"readable"`.
  1. Let _promise_ be <a>a new promise</a>.
  1. Let _readRequest_ be Record {[[promise]]: _promise_}.
  1. Append _readRequest_ as the last element of _stream_.[[reader]].[[readRequests]].
  1. Return _promise_.
</emu-alg>

<h4 id="readable-stream-cancel" aoid="ReadableStreamCancel" nothrow export>ReadableStreamCancel ( <var>stream</var>,
<var>reason</var> )</h4>

<emu-alg>
  1. Set _stream_.[[disturbed]] to *true*.
  1. If _stream_.[[state]] is `"closed"`, return <a>a promise resolved with</a> *undefined*.
  1. If _stream_.[[state]] is `"errored"`, return <a>a promise rejected with</a> _stream_.[[storedError]].
  1. Perform ! ReadableStreamClose(_stream_).
  1. Let _sourceCancelPromise_ be ! _stream_.[[readableStreamController]].<a abstract-op>[[CancelSteps]]</a>(_reason_).
  1. Return the result of <a>reacting</a> to _sourceCancelPromise_ with a fulfillment step that returns *undefined*.
</emu-alg>

<h4 id="readable-stream-close" aoid="ReadableStreamClose" nothrow>ReadableStreamClose ( <var>stream</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[state]] is `"readable"`.
  1. Set _stream_.[[state]] to `"closed"`.
  1. Let _reader_ be _stream_.[[reader]].
  1. If _reader_ is *undefined*, return.
  1. If ! IsReadableStreamDefaultReader(_reader_) is *true*,
    1. Repeat for each _readRequest_ that is an element of _reader_.[[readRequests]],
      1. <a>Resolve</a> _readRequest_.[[promise]] with ! ReadableStreamCreateReadResult(*undefined*, *true*,
         _reader_.[[forAuthorCode]]).
    1. Set _reader_.[[readRequests]] to an empty List.
  1. <a>Resolve</a> _reader_.[[closedPromise]] with *undefined*.
</emu-alg>

<div class="note">
  The case where <var>stream</var>.\[[state]] is <code>"closed"</code>, but <var>stream</var>.\[[closeRequested]] is
  <emu-val>false</emu-val>, will happen if the stream was closed without its controller's close method ever being
  called: i.e., if the stream was closed by a call to {{ReadableStream/cancel(reason)}}. In this case we allow the
  controller's <code>close</code> method to be called and silently do nothing, since the cancelation was outside the
  control of the underlying source.
</div>

<h4 id="readable-stream-create-read-result" aoid="ReadableStreamCreateReadResult" nothrow>ReadableStreamCreateReadResult
( <var>value</var>, <var>done</var>, <var>forAuthorCode</var> )</h4>

<div class="note" id="rs-read-result-for-author-code">
  When <var>forAuthorCode</var> is <emu-val>true</emu-val>, this abstract operation gives the same result
  as <a abstract-op>CreateIterResultObject</a>(<var>value</var>, <var>done</var>). This provides the expected semantics
  when the object is to be returned from the {{ReadableStreamDefaultReader/read()|defaultReader.read()}} or
  {{ReadableStreamBYOBReader/read()|byobReader.read()}} methods.

  However, resolving promises with such objects will unavoidably result in an access to
  <code>Object.prototype.then</code>. For internal use, particularly in {{ReadableStream/pipeTo()}} and in other
  specifications, it is important that reads not be observable by author code—even if that author code has tampered with
  <code>Object.prototype</code>. For this reason, a <emu-val>false</emu-val> value of <var>forAuthorCode</var> results
  in an object with a <emu-val>null</emu-val> prototype, keeping promise resolution unobservable.

  The underlying issue here is that reading from streams always uses promises for <code>{ value, done }</code> objects,
  even in specifications. Although it is conceivable we could rephrase all of the internal algorithms to not use
  promises and not use JavaScript objects, and instead only package up the results into promise-for-<code>{ value, done
  }</code> when a <code>read()</code> method is called, this would be a large undertaking, which we have not done. See
  <a href="https://github.com/whatwg/infra/issues/181">whatwg/infra#181</a> for more background on this subject.
</div>

<emu-alg>
  1. Let _prototype_ be *null*.
  1. If _forAuthorCode_ is *true*, set _prototype_ to %ObjectPrototype%.
  1. Assert: Type(_done_) is Boolean.
  1. Let _obj_ be ObjectCreate(_prototype_).
  1. Perform CreateDataProperty(_obj_, `"value"`, _value_).
  1. Perform CreateDataProperty(_obj_, `"done"`, _done_).
  1. Return _obj_.
</emu-alg>

<h4 id="readable-stream-error" aoid="ReadableStreamError" nothrow>ReadableStreamError ( <var>stream</var>, <var>e</var>
)</h4>

<emu-alg>
  1. Assert: ! IsReadableStream(_stream_) is *true*.
  1. Assert: _stream_.[[state]] is `"readable"`.
  1. Set _stream_.[[state]] to `"errored"`.
  1. Set _stream_.[[storedError]] to _e_.
  1. Let _reader_ be _stream_.[[reader]].
  1. If _reader_ is *undefined*, return.
  1. If ! IsReadableStreamDefaultReader(_reader_) is *true*,
    1. Repeat for each _readRequest_ that is an element of _reader_.[[readRequests]],
      1. <a>Reject</a> _readRequest_.[[promise]] with _e_.
    1. Set _reader_.[[readRequests]] to a new empty List.
  1. Otherwise,
    1. Assert: ! IsReadableStreamBYOBReader(_reader_).
    1. Repeat for each _readIntoRequest_ that is an element of _reader_.[[readIntoRequests]],
      1. <a>Reject</a> _readIntoRequest_.[[promise]] with _e_.
    1. Set _reader_.[[readIntoRequests]] to a new empty List.
  1. <a>Reject</a> _reader_.[[closedPromise]] with _e_.
  1. Set _reader_.[[closedPromise]].[[PromiseIsHandled]] to *true*.
</emu-alg>

<h4 id="readable-stream-fulfill-read-into-request" aoid="ReadableStreamFulfillReadIntoRequest"
nothrow>ReadableStreamFulfillReadIntoRequest ( <var>stream</var>, <var>chunk</var>, <var>done</var> )</h4>

<emu-alg>
  1. Let _reader_ be _stream_.[[reader]].
  1. Let _readIntoRequest_ be the first element of _reader_.[[readIntoRequests]].
  1. Remove _readIntoRequest_ from _reader_.[[readIntoRequests]], shifting all other elements downward (so that the
     second becomes the first, and so on).
  1. <a>Resolve</a> _readIntoRequest_.[[promise]] with ! ReadableStreamCreateReadResult(_chunk_, _done_,
     _reader_.[[forAuthorCode]]).
</emu-alg>

<h4 id="readable-stream-fulfill-read-request" aoid="ReadableStreamFulfillReadRequest"
nothrow>ReadableStreamFulfillReadRequest ( <var>stream</var>, <var>chunk</var>, <var>done</var> )</h4>

<emu-alg>
  1. Let _reader_ be _stream_.[[reader]].
  1. Let _readRequest_ be the first element of _reader_.[[readRequests]].
  1. Remove _readRequest_ from _reader_.[[readRequests]], shifting all other elements downward (so that the second
     becomes the first, and so on).
  1. <a>Resolve</a> _readRequest_.[[promise]] with ! ReadableStreamCreateReadResult(_chunk_, _done_,
     _reader_.[[forAuthorCode]]).
</emu-alg>

<h4 id="readable-stream-get-num-read-into-requests" aoid="ReadableStreamGetNumReadIntoRequests"
nothrow>ReadableStreamGetNumReadIntoRequests ( <var>stream</var> )</h4>

<emu-alg>
  1. Return the number of elements in _stream_.[[reader]].[[readIntoRequests]].
</emu-alg>

<h4 id="readable-stream-get-num-read-requests" aoid="ReadableStreamGetNumReadRequests"
nothrow>ReadableStreamGetNumReadRequests ( <var>stream</var> )</h4>

<emu-alg>
  1. Return the number of elements in _stream_.[[reader]].[[readRequests]].
</emu-alg>

<h4 id="readable-stream-has-byob-reader" aoid="ReadableStreamHasBYOBReader" nothrow>ReadableStreamHasBYOBReader (
<var>stream</var> )</h4>

<emu-alg>
  1. Let _reader_ be _stream_.[[reader]].
  1. If _reader_ is *undefined*, return *false*.
  1. If ! IsReadableStreamBYOBReader(_reader_) is *false*, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="readable-stream-has-default-reader" aoid="ReadableStreamHasDefaultReader" nothrow>ReadableStreamHasDefaultReader (
<var>stream</var> )</h4>

<emu-alg>
  1. Let _reader_ be _stream_.[[reader]].
  1. If _reader_ is *undefined*, return *false*.
  1. If ! IsReadableStreamDefaultReader(_reader_) is *false*, return *false*.
  1. Return *true*.
</emu-alg>

<h3 id="default-reader-class" interface lt="ReadableStreamDefaultReader">Class
<code>ReadableStreamDefaultReader</code></h3>

The {{ReadableStreamDefaultReader}} class represents a <a>default reader</a> designed to be vended by a
{{ReadableStream}} instance.

<h4 id="default-reader-class-definition">Class definition</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{ReadableStreamDefaultReader}} class in something close to the syntax of [[!ECMASCRIPT]], it
would look like

<pre><code class="lang-javascript">
  class ReadableStreamDefaultReader {
    <a href="#default-reader-constructor">constructor(stream)</a>

    get <a href="#default-reader-closed">closed</a>()

    <a href="#default-reader-cancel">cancel</a>(reason)
    <a href="#default-reader-read">read</a>()
    <a href="#default-reader-release-lock">releaseLock</a>()
  }
</code></pre>

</div>

<h4 id="default-reader-internal-slots">Internal slots</h4>

Instances of {{ReadableStreamDefaultReader}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[closedPromise]]
    <td class="non-normative">A promise returned by the reader's {{ReadableStreamDefaultReader/closed}} getter
  </tr>
  <tr>
    <td>\[[forAuthorCode]]
    <td class="non-normative">A boolean flag indicating whether this reader is visible to author code
  </tr>
  <tr>
    <td>\[[ownerReadableStream]]
    <td class="non-normative">A {{ReadableStream}} instance that owns this reader
  </tr>
  <tr>
    <td>\[[readRequests]]
    <td class="non-normative">A List of promises returned by calls to the reader's
      {{ReadableStreamDefaultReader/read()}} method that have not yet been resolved, due to the <a>consumer</a>
      requesting <a>chunks</a> sooner than they are available; also used for the <a
      href="#is-readable-stream-default-reader">IsReadableStreamDefaultReader</a> brand check
  </tr>
</table>

<h4 id="default-reader-constructor" constructor for="ReadableStreamDefaultReader"
lt="ReadableStreamDefaultReader(stream)">new ReadableStreamDefaultReader(<var>stream</var>)</h4>

<div class="note">
  The <code>ReadableStreamDefaultReader</code> constructor is generally not meant to be used directly; instead, a
  stream's {{ReadableStream/getReader()}} method ought to be used.
</div>

<emu-alg>
  1. If ! IsReadableStream(_stream_) is *false*, throw a *TypeError* exception.
  1. If ! IsReadableStreamLocked(_stream_) is *true*, throw a *TypeError* exception.
  1. Perform ! ReadableStreamReaderGenericInitialize(*this*, _stream_).
  1. Set *this*.[[readRequests]] to a new empty List.
</emu-alg>

<h4 id="default-reader-prototype">Properties of the {{ReadableStreamDefaultReader}} prototype</h4>

<h5 id="default-reader-closed" attribute for="ReadableStreamDefaultReader" lt="closed">get closed</h5>

<div class="note">
  The <code>closed</code> getter returns a promise that will be fulfilled when the stream becomes closed, or rejected if
  the stream ever errors or the reader's lock is <a lt="release a read lock">released</a> before the stream finishes
  closing.
</div>

<emu-alg>
  1. If ! IsReadableStreamDefaultReader(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return *this*.[[closedPromise]].
</emu-alg>

<h5 id="default-reader-cancel" method for="ReadableStreamDefaultReader">cancel(<var>reason</var>)</h5>

<div class="note">
  If the reader is <a lt="active reader">active</a>, the <code>cancel</code> method behaves the same as that for the
  associated stream.
</div>

<emu-alg>
  1. If ! IsReadableStreamDefaultReader(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If *this*.[[ownerReadableStream]] is *undefined*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return ! ReadableStreamReaderGenericCancel(*this*, _reason_).
</emu-alg>

<h5 id="default-reader-read" method for="ReadableStreamDefaultReader">read()</h5>

<div class="note">
  The <code>read</code> method will return a promise that allows access to the next <a>chunk</a> from the stream's
  internal queue, if available.

  <ul>
    <li> If the chunk does become available, the promise will be fulfilled with an object of the form
      <code>{ value: theChunk, done: false }</code>.
    <li> If the stream becomes closed, the promise will be fulfilled with an object of the form
      <code>{ value: undefined, done: true }</code>.
    <li> If the stream becomes errored, the promise will be rejected with the relevant error.
  </ul>

  If reading a chunk causes the queue to become empty, more data will be pulled from the <a>underlying source</a>.
</div>

<emu-alg>
  1. If ! IsReadableStreamDefaultReader(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If *this*.[[ownerReadableStream]] is *undefined*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return ! ReadableStreamDefaultReaderRead(*this*).
</emu-alg>

<h5 id="default-reader-release-lock" method for="ReadableStreamDefaultReader">releaseLock()</h5>

<div class="note">
  The <code>releaseLock</code> method <a lt="release a read lock">releases the reader's lock</a> on the corresponding
  stream. After the lock is released, the reader is no longer <a lt="active reader">active</a>. If the associated
  stream is errored when the lock is released, the reader will appear errored in the same way from now on; otherwise,
  the reader will appear closed.

  A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by the
  reader's {{ReadableStreamDefaultReader/read()}} method has not yet been settled. Attempting to do so will throw
  a <emu-val>TypeError</emu-val> and leave the reader locked to the stream.
</div>

<emu-alg>
  1. If ! IsReadableStreamDefaultReader(*this*) is *false*, throw a *TypeError* exception.
  1. If *this*.[[ownerReadableStream]] is *undefined*, return.
  1. If *this*.[[readRequests]] is not empty, throw a *TypeError* exception.
  1. Perform ! ReadableStreamReaderGenericRelease(*this*).
</emu-alg>

<h3 id="byob-reader-class" interface lt="ReadableStreamBYOBReader">Class <code>ReadableStreamBYOBReader</code></h3>

The {{ReadableStreamBYOBReader}} class represents a <a>BYOB reader</a> designed to be vended by a {{ReadableStream}}
instance.

<h4 id="byob-reader-class-definition">Class definition</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{ReadableStreamBYOBReader}} class in something close to the syntax of [[!ECMASCRIPT]], it
would look like

<pre><code class="lang-javascript">
  class ReadableStreamBYOBReader {
    <a href="#byob-reader-constructor">constructor</a>(stream)

    get <a href="#byob-reader-closed">closed</a>()

    <a href="#byob-reader-cancel">cancel</a>(reason)
    <a href="#byob-reader-read">read</a>(view)
    <a href="#byob-reader-release-lock">releaseLock</a>()
  }
</code></pre>

</div>

<h4 id="byob-reader-internal-slots">Internal slots</h4>

Instances of {{ReadableStreamBYOBReader}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[closedPromise]]
    <td class="non-normative">A promise returned by the reader's {{ReadableStreamBYOBReader/closed}} getter
  </tr>
  <tr>
    <td>\[[forAuthorCode]]
    <td class="non-normative">A boolean flag indicating whether this reader is visible to author code
  </tr>
  <tr>
    <td>\[[ownerReadableStream]]
    <td class="non-normative">A {{ReadableStream}} instance that owns this reader
  </tr>
  <tr>
    <td>\[[readIntoRequests]]
    <td class="non-normative">A List of promises returned by calls to the reader's
      {{ReadableStreamBYOBReader/read(view)}} method that have not yet been resolved, due to the <a>consumer</a>
      requesting <a>chunks</a> sooner than they are available; also used for the <a
      href="#is-readable-stream-byob-reader">IsReadableStreamBYOBReader</a> brand check
  </tr>
</table>

<h4 id="byob-reader-constructor" constructor for="ReadableStreamBYOBReader" lt="ReadableStreamBYOBReader(stream)">new
ReadableStreamBYOBReader(<var>stream</var>)</h4>

<div class="note">
  The <code>ReadableStreamBYOBReader</code> constructor is generally not meant to be used directly; instead, a stream's
  {{ReadableStream/getReader()}} method ought to be used.
</div>

<emu-alg>
  1. If ! IsReadableStream(_stream_) is *false*, throw a *TypeError* exception.
  1. If ! IsReadableByteStreamController(_stream_.[[readableStreamController]]) is *false*, throw a *TypeError* exception.
  1. If ! IsReadableStreamLocked(_stream_) is *true*, throw a *TypeError* exception.
  1. Perform ! ReadableStreamReaderGenericInitialize(*this*, _stream_).
  1. Set *this*.[[readIntoRequests]] to a new empty List.
</emu-alg>

<h4 id="byob-reader-prototype">Properties of the {{ReadableStreamBYOBReader}} prototype</h4>

<h5 id="byob-reader-closed" attribute for="ReadableStreamBYOBReader" lt="closed">get closed</h5>

<div class="note">
  The <code>closed</code> getter returns a promise that will be fulfilled when the stream becomes closed, or rejected if
  the stream ever errors or the reader's lock is <a lt="release a read lock">released</a> before the stream finishes
  closing.
</div>

<emu-alg>
  1. If ! IsReadableStreamBYOBReader(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return *this*.[[closedPromise]].
</emu-alg>

<h5 id="byob-reader-cancel" method for="ReadableStreamBYOBReader">cancel(<var>reason</var>)</h5>

<div class="note">
  If the reader is <a lt="active reader">active</a>, the <code>cancel</code> method behaves the same as that for the
  associated stream.
</div>

<emu-alg>
  1. If ! IsReadableStreamBYOBReader(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If *this*.[[ownerReadableStream]] is *undefined*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return ! ReadableStreamReaderGenericCancel(*this*, _reason_).
</emu-alg>

<h5 id="byob-reader-read" method for="ReadableStreamBYOBReader">read(<var>view</var>)</h5>

<div class="note">
  The <code>read</code> method will write read bytes into <code>view</code> and return <a>a promise resolved with</a> a
  possibly transferred buffer as described below.

  <ul>
    <li> If the chunk does become available, the promise will be fulfilled with an object of the form
      <code>{ value: theChunk, done: false }</code>.
    <li> If the stream becomes closed, the promise will be fulfilled with an object of the form
      <code>{ value: undefined, done: true }</code>.
    <li> If the stream becomes errored, the promise will be rejected with the relevant error.
  </ul>

  If reading a chunk causes the queue to become empty, more data will be pulled from the <a>underlying byte source</a>.
</div>

<emu-alg>
  1. If ! IsReadableStreamBYOBReader(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If *this*.[[ownerReadableStream]] is *undefined*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If Type(_view_) is not Object, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If _view_ does not have a [[ViewedArrayBuffer]] internal slot, return <a>a promise rejected with</a> a *TypeError*
     exception.
  1. If ! IsDetachedBuffer(_view_.[[ViewedArrayBuffer]]) is *true*, return <a>a promise rejected with</a> a *TypeError*
     exception.
  1. If _view_.[[ByteLength]] is *0*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return ! ReadableStreamBYOBReaderRead(*this*, _view_).
</emu-alg>

<h5 id="byob-reader-release-lock" method for="ReadableStreamBYOBReader">releaseLock()</h5>

<div class="note">
  The <code>releaseLock</code> method <a lt="release a read lock">releases the reader's lock</a> on the corresponding
  stream. After the lock is released, the reader is no longer <a lt="active reader">active</a>. If the associated
  stream is errored when the lock is released, the reader will appear errored in the same way from now on; otherwise,
  the reader will appear closed.

  A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by the
  reader's {{ReadableStreamBYOBReader/read()}} method has not yet been settled. Attempting to do so will throw
  a <emu-val>TypeError</emu-val> and leave the reader locked to the stream.
</div>

<emu-alg>
  1. If ! IsReadableStreamBYOBReader(*this*) is *false*, throw a *TypeError* exception.
  1. If *this*.[[ownerReadableStream]] is *undefined*, return.
  1. If *this*.[[readIntoRequests]] is not empty, throw a *TypeError* exception.
  1. Perform ! ReadableStreamReaderGenericRelease(*this*).
</emu-alg>

<h3 id="rs-reader-abstract-ops">Readable stream reader abstract operations</h3>

<h4 id="is-readable-stream-default-reader" aoid="IsReadableStreamDefaultReader" nothrow>IsReadableStreamDefaultReader (
<var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have a [[readRequests]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="is-readable-stream-byob-reader" aoid="IsReadableStreamBYOBReader" nothrow>IsReadableStreamBYOBReader (
<var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have a [[readIntoRequests]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="readable-stream-reader-generic-cancel" aoid="ReadableStreamReaderGenericCancel"
nothrow>ReadableStreamReaderGenericCancel ( <var>reader</var>, <var>reason</var> )</h4>

<emu-alg>
  1. Let _stream_ be _reader_.[[ownerReadableStream]].
  1. Assert: _stream_ is not *undefined*.
  1. Return ! ReadableStreamCancel(_stream_, _reason_).
</emu-alg>

<h4 id="readable-stream-reader-generic-initialize" aoid="ReadableStreamReaderGenericInitialize"
nothrow>ReadableStreamReaderGenericInitialize ( <var>reader</var>, <var>stream</var> )</h4>

<emu-alg>
  1. Set _reader_.[[forAuthorCode]] to *true*.
  1. Set _reader_.[[ownerReadableStream]] to _stream_.
  1. Set _stream_.[[reader]] to _reader_.
  1. If _stream_.[[state]] is `"readable"`,
    1. Set _reader_.[[closedPromise]] to <a>a new promise</a>.
  1. Otherwise, if _stream_.[[state]] is `"closed"`,
    1. Set _reader_.[[closedPromise]] to <a>a promise resolved with</a> *undefined*.
  1. Otherwise,
    1. Assert: _stream_.[[state]] is `"errored"`.
    1. Set _reader_.[[closedPromise]] to <a>a promise rejected with</a> _stream_.[[storedError]].
    1. Set _reader_.[[closedPromise]].[[PromiseIsHandled]] to *true*.
</emu-alg>

<h4 id="readable-stream-reader-generic-release" aoid="ReadableStreamReaderGenericRelease"
nothrow>ReadableStreamReaderGenericRelease ( <var>reader</var> )</h4>

<emu-alg>
  1. Assert: _reader_.[[ownerReadableStream]] is not *undefined*.
  1. Assert: _reader_.[[ownerReadableStream]].[[reader]] is _reader_.
  1. If _reader_.[[ownerReadableStream]].[[state]] is `"readable"`, <a>reject</a> _reader_.[[closedPromise]] with a *TypeError*
     exception.
  1. Otherwise, set _reader_.[[closedPromise]] to <a>a promise rejected with</a> a *TypeError* exception.
  1. Set _reader_.[[closedPromise]].[[PromiseIsHandled]] to *true*.
  1. Set _reader_.[[ownerReadableStream]].[[reader]] to *undefined*.
  1. Set _reader_.[[ownerReadableStream]] to *undefined*.
</emu-alg>

<h4 id="readable-stream-byob-reader-read" aoid="ReadableStreamBYOBReaderRead" nothrow>ReadableStreamBYOBReaderRead
( <var>reader</var>, <var>view</var> )</h4>

<emu-alg>
  1. Let _stream_ be _reader_.[[ownerReadableStream]].
  1. Assert: _stream_ is not *undefined*.
  1. Set _stream_.[[disturbed]] to *true*.
  1. If _stream_.[[state]] is `"errored"`, return <a>a promise rejected with</a> _stream_.[[storedError]].
  1. Return ! ReadableByteStreamControllerPullInto(_stream_.[[readableStreamController]], _view_).
</emu-alg>

<h4 id="readable-stream-default-reader-read" aoid="ReadableStreamDefaultReaderRead" nothrow
export>ReadableStreamDefaultReaderRead ( <var>reader</var> )</h4>

<emu-alg>
  1. Let _stream_ be _reader_.[[ownerReadableStream]].
  1. Assert: _stream_ is not *undefined*.
  1. Set _stream_.[[disturbed]] to *true*.
  1. If _stream_.[[state]] is `"closed"`, return <a>a promise resolved with</a> !
     ReadableStreamCreateReadResult(*undefined*, *true*, _reader_.[[forAuthorCode]]).
  1. If _stream_.[[state]] is `"errored"`, return <a>a promise rejected with</a> _stream_.[[storedError]].
  1. Assert: _stream_.[[state]] is `"readable"`.
  1. Return ! _stream_.[[readableStreamController]].<a abstract-op>[[PullSteps]]</a>().
</emu-alg>

<h3 id="rs-default-controller-class" interface lt="ReadableStreamDefaultController">Class
<code>ReadableStreamDefaultController</code></h3>

The {{ReadableStreamDefaultController}} class has methods that allow control of a {{ReadableStream}}'s state and
<a>internal queue</a>. When constructing a {{ReadableStream}} that is not a <a>readable byte stream</a>, the
<a>underlying source</a> is given a corresponding {{ReadableStreamDefaultController}} instance to manipulate.

<h4 id="rs-default-controller-class-definition">Class definition</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{ReadableStreamDefaultController}} class in something close to the syntax of [[!ECMASCRIPT]],
it would look like

<pre><code class="lang-javascript">
  class ReadableStreamDefaultController {
    <a href="#rs-default-controller-constructor">constructor</a>() // always throws

    get <a href="#rs-default-controller-desired-size">desiredSize</a>()

    <a href="#rs-default-controller-close">close</a>()
    <a href="#rs-default-controller-enqueue">enqueue</a>(chunk)
    <a href="#rs-default-controller-error">error</a>(e)
  }
</code></pre>

</div>

<h4 id="rs-default-controller-internal-slots">Internal slots</h4>

Instances of {{ReadableStreamDefaultController}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[cancelAlgorithm]]
    <td class="non-normative">A promise-returning algorithm, taking one argument (the cancel reason), which communicates
      a requested cancelation to the <a>underlying source</a>
  </tr>
  <tr>
    <td>\[[closeRequested]]
    <td class="non-normative">A boolean flag indicating whether the stream has been closed by its <a>underlying
      source</a>, but still has <a>chunks</a> in its internal queue that have not yet been read
  </tr>
  <tr>
    <td>\[[controlledReadableStream]]
    <td class="non-normative">The {{ReadableStream}} instance controlled
  </tr>
  <tr>
    <td>\[[pullAgain]]
    <td class="non-normative">A boolean flag set to <emu-val>true</emu-val> if the stream's mechanisms requested a call
      to the <a>underlying source</a>'s pull algorithm to pull more data, but the pull could not yet be done since a
      previous call is still executing
  </tr>
  <tr>
    <td>\[[pullAlgorithm]]
    <td class="non-normative">A promise-returning algorithm that pulls data from the <a>underlying source</a>
  </tr>
  <tr>
    <td>\[[pulling]]
    <td class="non-normative">A boolean flag set to <emu-val>true</emu-val> while the <a>underlying source</a>'s
      pull algorithm is executing and the returned promise has not yet fulfilled, used to prevent reentrant calls
  </tr>
  <tr>
    <td>\[[queue]]
    <td class="non-normative">A List representing the stream's internal queue of <a>chunks</a>
  </tr>
  <tr>
    <td>\[[queueTotalSize]]
    <td class="non-normative">The total size of all the chunks stored in \[[queue]] (see [[#queue-with-sizes]])
  </tr>
  <tr>
    <td>\[[started]]
    <td class="non-normative">A boolean flag indicating whether the <a>underlying source</a> has finished starting
  </tr>
  <tr>
    <td>\[[strategyHWM]]
    <td class="non-normative">A number supplied to the constructor as part of the stream's <a>queuing strategy</a>,
      indicating the point at which the stream will apply <a>backpressure</a> to its <a>underlying source</a>
  </tr>
  <tr>
    <td>\[[strategySizeAlgorithm]]
    <td class="non-normative">An algorithm to calculate the size of enqueued <a>chunks</a>, as part of the stream's
      <a>queuing strategy</a>
  </tr>
</table>

<h4 id="rs-default-controller-constructor" constructor for="ReadableStreamDefaultController"
lt="ReadableStreamDefaultController()">new ReadableStreamDefaultController()</h4>

<div class="note">
  The <code>ReadableStreamDefaultController</code> constructor cannot be used directly;
  {{ReadableStreamDefaultController}} instances are created automatically during {{ReadableStream}} construction.
</div>

<emu-alg>
  1. Throw a *TypeError*.
</emu-alg>

<h4 id="rs-default-controller-prototype">Properties of the {{ReadableStreamDefaultController}} prototype</h4>

<h5 id="rs-default-controller-desired-size" attribute for="ReadableStreamDefaultController" lt="desiredSize">get
desiredSize</h5>

<div class="note">
  The <code>desiredSize</code> getter returns the <a lt="desired size to fill a stream's internal queue">desired size
  to fill the controlled stream's internal queue</a>. It can be negative, if the queue is over-full. An <a>underlying
  source</a> ought to use this information to determine when and how to apply <a>backpressure</a>.
</div>

<emu-alg>
  1. If ! IsReadableStreamDefaultController(*this*) is *false*, throw a *TypeError* exception.
  1. Return ! ReadableStreamDefaultControllerGetDesiredSize(*this*).
</emu-alg>

<h5 id="rs-default-controller-close" method for="ReadableStreamDefaultController">close()</h5>

<div class="note">
  The <code>close</code> method will close the controlled readable stream. <a>Consumers</a> will still be able to read
  any previously-enqueued <a>chunks</a> from the stream, but once those are read, the stream will become closed.
</div>

<emu-alg>
  1. If ! IsReadableStreamDefaultController(*this*) is *false*, throw a *TypeError* exception.
  1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(*this*) is *false*, throw a *TypeError* exception.
  1. Perform ! ReadableStreamDefaultControllerClose(*this*).
</emu-alg>

<h5 id="rs-default-controller-enqueue" method for="ReadableStreamDefaultController">enqueue(<var>chunk</var>)</h5>

<div class="note">
  The <code>enqueue</code> method will enqueue a given <a>chunk</a> in the controlled readable stream.
</div>

<emu-alg>
  1. If ! IsReadableStreamDefaultController(*this*) is *false*, throw a *TypeError* exception.
  1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(*this*) is *false*, throw a *TypeError* exception.
  1. Return ? ReadableStreamDefaultControllerEnqueue(*this*, _chunk_).
</emu-alg>

<h5 id="rs-default-controller-error" method for="ReadableStreamDefaultController">error(<var>e</var>)</h5>

<div class="note">
  The <code>error</code> method will error the readable stream, making all future interactions with it fail with the
  given error <code>e</code>.
</div>

<emu-alg>
  1. If ! IsReadableStreamDefaultController(*this*) is *false*, throw a *TypeError* exception.
  1. Perform ! ReadableStreamDefaultControllerError(*this*, _e_).
</emu-alg>

<h4 id="rs-default-controller-internal-methods">Readable stream default controller internal methods</h4>

The following are additional internal methods implemented by each {{ReadableStreamDefaultController}} instance. The
readable stream implementation will polymorphically call to either these or their counterparts for BYOB controllers.

<h5 id="rs-default-controller-private-cancel"><a abstract-op>\[[CancelSteps]]</a>(<var>reason</var>)</h5>

<emu-alg>
  1. Perform ! ResetQueue(*this*).
  1. Let _result_ be the result of performing *this*.[[cancelAlgorithm]], passing _reason_.
  1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(*this*).
  1. Return _result_.
</emu-alg>

<h5 id="rs-default-controller-private-pull"><a abstract-op>\[[PullSteps]]</a>( )</h5>

<emu-alg>
  1. Let _stream_ be *this*.[[controlledReadableStream]].
  1. If *this*.[[queue]] is not empty,
    1. Let _chunk_ be ! DequeueValue(*this*).
    1. If *this*.[[closeRequested]] is *true* and *this*.[[queue]] is empty,
      1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(*this*).
      1. Perform ! ReadableStreamClose(_stream_).
    1. Otherwise, perform ! ReadableStreamDefaultControllerCallPullIfNeeded(*this*).
    1. Return <a>a promise resolved with</a> ! ReadableStreamCreateReadResult(_chunk_, *false*,
       _stream_.[[reader]].[[forAuthorCode]]).
  1. Let _pendingPromise_ be ! ReadableStreamAddReadRequest(_stream_).
  1. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(*this*).
  1. Return _pendingPromise_.
</emu-alg>

<h3 id="rs-default-controller-abstract-ops">Readable stream default controller abstract operations</h3>

<h4 id="is-readable-stream-default-controller" aoid="IsReadableStreamDefaultController"
nothrow>IsReadableStreamDefaultController ( <var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have a [[controlledReadableStream]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="readable-stream-default-controller-call-pull-if-needed" aoid="ReadableStreamDefaultControllerCallPullIfNeeded"
nothrow>ReadableStreamDefaultControllerCallPullIfNeeded ( <var>controller</var> )</h4>

<emu-alg>
  1. Let _shouldPull_ be ! ReadableStreamDefaultControllerShouldCallPull(_controller_).
  1. If _shouldPull_ is *false*, return.
  1. If _controller_.[[pulling]] is *true*,
    1. Set _controller_.[[pullAgain]] to *true*.
    1. Return.
  1. Assert: _controller_.[[pullAgain]] is *false*.
  1. Set _controller_.[[pulling]] to *true*.
  1. Let _pullPromise_ be the result of performing _controller_.[[pullAlgorithm]].
  1. <a>Upon fulfillment</a> of _pullPromise_,
    1. Set _controller_.[[pulling]] to *false*.
    1. If _controller_.[[pullAgain]] is *true*,
      1. Set _controller_.[[pullAgain]] to *false*.
      1. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(_controller_).
  1. <a>Upon rejection</a> of _pullPromise_ with reason _e_,
    1. Perform ! ReadableStreamDefaultControllerError(_controller_, _e_).
</emu-alg>

<h4 id="readable-stream-default-controller-should-call-pull" aoid="ReadableStreamDefaultControllerShouldCallPull"
nothrow>ReadableStreamDefaultControllerShouldCallPull ( <var>controller</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableStream]].
  1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(_controller_) is *false*, return *false*.
  1. If _controller_.[[started]] is *false*, return *false*.
  1. If ! IsReadableStreamLocked(_stream_) is *true* and ! ReadableStreamGetNumReadRequests(_stream_) > *0*, return
     *true*.
  1. Let _desiredSize_ be ! ReadableStreamDefaultControllerGetDesiredSize(_controller_).
  1. Assert: _desiredSize_ is not *null*.
  1. If _desiredSize_ > *0*, return *true*.
  1. Return *false*.
</emu-alg>

<h4 id="readable-stream-default-controller-clear-algorithms" aoid="ReadableStreamDefaultControllerClearAlgorithms"
nothrow export>ReadableStreamDefaultControllerClearAlgorithms ( <var>controller</var> )</h4>

This abstract operation is called once the stream is closed or errored and the algorithms will not be executed any more.
By removing the algorithm references it permits the <a>underlying source</a> object to be garbage collected even if the
{{ReadableStream}} itself is still referenced.

<p class="note">The results of this algorithm are not currently observable, but could become so if JavaScript eventually
adds <a href="https://github.com/tc39/proposal-weakrefs/">weak references</a>. But even without that factor,
implementations will likely want to include similar steps.</p>

<emu-alg>
  1. Set _controller_.[[pullAlgorithm]] to *undefined*.
  1. Set _controller_.[[cancelAlgorithm]] to *undefined*.
  1. Set _controller_.[[strategySizeAlgorithm]] to *undefined*.
</emu-alg>

<h4 id="readable-stream-default-controller-close" aoid="ReadableStreamDefaultControllerClose" nothrow
export>ReadableStreamDefaultControllerClose ( <var>controller</var> )</h4>

This abstract operation can be called by other specifications that wish to close a readable stream, in the same way
a developer-created stream would be closed by its associated controller object. Specifications should <em>not</em> do
this to streams they did not create, and must ensure they have obeyed the preconditions (listed here as asserts).

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableStream]].
  1. Assert: ! ReadableStreamDefaultControllerCanCloseOrEnqueue(_controller_) is *true*.
  1. Set _controller_.[[closeRequested]] to *true*.
  1. If _controller_.[[queue]] is empty,
    1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(_controller_).
    1. Perform ! ReadableStreamClose(_stream_).
</emu-alg>

<h4 id="readable-stream-default-controller-enqueue" aoid="ReadableStreamDefaultControllerEnqueue" throws
export>ReadableStreamDefaultControllerEnqueue ( <var>controller</var>, <var>chunk</var> )</h4>

This abstract operation can be called by other specifications that wish to enqueue <a>chunks</a> in a readable stream,
in the same way a developer would enqueue chunks using the stream's associated controller object. Specifications should
<em>not</em> do this to streams they did not create, and must ensure they have obeyed the preconditions (listed here as
asserts).

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableStream]].
  1. Assert: ! ReadableStreamDefaultControllerCanCloseOrEnqueue(_controller_) is *true*.
  1. If ! IsReadableStreamLocked(_stream_) is *true* and ! ReadableStreamGetNumReadRequests(_stream_) > *0*, perform
     ! ReadableStreamFulfillReadRequest(_stream_, _chunk_, *false*).
  1. Otherwise,
    1. Let _result_ be the result of performing _controller_.[[strategySizeAlgorithm]], passing in _chunk_, and
       interpreting the result as an ECMAScript completion value.
    1. If _result_ is an abrupt completion,
      1. Perform ! ReadableStreamDefaultControllerError(_controller_, _result_.[[Value]]).
      1. Return _result_.
    1. Let _chunkSize_ be _result_.[[Value]].
    1. Let _enqueueResult_ be EnqueueValueWithSize(_controller_, _chunk_, _chunkSize_).
    1. If _enqueueResult_ is an abrupt completion,
      1. Perform ! ReadableStreamDefaultControllerError(_controller_, _enqueueResult_.[[Value]]).
      1. Return _enqueueResult_.
  1. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(_controller_).
</emu-alg>

<h4 id="readable-stream-default-controller-error" aoid="ReadableStreamDefaultControllerError" nothrow
export>ReadableStreamDefaultControllerError ( <var>controller</var>, <var>e</var> )</h4>

This abstract operation can be called by other specifications that wish to move a readable stream to an errored state,
in the same way a developer would error a stream using its associated controller object. Specifications should
<em>not</em> do this to streams they did not create.

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableStream]].
  1. If _stream_.[[state]] is not `"readable"`, return.
  1. Perform ! ResetQueue(_controller_).
  1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(_controller_).
  1. Perform ! ReadableStreamError(_stream_, _e_).
</emu-alg>

<h4 id="readable-stream-default-controller-get-desired-size" aoid="ReadableStreamDefaultControllerGetDesiredSize"
nothrow export>ReadableStreamDefaultControllerGetDesiredSize ( <var>controller</var> )</h4>

This abstract operation can be called by other specifications that wish to determine the <a lt="desired size to fill a
stream's internal queue">desired size to fill this stream's internal queue</a>, similar to how a developer would consult
the {{ReadableStreamDefaultController/desiredSize}} property of the stream's associated controller object.
Specifications should <em>not</em> use this on streams they did not create.

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableStream]].
  1. Let _state_ be _stream_.[[state]].
  1. If _state_ is `"errored"`, return *null*.
  1. If _state_ is `"closed"`, return *0*.
  1. Return _controller_.[[strategyHWM]] − _controller_.[[queueTotalSize]].
</emu-alg>

<h4 id="rs-default-controller-has-backpressure" aoid="ReadableStreamDefaultControllerHasBackpressure"
nothrow>ReadableStreamDefaultControllerHasBackpressure ( <var>controller</var> )</h4>

This abstract operation is used in the implementation of TransformStream.

<emu-alg>
  1. If ! ReadableStreamDefaultControllerShouldCallPull(_controller_) is *true*, return *false*.
  1. Otherwise, return *true*.
</emu-alg>

<h4 id="readable-stream-default-controller-can-close-or-enqueue" aoid="ReadableStreamDefaultControllerCanCloseOrEnqueue"
nothrow>ReadableStreamDefaultControllerCanCloseOrEnqueue ( <var>controller</var> )</h4>

<emu-alg>
  1. Let _state_ be _controller_.[[controlledReadableStream]].[[state]].
  1. If _controller_.[[closeRequested]] is *false* and _state_ is `"readable"`, return *true*.
  1. Otherwise, return *false*.
</emu-alg>

<div class="note">
  The case where <var>stream</var>.\[[closeRequested]] is <emu-val>false</emu-val>, but <var>stream</var>.\[[state]] is
  not <code>"readable"</code>, happens when the stream is errored via {{ReadableStreamDefaultController/error(e)}}, or
  when it is closed without its controller's <code>close</code> method ever being called: e.g., if the stream was closed
  by a call to {{ReadableStream/cancel(reason)}}.
</div>

<h4 id="set-up-readable-stream-default-controller" aoid="SetUpReadableStreamDefaultController"
throws>SetUpReadableStreamDefaultController(<var>stream</var>, <var>controller</var>, <var>startAlgorithm</var>,
<var>pullAlgorithm</var>, <var>cancelAlgorithm</var>, <var>highWaterMark</var>, <var>sizeAlgorithm</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[readableStreamController]] is *undefined*.
  1. Set _controller_.[[controlledReadableStream]] to _stream_.
  1. Set _controller_.[[queue]] and _controller_.[[queueTotalSize]] to *undefined*, then perform !
     ResetQueue(_controller_).
  1. Set _controller_.[[started]], _controller_.[[closeRequested]], _controller_.[[pullAgain]], and
     _controller_.[[pulling]] to *false*.
  1. Set _controller_.[[strategySizeAlgorithm]] to _sizeAlgorithm_ and _controller_.[[strategyHWM]] to _highWaterMark_.
  1. Set _controller_.[[pullAlgorithm]] to _pullAlgorithm_.
  1. Set _controller_.[[cancelAlgorithm]] to _cancelAlgorithm_.
  1. Set _stream_.[[readableStreamController]] to _controller_.
  1. Let _startResult_ be the result of performing _startAlgorithm_. (This may throw an exception.)
  1. Let _startPromise_ be <a>a promise resolved with</a> _startResult_.
  1. <a>Upon fulfillment</a>  of _startPromise_,
    1. Set _controller_.[[started]] to *true*.
    1. Assert: _controller_.[[pulling]] is *false*.
    1. Assert: _controller_.[[pullAgain]] is *false*.
    1. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(_controller_).
  1. <a>Upon rejection</a> of _startPromise_ with reason _r_,
    1. Perform ! ReadableStreamDefaultControllerError(_controller_, _r_).
</emu-alg>

<h4 id="set-up-readable-stream-default-controller-from-underlying-source"
aoid="SetUpReadableStreamDefaultControllerFromUnderlyingSource"
throws>SetUpReadableStreamDefaultControllerFromUnderlyingSource(<var>stream</var>, <var>underlyingSource</var>,
<var>highWaterMark</var>, <var>sizeAlgorithm</var> )</h4>

<emu-alg>
  1. Assert: _underlyingSource_ is not *undefined*.
  1. Let _controller_ be ObjectCreate(the original value of `<a idl>ReadableStreamDefaultController</a>`'s `prototype`
     property).
  1. Let _startAlgorithm_ be the following steps:
    1. Return ? InvokeOrNoop(_underlyingSource_, `"start"`, « _controller_ »).
  1. Let _pullAlgorithm_ be ? CreateAlgorithmFromUnderlyingMethod(_underlyingSource_, `"pull"`, *0*, « _controller_ »).
  1. Let _cancelAlgorithm_ be ? CreateAlgorithmFromUnderlyingMethod(_underlyingSource_, `"cancel"`, *1*, « »).
  1. Perform ? SetUpReadableStreamDefaultController(_stream_, _controller_, _startAlgorithm_, _pullAlgorithm_,
     _cancelAlgorithm_, _highWaterMark_, _sizeAlgorithm_).
</emu-alg>

<h3 id="rbs-controller-class" interface lt="ReadableByteStreamController">Class
<code>ReadableByteStreamController</code></h3>

The {{ReadableByteStreamController}} class has methods that allow control of a {{ReadableStream}}'s state and
<a>internal queue</a>. When constructing a {{ReadableStream}}, the <a>underlying byte source</a> is given a
corresponding {{ReadableByteStreamController}} instance to manipulate.

<h4 id="rbs-controller-class-definition">Class definition</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{ReadableByteStreamController}} class in something close to the syntax of [[!ECMASCRIPT]], it
would look like

<pre><code class="lang-javascript">
  class ReadableByteStreamController {
    <a href="#rbs-controller-constructor">constructor</a>() // always throws

    get <a href="#rbs-controller-byob-request">byobRequest</a>()
    get <a href="#rbs-controller-desired-size">desiredSize</a>()

    <a href="#rbs-controller-close">close</a>()
    <a href="#rbs-controller-enqueue">enqueue</a>(chunk)
    <a href="#rbs-controller-error">error</a>(e)
  }
</code></pre>

</div>

<h4 id="rbs-controller-internal-slots">Internal slots</h4>

Instances of {{ReadableByteStreamController}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[autoAllocateChunkSize]]
    <td class="non-normative">A positive integer, when the automatic buffer allocation feature is enabled. In that case,
      this value specifies the size of buffer to allocate. It is <emu-val>undefined</emu-val> otherwise.
  </tr>
  <tr>
    <td>\[[byobRequest]]
    <td class="non-normative">A {{ReadableStreamBYOBRequest}} instance representing the current BYOB pull request,
      or <emu-val>undefined</emu-val> if there are no pending requests
  </tr>
  <tr>
    <td>\[[cancelAlgorithm]]
    <td class="non-normative">A promise-returning algorithm, taking one argument (the cancel reason), which communicates
      a requested cancelation to the <a>underlying source</a>
  </tr>
  <tr>
    <td>\[[closeRequested]]
    <td class="non-normative">A boolean flag indicating whether the stream has been closed by its <a>underlying byte
      source</a>, but still has <a>chunks</a> in its internal queue that have not yet been read
  </tr>
  <tr>
    <td>\[[controlledReadableByteStream]]
    <td class="non-normative">The {{ReadableStream}} instance controlled
  </tr>
  <tr>
    <td>\[[pullAgain]]
    <td class="non-normative">A boolean flag set to <emu-val>true</emu-val> if the stream's mechanisms requested a call
      to the <a>underlying byte source</a>'s {{underlying source/pull()}} method to pull more data, but the pull could
      not yet be done since a previous call is still executing
  </tr>
  <tr>
    <td>\[[pullAlgorithm]]
    <td class="non-normative">A promise-returning algorithm that pulls data from the <a>underlying source</a>
  </tr>
  <tr>
    <td>\[[pulling]]
    <td class="non-normative">A boolean flag set to <emu-val>true</emu-val> while the <a>underlying byte source</a>'s
      {{underlying source/pull()}} method is executing and has not yet fulfilled, used to prevent reentrant calls
  </tr>
  <tr>
    <td>\[[pendingPullIntos]]
    <td class="non-normative">A List of descriptors representing pending BYOB pull requests
  </tr>
  <tr>
    <td>\[[queue]]
    <td class="non-normative">A List representing the stream's internal queue of <a>chunks</a>
  </tr>
  <tr>
    <td>\[[queueTotalSize]]
    <td class="non-normative">The total size (in bytes) of all the chunks stored in \[[queue]]
  </tr>
  <tr>
    <td>\[[started]]
    <td class="non-normative">A boolean flag indicating whether the <a>underlying source</a> has finished starting
  </tr>
  <tr>
    <td>\[[strategyHWM]]
    <td class="non-normative">A number supplied to the constructor as part of the stream's <a>queuing strategy</a>,
      indicating the point at which the stream will apply <a>backpressure</a> to its <a>underlying byte source</a>
  </tr>
</table>

<div class="note">
  <p>Although {{ReadableByteStreamController}} instances have \[[queue]] and \[[queueTotalSize]] slots, we do not use
  most of the abstract operations in [[#queue-with-sizes]] on them, as the way in which we manipulate this queue is
  rather different than the others in the spec. Instead, we update the two slots together manually.</p>

  <p>This might be cleaned up in a future spec refactoring.</p>
</div>

<h4 id="rbs-controller-constructor" constructor for="ReadableByteStreamController"
lt="ReadableByteStreamController()">new
ReadableByteStreamController()</h4>

<div class="note">
  The <code>ReadableByteStreamController</code> constructor cannot be used directly;
  {{ReadableByteStreamController}} instances are created automatically during {{ReadableStream}} construction.
</div>

<emu-alg>
  1. Throw a *TypeError* exception.
</emu-alg>

<h4 id="rbs-controller-prototype">Properties of the {{ReadableByteStreamController}} prototype</h4>

<h5 id="rbs-controller-byob-request" attribute for="ReadableByteStreamController" lt="byobRequest">get byobRequest</h5>

<div class="note">
  The <code>byobRequest</code> getter returns the current BYOB pull request.
</div>

<emu-alg>
  1. If ! IsReadableByteStreamController(*this*) is *false*, throw a *TypeError* exception.
  1. If *this*.[[byobRequest]] is *undefined* and *this*.[[pendingPullIntos]] is not empty,
    1. Let _firstDescriptor_ be the first element of *this*.[[pendingPullIntos]].
    1. Let _view_ be ! Construct(<a idl>%Uint8Array%</a>, « _firstDescriptor_.[[buffer]],
       _firstDescriptor_.[[byteOffset]] + _firstDescriptor_.[[bytesFilled]], _firstDescriptor_.[[byteLength]] −
       _firstDescriptor_.[[bytesFilled]] »).
    1. Let _byobRequest_ be ObjectCreate(the original value of `<a idl>ReadableStreamBYOBRequest</a>`'s `prototype`
      property).
    1. Perform ! SetUpReadableStreamBYOBRequest(_byobRequest_, *this*, _view_).
    1. Set *this*.[[byobRequest]] to _byobRequest_.
  1. Return *this*.[[byobRequest]].
</emu-alg>

<h5 id="rbs-controller-desired-size" attribute for="ReadableByteStreamController" lt="desiredSize">get desiredSize</h5>

<div class="note">
  The <code>desiredSize</code> getter returns the <a lt="desired size to fill a stream's internal queue">desired size
  to fill the controlled stream's internal queue</a>. It can be negative, if the queue is over-full. An <a>underlying
  source</a> ought to use this information to determine when and how to apply <a>backpressure</a>.
</div>

<emu-alg>
  1. If ! IsReadableByteStreamController(*this*) is *false*, throw a *TypeError* exception.
  1. Return ! ReadableByteStreamControllerGetDesiredSize(*this*).
</emu-alg>

<h5 id="rbs-controller-close" method for="ReadableByteStreamController">close()</h5>

<div class="note">
  The <code>close</code> method will close the controlled readable stream. <a>Consumers</a> will still be able to read
  any previously-enqueued <a>chunks</a> from the stream, but once those are read, the stream will become closed.
</div>

<emu-alg>
  1. If ! IsReadableByteStreamController(*this*) is *false*, throw a *TypeError* exception.
  1. If *this*.[[closeRequested]] is *true*, throw a *TypeError* exception.
  1. If *this*.[[controlledReadableByteStream]].[[state]] is not `"readable"`, throw a *TypeError* exception.
  1. Perform ? ReadableByteStreamControllerClose(*this*).
</emu-alg>

<h5 id="rbs-controller-enqueue" method for="ReadableByteStreamController">enqueue(<var>chunk</var>)</h5>

<div class="note">
  The <code>enqueue</code> method will enqueue a given <a>chunk</a> in the controlled readable stream.
</div>

<emu-alg>
  1. If ! IsReadableByteStreamController(*this*) is *false*, throw a *TypeError* exception.
  1. If *this*.[[closeRequested]] is *true*, throw a *TypeError* exception.
  1. If *this*.[[controlledReadableByteStream]].[[state]] is not `"readable"`, throw a *TypeError* exception.
  1. If Type(_chunk_) is not Object, throw a *TypeError* exception.
  1. If _chunk_ does not have a [[ViewedArrayBuffer]] internal slot, throw a *TypeError* exception.
  1. If ! IsDetachedBuffer(_chunk_.[[ViewedArrayBuffer]]) is *true*, throw a *TypeError* exception.
  1. Return ! ReadableByteStreamControllerEnqueue(*this*, _chunk_).
</emu-alg>

<h5 id="rbs-controller-error" method for="ReadableByteStreamController">error(<var>e</var>)</h5>

<div class="note">
  The <code>error</code> method will error the readable stream, making all future interactions with it fail with the
  given error <code>e</code>.
</div>

<emu-alg>
  1. If ! IsReadableByteStreamController(*this*) is *false*, throw a *TypeError* exception.
  1. Perform ! ReadableByteStreamControllerError(*this*, _e_).
</emu-alg>

<h4 id="rbs-controller-internal-methods">Readable stream BYOB controller internal methods</h4>

The following are additional internal methods implemented by each {{ReadableByteStreamController}} instance. The
readable stream implementation will polymorphically call to either these or their counterparts for default controllers.

<h5 id="rbs-controller-private-cancel"><a abstract-op>\[[CancelSteps]]</a>(<var>reason</var>)</h5>

<emu-alg>
  1. If *this*.[[pendingPullIntos]] is not empty,
    1. Let _firstDescriptor_ be the first element of *this*.[[pendingPullIntos]].
    1. Set _firstDescriptor_.[[bytesFilled]] to *0*.
  1. Perform ! ResetQueue(*this*).
  1. Let _result_ be the result of performing *this*.[[cancelAlgorithm]], passing in _reason_.
  1. Perform ! ReadableByteStreamControllerClearAlgorithms(*this*).
  1. Return _result_.
</emu-alg>

<h5 id="rbs-controller-private-pull"><a abstract-op>\[[PullSteps]]</a>( )</h5>

<emu-alg>
  1. Let _stream_ be *this*.[[controlledReadableByteStream]].
  1. Assert: ! ReadableStreamHasDefaultReader(_stream_) is *true*.
  1. If *this*.[[queueTotalSize]] > *0*,
    1. Assert: ! ReadableStreamGetNumReadRequests(_stream_) is *0*.
    1. Let _entry_ be the first element of *this*.[[queue]].
    1. Remove _entry_ from *this*.[[queue]], shifting all other elements downward (so that the second becomes the
       first, and so on).
    1. Set *this*.[[queueTotalSize]] to *this*.[[queueTotalSize]] − _entry_.[[byteLength]].
    1. Perform ! ReadableByteStreamControllerHandleQueueDrain(*this*).
    1. Let _view_ be ! Construct(<a idl>%Uint8Array%</a>, « _entry_.[[buffer]], _entry_.[[byteOffset]],
       _entry_.[[byteLength]] »).
    1. Return <a>a promise resolved with</a> ! ReadableStreamCreateReadResult(_view_, *false*,
       _stream_.[[reader]].[[forAuthorCode]]).
  1. Let _autoAllocateChunkSize_ be *this*.[[autoAllocateChunkSize]].
  1. If _autoAllocateChunkSize_ is not *undefined*,
    1. Let _buffer_ be Construct(%ArrayBuffer%, « _autoAllocateChunkSize_ »).
    1. If _buffer_ is an abrupt completion, return <a>a promise rejected with</a> _buffer_.[[Value]].
    1. Let _pullIntoDescriptor_ be Record {[[buffer]]: _buffer_.[[Value]], [[byteOffset]]: *0*, [[byteLength]]:
       _autoAllocateChunkSize_, [[bytesFilled]]: *0*, [[elementSize]]: *1*, [[ctor]]: <a idl>%Uint8Array%</a>,
       [[readerType]]: `"default"`}.
    1. Append _pullIntoDescriptor_ as the last element of *this*.[[pendingPullIntos]].
  1. Let _promise_ be ! ReadableStreamAddReadRequest(_stream_).
  1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(*this*).
  1. Return _promise_.
</emu-alg>

<h3 id="rs-byob-request-class" interface lt="ReadableStreamBYOBRequest">Class
<code>ReadableStreamBYOBRequest</code></h3>

The {{ReadableStreamBYOBRequest}} class represents a pull into request in a {{ReadableByteStreamController}}.

<h4 id="rs-byob-request-class-definition">Class definition</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{ReadableStreamBYOBRequest}} class in something close to the syntax of [[!ECMASCRIPT]], it
would look like

<pre><code class="lang-javascript">
  class ReadableStreamBYOBRequest {
    <a href="#rs-byob-request-constructor">constructor</a>(controller, view)

    get <a href="#rs-byob-request-view">view</a>()

    <a href="#rs-byob-request-respond">respond</a>(bytesWritten)
    <a href="#rs-byob-request-respond-with-new-view">respondWithNewView</a>(view)
  }
</code></pre>

</div>

<h4 id="rs-byob-request-internal-slots">Internal slots</h4>

Instances of {{ReadableStreamBYOBRequest}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[associatedReadableByteStreamController]]
    <td class="non-normative">The parent {{ReadableByteStreamController}} instance
  </tr>
  <tr>
    <td>\[[view]]
    <td class="non-normative">A <a>typed array</a> representing the destination region to which the controller can write
      generated data
  </tr>
</table>

<h4 id="rs-byob-request-constructor" constructor for="ReadableStreamBYOBRequest"
lt="ReadableStreamBYOBRequest(controller, view)">new
ReadableStreamBYOBRequest()</h4>

<emu-alg>
  1. Throw a *TypeError* exception.
</emu-alg>

<h4 id="rs-byob-request-prototype">Properties of the {{ReadableStreamBYOBRequest}} prototype</h4>

<h5 id="rs-byob-request-view" attribute for="ReadableStreamBYOBRequest" lt="view">get view</h5>

<emu-alg>
  1. If ! IsReadableStreamBYOBRequest(*this*) is *false*, throw a *TypeError* exception.
  1. Return *this*.[[view]].
</emu-alg>

<h5 id="rs-byob-request-respond" method for="ReadableStreamBYOBRequest">respond(<var>bytesWritten</var>)</h5>

<emu-alg>
  1. If ! IsReadableStreamBYOBRequest(*this*) is *false*, throw a *TypeError* exception.
  1. If *this*.[[associatedReadableByteStreamController]] is *undefined*, throw a *TypeError* exception.
  1. If ! IsDetachedBuffer(*this*.[[view]].[[ViewedArrayBuffer]]) is *true*, throw a *TypeError* exception.
  1. Return ? ReadableByteStreamControllerRespond(*this*.[[associatedReadableByteStreamController]], _bytesWritten_).
</emu-alg>

<h5 id="rs-byob-request-respond-with-new-view" method
for="ReadableStreamBYOBRequest">respondWithNewView(<var>view</var>)</h5>

<emu-alg>
  1. If ! IsReadableStreamBYOBRequest(*this*) is *false*, throw a *TypeError* exception.
  1. If *this*.[[associatedReadableByteStreamController]] is *undefined*, throw a *TypeError* exception.
  1. If Type(_view_) is not Object, throw a *TypeError* exception.
  1. If _view_ does not have a [[ViewedArrayBuffer]] internal slot, throw a *TypeError* exception.
  1. If ! IsDetachedBuffer(_view_.[[ViewedArrayBuffer]]) is *true*, throw a *TypeError* exception.
  1. Return ? ReadableByteStreamControllerRespondWithNewView(*this*.[[associatedReadableByteStreamController]], _view_).
</emu-alg>

<h3 id="rbs-controller-abstract-ops">Readable stream BYOB controller abstract operations</h3>

<h4 id="is-readable-stream-byob-request" aoid="IsReadableStreamBYOBRequest" nothrow>IsReadableStreamBYOBRequest (
<var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have an [[associatedReadableByteStreamController]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>


<h4 id="is-readable-byte-stream-controller" aoid="IsReadableByteStreamController" nothrow>IsReadableByteStreamController
( <var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have an [[controlledReadableByteStream]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="readable-byte-stream-controller-call-pull-if-needed" aoid="ReadableByteStreamControllerCallPullIfNeeded"
nothrow>ReadableByteStreamControllerCallPullIfNeeded ( <var>controller</var> )</h4>

<emu-alg>
  1. Let _shouldPull_ be ! ReadableByteStreamControllerShouldCallPull(_controller_).
  1. If _shouldPull_ is *false*, return.
  1. If _controller_.[[pulling]] is *true*,
    1. Set _controller_.[[pullAgain]] to *true*.
    1. Return.
  1. Assert: _controller_.[[pullAgain]] is *false*.
  1. Set _controller_.[[pulling]] to *true*.
  1. Let _pullPromise_ be the result of performing _controller_.[[pullAlgorithm]].
  1. <a>Upon fulfillment</a> of _pullPromise_,
    1. Set _controller_.[[pulling]] to *false*.
    1. If _controller_.[[pullAgain]] is *true*,
      1. Set _controller_.[[pullAgain]] to *false*.
      1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(_controller_).
  1. <a>Upon rejection</a> of _pullPromise_ with reason _e_,
    1. Perform ! ReadableByteStreamControllerError(_controller_, _e_).
</emu-alg>

<h4 id="readable-byte-stream-controller-clear-algorithms" aoid="ReadableByteStreamControllerClearAlgorithms"
throws>ReadableByteStreamControllerClearAlgorithms ( <var>controller</var> )</h4>

This abstract operation is called once the stream is closed or errored and the algorithms will not be executed any more.
By removing the algorithm references it permits the <a>underlying source</a> object to be garbage collected even if the
{{ReadableStream}} itself is still referenced.

<p class="note">The results of this algorithm are not currently observable, but could become so if JavaScript eventually
adds <a href="https://github.com/tc39/proposal-weakrefs/">weak references</a>. But even without that factor,
implementations will likely want to include similar steps.</p>

<emu-alg>
  1. Set _controller_.[[pullAlgorithm]] to *undefined*.
  1. Set _controller_.[[cancelAlgorithm]] to *undefined*.
</emu-alg>

<h4 id="readable-byte-stream-controller-clear-pending-pull-intos"
aoid="ReadableByteStreamControllerClearPendingPullIntos" nothrow>ReadableByteStreamControllerClearPendingPullIntos (
<var>controller</var> )</h4>

<emu-alg>
  1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(_controller_).
  1. Set _controller_.[[pendingPullIntos]] to a new empty List.
</emu-alg>

<h4 id="readable-byte-stream-controller-close" aoid="ReadableByteStreamControllerClose"
throws>ReadableByteStreamControllerClose ( <var>controller</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableByteStream]].
  1. Assert: _controller_.[[closeRequested]] is *false*.
  1. Assert: _stream_.[[state]] is `"readable"`.
  1. If _controller_.[[queueTotalSize]] > *0*,
    1. Set _controller_.[[closeRequested]] to *true*.
    1. Return.
  1. If _controller_.[[pendingPullIntos]] is not empty,
    1. Let _firstPendingPullInto_ be the first element of _controller_.[[pendingPullIntos]].
    1. If _firstPendingPullInto_.[[bytesFilled]] > *0*,
      1. Let _e_ be a new *TypeError* exception.
      1. Perform ! ReadableByteStreamControllerError(_controller_, _e_).
      1. Throw _e_.
  1. Perform ! ReadableByteStreamControllerClearAlgorithms(_controller_).
  1. Perform ! ReadableStreamClose(_stream_).
</emu-alg>

<h4 id="readable-byte-stream-controller-commit-pull-into-descriptor"
aoid="ReadableByteStreamControllerCommitPullIntoDescriptor" nothrow>ReadableByteStreamControllerCommitPullIntoDescriptor
( <var>stream</var>, <var>pullIntoDescriptor</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[state]] is not `"errored"`.
  1. Let _done_ be *false*.
  1. If _stream_.[[state]] is `"closed"`,
    1. Assert: _pullIntoDescriptor_.[[bytesFilled]] is *0*.
    1. Set _done_ to *true*.
  1. Let _filledView_ be ! ReadableByteStreamControllerConvertPullIntoDescriptor(_pullIntoDescriptor_).
  1. If _pullIntoDescriptor_.[[readerType]] is `"default"`,
    1. Perform ! ReadableStreamFulfillReadRequest(_stream_, _filledView_, _done_).
  1. Otherwise,
    1. Assert: _pullIntoDescriptor_.[[readerType]] is `"byob"`.
    1. Perform ! ReadableStreamFulfillReadIntoRequest(_stream_, _filledView_, _done_).
</emu-alg>

<h4 id="readable-byte-stream-controller-convert-pull-into-descriptor"
aoid="ReadableByteStreamControllerConvertPullIntoDescriptor"
nothrow>ReadableByteStreamControllerConvertPullIntoDescriptor ( <var>pullIntoDescriptor</var> )</h4>

<emu-alg>
  1. Let _bytesFilled_ be _pullIntoDescriptor_.[[bytesFilled]].
  1. Let _elementSize_ be _pullIntoDescriptor_.[[elementSize]].
  1. Assert: _bytesFilled_ ≤ _pullIntoDescriptor_.[[byteLength]].
  1. Assert: _bytesFilled_ mod _elementSize_ is *0*.
  1. Return ! Construct(_pullIntoDescriptor_.[[ctor]], « _pullIntoDescriptor_.[[buffer]],
     _pullIntoDescriptor_.[[byteOffset]], _bytesFilled_ ÷ _elementSize_ »).
</emu-alg>

<h4 id="readable-byte-stream-controller-enqueue" aoid="ReadableByteStreamControllerEnqueue"
nothrow>ReadableByteStreamControllerEnqueue ( <var>controller</var>, <var>chunk</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableByteStream]].
  1. Assert: _controller_.[[closeRequested]] is *false*.
  1. Assert: _stream_.[[state]] is `"readable"`.
  1. Let _buffer_ be _chunk_.[[ViewedArrayBuffer]].
  1. Let _byteOffset_ be _chunk_.[[ByteOffset]].
  1. Let _byteLength_ be _chunk_.[[ByteLength]].
  1. Let _transferredBuffer_ be ! TransferArrayBuffer(_buffer_).
  1. If ! ReadableStreamHasDefaultReader(_stream_) is *true*
    1. If ! ReadableStreamGetNumReadRequests(_stream_) is *0*,
      1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(_controller_, _transferredBuffer_, _byteOffset_,
         _byteLength_).
    1. Otherwise,
      1. Assert: _controller_.[[queue]] is empty.
      1. Let _transferredView_ be ! Construct(<a idl>%Uint8Array%</a>, « _transferredBuffer_, _byteOffset_,
         _byteLength_ »).
      1. Perform ! ReadableStreamFulfillReadRequest(_stream_, _transferredView_, *false*).
  1. Otherwise, if ! ReadableStreamHasBYOBReader(_stream_) is *true*,
    1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(_controller_, _transferredBuffer_, _byteOffset_,
       _byteLength_).
    1. Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(_controller_).
  1. Otherwise,
    1. Assert: ! IsReadableStreamLocked(_stream_) is *false*.
    1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(_controller_, _transferredBuffer_, _byteOffset_,
       _byteLength_).
  1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(_controller_).
</emu-alg>

<h4 id="readable-byte-stream-controller-enqueue-chunk-to-queue" aoid="ReadableByteStreamControllerEnqueueChunkToQueue"
nothrow>ReadableByteStreamControllerEnqueueChunkToQueue ( <var>controller</var>, <var ignore>buffer</var>,
<var ignore>byteOffset</var>, <var ignore>byteLength</var> )</h4>

<emu-alg>
  1. Append Record {[[buffer]]: _buffer_, [[byteOffset]]: _byteOffset_, [[byteLength]]: _byteLength_} as the last
     element of _controller_.[[queue]].
  1. Add _byteLength_ to _controller_.[[queueTotalSize]].
</emu-alg>

<h4 id="readable-byte-stream-controller-error" aoid="ReadableByteStreamControllerError"
nothrow>ReadableByteStreamControllerError ( <var>controller</var>, <var>e</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableByteStream]].
  1. If _stream_.[[state]] is not `"readable"`, return.
  1. Perform ! ReadableByteStreamControllerClearPendingPullIntos(_controller_).
  1. Perform ! ResetQueue(_controller_).
  1. Perform ! ReadableByteStreamControllerClearAlgorithms(_controller_).
  1. Perform ! ReadableStreamError(_stream_, _e_).
</emu-alg>

<h4 id="readable-byte-stream-controller-fill-head-pull-into-descriptor"
aoid="ReadableByteStreamControllerFillHeadPullIntoDescriptor"
nothrow>ReadableByteStreamControllerFillHeadPullIntoDescriptor ( <var>controller</var>, <var>size</var>,
<var>pullIntoDescriptor</var> )</h4>

<emu-alg>
  1. Assert: either _controller_.[[pendingPullIntos]] is empty, or the first element of
     _controller_.[[pendingPullIntos]] is _pullIntoDescriptor_.
  1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(_controller_).
  1. Set _pullIntoDescriptor_.[[bytesFilled]] to _pullIntoDescriptor_.[[bytesFilled]] + _size_.
</emu-alg>

<h4 id="readable-byte-stream-controller-fill-pull-into-descriptor-from-queue"
aoid="ReadableByteStreamControllerFillPullIntoDescriptorFromQueue"
nothrow>ReadableByteStreamControllerFillPullIntoDescriptorFromQueue ( <var>controller</var>,
<var>pullIntoDescriptor</var> )</h4>

<emu-alg>
  1. Let _elementSize_ be _pullIntoDescriptor_.[[elementSize]].
  1. Let _currentAlignedBytes_ be _pullIntoDescriptor_.[[bytesFilled]] − (_pullIntoDescriptor_.[[bytesFilled]] mod
     _elementSize_).
  1. Let _maxBytesToCopy_ be min(_controller_.[[queueTotalSize]], _pullIntoDescriptor_.[[byteLength]] −
     _pullIntoDescriptor_.[[bytesFilled]]).
  1. Let _maxBytesFilled_ be _pullIntoDescriptor_.[[bytesFilled]] + _maxBytesToCopy_.
  1. Let _maxAlignedBytes_ be _maxBytesFilled_ − (_maxBytesFilled_ mod _elementSize_).
  1. Let _totalBytesToCopyRemaining_ be _maxBytesToCopy_.
  1. Let _ready_ be *false*.
  1. If _maxAlignedBytes_ > _currentAlignedBytes_,
    1. Set _totalBytesToCopyRemaining_ to _maxAlignedBytes_ − _pullIntoDescriptor_.[[bytesFilled]].
    1. Set _ready_ to *true*.
  1. Let _queue_ be _controller_.[[queue]].
  1. Repeat the following steps while _totalBytesToCopyRemaining_ > *0*,
    1. Let _headOfQueue_ be the first element of _queue_.
    1. Let _bytesToCopy_ be min(_totalBytesToCopyRemaining_, _headOfQueue_.[[byteLength]]).
    1. Let _destStart_ be _pullIntoDescriptor_.[[byteOffset]] + _pullIntoDescriptor_.[[bytesFilled]].
    1. Perform ! CopyDataBlockBytes(_pullIntoDescriptor_.[[buffer]].[[ArrayBufferData]], _destStart_,
       _headOfQueue_.[[buffer]].[[ArrayBufferData]], _headOfQueue_.[[byteOffset]], _bytesToCopy_).
    1. If _headOfQueue_.[[byteLength]] is _bytesToCopy_,
      1. Remove the first element of _queue_, shifting all other elements downward (so that the second becomes the
         first, and so on).
    1. Otherwise,
      1. Set _headOfQueue_.[[byteOffset]] to _headOfQueue_.[[byteOffset]] + _bytesToCopy_.
      1. Set _headOfQueue_.[[byteLength]] to _headOfQueue_.[[byteLength]] − _bytesToCopy_.
    1. Set _controller_.[[queueTotalSize]] to _controller_.[[queueTotalSize]] − _bytesToCopy_.
    1. Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(_controller_, _bytesToCopy_,
       _pullIntoDescriptor_).
    1. Set _totalBytesToCopyRemaining_ to _totalBytesToCopyRemaining_ − _bytesToCopy_.
  1. If _ready_ is *false*,
    1. Assert: _controller_.[[queueTotalSize]] is *0*.
    1. Assert: _pullIntoDescriptor_.[[bytesFilled]] > *0*.
    1. Assert: _pullIntoDescriptor_.[[bytesFilled]] < _pullIntoDescriptor_.[[elementSize]].
  1. Return _ready_.
</emu-alg>

<h4 id="readable-byte-stream-controller-get-desired-size" aoid="ReadableByteStreamControllerGetDesiredSize"
nothrow>ReadableByteStreamControllerGetDesiredSize ( <var>controller</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableByteStream]].
  1. Let _state_ be _stream_.[[state]].
  1. If _state_ is `"errored"`, return *null*.
  1. If _state_ is `"closed"`, return *0*.
  1. Return _controller_.[[strategyHWM]] − _controller_.[[queueTotalSize]].
</emu-alg>

<h4 id="readable-byte-stream-controller-handle-queue-drain" aoid="ReadableByteStreamControllerHandleQueueDrain"
nothrow>ReadableByteStreamControllerHandleQueueDrain ( <var>controller</var> )</h4>

<emu-alg>
  1. Assert: _controller_.[[controlledReadableByteStream]].[[state]] is `"readable"`.
  1. If _controller_.[[queueTotalSize]] is *0* and _controller_.[[closeRequested]] is *true*,
    1. Perform ! ReadableByteStreamControllerClearAlgorithms(_controller_).
    1. Perform ! ReadableStreamClose(_controller_.[[controlledReadableByteStream]]).
  1. Otherwise,
    1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(_controller_).
</emu-alg>

<h4 id="readable-byte-stream-controller-invalidate-byob-request"
aoid="ReadableByteStreamControllerInvalidateBYOBRequest" nothrow>ReadableByteStreamControllerInvalidateBYOBRequest (
<var>controller</var> )</h4>

<emu-alg>
  1. If _controller_.[[byobRequest]] is *undefined*, return.
  1. Set _controller_.[[byobRequest]].[[associatedReadableByteStreamController]] to *undefined*.
  1. Set _controller_.[[byobRequest]].[[view]] to *undefined*.
  1. Set _controller_.[[byobRequest]] to *undefined*.
</emu-alg>

<h4 id="readable-byte-stream-controller-process-pull-into-descriptors-using-queue"
aoid="ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue"
nothrow>ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue ( <var>controller</var> )</h4>

<emu-alg>
  1. Assert: _controller_.[[closeRequested]] is *false*.
  1. Repeat the following steps while _controller_.[[pendingPullIntos]] is not empty,
    1. If _controller_.[[queueTotalSize]] is *0*, return.
    1. Let _pullIntoDescriptor_ be the first element of _controller_.[[pendingPullIntos]].
    1. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(_controller_, _pullIntoDescriptor_) is *true*,
      1. Perform ! ReadableByteStreamControllerShiftPendingPullInto(_controller_).
      1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(_controller_.[[controlledReadableByteStream]],
         _pullIntoDescriptor_).
</emu-alg>

<h4 id="readable-byte-stream-controller-pull-into" aoid="ReadableByteStreamControllerPullInto"
nothrow>ReadableByteStreamControllerPullInto ( <var>controller</var>, <var>view</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableByteStream]].
  1. Let _elementSize_ be 1.
  1. Let _ctor_ be %DataView%.
  1. If _view_ has a [[TypedArrayName]] internal slot (i.e., it is not a `<a idl>DataView</a>`),
    1. Set _elementSize_ to the element size specified in <a>the typed array constructors table</a> for
       _view_.[[TypedArrayName]].
    1. Set _ctor_ to the constructor specified in <a>the typed array constructors table</a> for
       _view_.[[TypedArrayName]].
  1. Let _byteOffset_ be _view_.[[ByteOffset]].
  1. Let _byteLength_ be _view_.[[ByteLength]].
  1. Let _buffer_ be ! TransferArrayBuffer(_view_.[[ViewedArrayBuffer]]).
  1. Let _pullIntoDescriptor_ be Record {[[buffer]]: _buffer_, [[byteOffset]]: _byteOffset_,
     [[byteLength]]: _byteLength_, [[bytesFilled]]: *0*, [[elementSize]]: _elementSize_,
     [[ctor]]: _ctor_, [[readerType]]: `"byob"`}.
  1. If _controller_.[[pendingPullIntos]] is not empty,
    1. Append _pullIntoDescriptor_ as the last element of _controller_.[[pendingPullIntos]].
    1. Return ! ReadableStreamAddReadIntoRequest(_stream_).
  1. If _stream_.[[state]] is `"closed"`,
    1. Let _emptyView_ be ! Construct(_ctor_, « _pullIntoDescriptor_.[[buffer]], _pullIntoDescriptor_.[[byteOffset]], *0* »).
    1. Return <a>a promise resolved with</a> ! ReadableStreamCreateReadResult(_emptyView_, *true*,
       _stream_.[[reader]].[[forAuthorCode]]).
  1. If _controller_.[[queueTotalSize]] > *0*,
    1. If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(_controller_, _pullIntoDescriptor_) is *true*,
      1. Let _filledView_ be ! ReadableByteStreamControllerConvertPullIntoDescriptor(_pullIntoDescriptor_).
      1. Perform ! ReadableByteStreamControllerHandleQueueDrain(_controller_).
      1. Return <a>a promise resolved with</a> ! ReadableStreamCreateReadResult(_filledView_, *false*,
         _stream_.[[reader]].[[forAuthorCode]]).
    1. If _controller_.[[closeRequested]] is *true*,
      1. Let _e_ be a *TypeError* exception.
      1. Perform ! ReadableByteStreamControllerError(_controller_, _e_).
      1. Return <a>a promise rejected with</a> _e_.
  1. Append _pullIntoDescriptor_ as the last element of _controller_.[[pendingPullIntos]].
  1. Let _promise_ be ! ReadableStreamAddReadIntoRequest(_stream_).
  1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(_controller_).
  1. Return _promise_.
</emu-alg>

<h4 id="readable-byte-stream-controller-respond" aoid="ReadableByteStreamControllerRespond"
throws>ReadableByteStreamControllerRespond ( <var>controller</var>, <var>bytesWritten</var> )</h4>

<emu-alg>
  1. Let _bytesWritten_ be ? ToNumber(_bytesWritten_).
  1. If ! IsFiniteNonNegativeNumber(_bytesWritten_) is *false*,
    1. Throw a *RangeError* exception.
  1. Assert: _controller_.[[pendingPullIntos]] is not empty.
  1. Perform ? ReadableByteStreamControllerRespondInternal(_controller_, _bytesWritten_).
</emu-alg>

<h4 id="readable-byte-stream-controller-respond-in-closed-state" aoid="ReadableByteStreamControllerRespondInClosedState"
nothrow>ReadableByteStreamControllerRespondInClosedState ( <var>controller</var>,
<var ignore>firstDescriptor</var> )</h4>

<emu-alg>
  1. Set _firstDescriptor_.[[buffer]] to ! TransferArrayBuffer(_firstDescriptor_.[[buffer]]).
  1. Assert: _firstDescriptor_.[[bytesFilled]] is *0*.
  1. Let _stream_ be _controller_.[[controlledReadableByteStream]].
  1. If ! ReadableStreamHasBYOBReader(_stream_) is *true*,
    1. Repeat the following steps while ! ReadableStreamGetNumReadIntoRequests(_stream_) > *0*,
      1. Let _pullIntoDescriptor_ be ! ReadableByteStreamControllerShiftPendingPullInto(_controller_).
      1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(_stream_, _pullIntoDescriptor_).
</emu-alg>

<h4 id="readable-byte-stream-controller-respond-in-readable-state"
aoid="ReadableByteStreamControllerRespondInReadableState" throws>ReadableByteStreamControllerRespondInReadableState (
<var>controller</var>, <var>bytesWritten</var>, <var>pullIntoDescriptor</var> )</h4>

<emu-alg>
  1. If _pullIntoDescriptor_.[[bytesFilled]] + _bytesWritten_ > _pullIntoDescriptor_.[[byteLength]], throw a
     *RangeError* exception.
  1. Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(_controller_, _bytesWritten_,
     _pullIntoDescriptor_).
  1. If _pullIntoDescriptor_.[[bytesFilled]] < _pullIntoDescriptor_.[[elementSize]], return.
  1. Perform ! ReadableByteStreamControllerShiftPendingPullInto(_controller_).
  1. Let _remainderSize_ be _pullIntoDescriptor_.[[bytesFilled]] mod _pullIntoDescriptor_.[[elementSize]].
  1. If _remainderSize_ > *0*,
    1. Let _end_ be _pullIntoDescriptor_.[[byteOffset]] + _pullIntoDescriptor_.[[bytesFilled]].
    1. Let _remainder_ be ? CloneArrayBuffer(_pullIntoDescriptor_.[[buffer]], _end_ − _remainderSize_, _remainderSize_,
       %ArrayBuffer%).
    1. Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(_controller_, _remainder_, *0*,
       _remainder_.[[ByteLength]]).
  1. Set _pullIntoDescriptor_.[[buffer]] to ! TransferArrayBuffer(_pullIntoDescriptor_.[[buffer]]).
  1. Set _pullIntoDescriptor_.[[bytesFilled]] to _pullIntoDescriptor_.[[bytesFilled]] − _remainderSize_.
  1. Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(_controller_.[[controlledReadableByteStream]],
     _pullIntoDescriptor_).
  1. Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(_controller_).
</emu-alg>

<h4 id="readable-byte-stream-controller-respond-internal" aoid="ReadableByteStreamControllerRespondInternal"
throws>ReadableByteStreamControllerRespondInternal ( <var>controller</var>, <var>bytesWritten</var> )</h4>

<emu-alg>
  1. Let _firstDescriptor_ be the first element of _controller_.[[pendingPullIntos]].
  1. Let _stream_ be _controller_.[[controlledReadableByteStream]].
  1. If _stream_.[[state]] is `"closed"`,
    1. If _bytesWritten_ is not *0*, throw a *TypeError* exception.
    1. Perform ! ReadableByteStreamControllerRespondInClosedState(_controller_, _firstDescriptor_).
  1. Otherwise,
    1. Assert: _stream_.[[state]] is `"readable"`.
    1. Perform ? ReadableByteStreamControllerRespondInReadableState(_controller_, _bytesWritten_, _firstDescriptor_).
  1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(_controller_).
</emu-alg>

<h4 id="readable-byte-stream-controller-respond-with-new-view" aoid="ReadableByteStreamControllerRespondWithNewView"
throws>ReadableByteStreamControllerRespondWithNewView ( <var>controller</var>, <var>view</var> )</h4>

<emu-alg>
  1. Assert: _controller_.[[pendingPullIntos]] is not empty.
  1. Let _firstDescriptor_ be the first element of _controller_.[[pendingPullIntos]].
  1. If _firstDescriptor_.[[byteOffset]] + _firstDescriptor_.[[bytesFilled]] is not _view_.[[ByteOffset]], throw a
     *RangeError* exception.
  1. If _firstDescriptor_.[[byteLength]] is not _view_.[[ByteLength]], throw a *RangeError* exception.
  1. Set _firstDescriptor_.[[buffer]] to _view_.[[ViewedArrayBuffer]].
  1. Perform ? ReadableByteStreamControllerRespondInternal(_controller_, _view_.[[ByteLength]]).
</emu-alg>

<h4 id="readable-byte-stream-controller-shift-pending-pull-into" aoid="ReadableByteStreamControllerShiftPendingPullInto"
nothrow>ReadableByteStreamControllerShiftPendingPullInto ( <var>controller</var> )</h4>

<emu-alg>
  1. Let _descriptor_ be the first element of _controller_.[[pendingPullIntos]].
  1. Remove _descriptor_ from _controller_.[[pendingPullIntos]], shifting all other elements downward (so that the
     second becomes the first, and so on).
  1. Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(_controller_).
  1. Return _descriptor_.
</emu-alg>

<h4 id="readable-byte-stream-controller-should-call-pull" aoid="ReadableByteStreamControllerShouldCallPull"
nothrow>ReadableByteStreamControllerShouldCallPull ( <var>controller</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledReadableByteStream]].
  1. If _stream_.[[state]] is not `"readable"`, return *false*.
  1. If _controller_.[[closeRequested]] is *true*, return *false*.
  1. If _controller_.[[started]] is *false*, return *false*.
  1. If ! ReadableStreamHasDefaultReader(_stream_) is *true* and ! ReadableStreamGetNumReadRequests(_stream_) > *0*,
     return *true*.
  1. If ! ReadableStreamHasBYOBReader(_stream_) is *true* and ! ReadableStreamGetNumReadIntoRequests(_stream_) > *0*,
     return *true*.
  1. Let _desiredSize_ be  ! ReadableByteStreamControllerGetDesiredSize(_controller_).
  1. Assert: _desiredSize_ is not *null*.
  1. If _desiredSize_ > *0*, return *true*.
  1. Return *false*.
</emu-alg>

<h4 id="set-up-readable-byte-stream-controller" aoid="SetUpReadableByteStreamController"
throws>SetUpReadableByteStreamController ( <var>stream</var>, <var>controller</var>, <var>startAlgorithm</var>,
<var>pullAlgorithm</var>, <var>cancelAlgorithm</var>, <var>highWaterMark</var>, <var>autoAllocateChunkSize</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[readableStreamController]] is *undefined*.
  1. If _autoAllocateChunkSize_ is not *undefined*,
    1. Assert: ! IsInteger(_autoAllocateChunkSize_) is *true*.
    1. Assert: _autoAllocateChunkSize_ is positive.
  1. Set _controller_.[[controlledReadableByteStream]] to _stream_.
  1. Set _controller_.[[pullAgain]] and _controller_.[[pulling]] to *false*.
  1. Set _controller_.[[byobRequest]] to *undefined*.
  1. Perform ! ResetQueue(_controller_).
  1. Set _controller_.[[closeRequested]] and _controller_.[[started]] to *false*.
  1. Set _controller_.[[strategyHWM]] to ? ValidateAndNormalizeHighWaterMark(_highWaterMark_).
  1. Set _controller_.[[pullAlgorithm]] to _pullAlgorithm_.
  1. Set _controller_.[[cancelAlgorithm]] to _cancelAlgorithm_.
  1. Set _controller_.[[autoAllocateChunkSize]] to _autoAllocateChunkSize_.
  1. Set _controller_.[[pendingPullIntos]] to a new empty List.
  1. Set _stream_.[[readableStreamController]] to _controller_.
  1. Let _startResult_ be the result of performing _startAlgorithm_.
  1. Let _startPromise_ be <a>a promise resolved with</a> _startResult_.
  1. <a>Upon fulfillment</a>  of _startPromise_,
    1. Set _controller_.[[started]] to *true*.
    1. Assert: _controller_.[[pulling]] is *false*.
    1. Assert: _controller_.[[pullAgain]] is *false*.
    1. Perform ! ReadableByteStreamControllerCallPullIfNeeded(_controller_).
  1. <a>Upon rejection</a> of _startPromise_ with reason _r_,
    1. Perform ! ReadableByteStreamControllerError(_controller_, _r_).
</emu-alg>

<h4 id="set-up-readable-byte-stream-controller-from-underlying-source"
aoid="SetUpReadableByteStreamControllerFromUnderlyingSource"
throws>SetUpReadableByteStreamControllerFromUnderlyingSource ( <var>stream</var>,
<var ignore>underlyingByteSource</var>, <var>highWaterMark</var> )</h4>

<emu-alg>
  1. Assert: _underlyingByteSource_ is not *undefined*.
  1. Let _controller_ be ObjectCreate(the original value of `<a idl>ReadableByteStreamController</a>`'s `prototype`
     property).
  1. Let _startAlgorithm_ be the following steps:
    1. Return ? InvokeOrNoop(_underlyingByteSource_, `"start"`, « _controller_ »).
  1. Let _pullAlgorithm_ be ? CreateAlgorithmFromUnderlyingMethod(_underlyingByteSource_, `"pull"`, *0*, « _controller_
     »).
  1. Let _cancelAlgorithm_ be ? CreateAlgorithmFromUnderlyingMethod(_underlyingByteSource_, `"cancel"`, *1*, « »).
  1. Let _autoAllocateChunkSize_ be ? GetV(_underlyingByteSource_, `"autoAllocateChunkSize"`).
  1. If _autoAllocateChunkSize_ is not *undefined*,
    1. Set _autoAllocateChunkSize_ to ? ToNumber(_autoAllocateChunkSize_).
    1. If ! IsInteger(_autoAllocateChunkSize_) is *false*, or if _autoAllocateChunkSize_ ≤ *0*, throw a *RangeError*
       exception.
  1. Perform ? SetUpReadableByteStreamController(_stream_, _controller_, _startAlgorithm_, _pullAlgorithm_,
     _cancelAlgorithm_, _highWaterMark_, _autoAllocateChunkSize_).
</emu-alg>

<h4 id="set-up-readable-stream-byob-request"
aoid="SetUpReadableStreamBYOBRequest"
nothrow>SetUpReadableStreamBYOBRequest ( <var ignore>request</var>, <var>controller</var>, <var>view</var> )</h4>

<emu-alg>
  1. Assert: ! IsReadableByteStreamController(_controller_) is *true*.
  1. Assert: Type(_view_) is Object.
  1. Assert: _view_ has a [[ViewedArrayBuffer]] internal slot.
  1. Assert: ! IsDetachedBuffer(_view_.[[ViewedArrayBuffer]]) is *false*.
  1. Set _request_.[[associatedReadableByteStreamController]] to _controller_.
  1. Set _request_.[[view]] to _view_.
</emu-alg>

<h2 id="ws">Writable streams</h2>

<h3 id="ws-intro">Using writable streams</h3>

<div class="example" id="example-basic-pipe-to-2">
  The usual way to write to a writable stream is to simply <a lt="piping">pipe</a> a <a>readable stream</a> to it.
  This ensures that <a>backpressure</a> is respected, so that if the writable stream's <a>underlying sink</a> is not
  able to accept data as fast as the readable stream can produce it, the readable stream is informed of this and has a
  chance to slow down its data production.

  <pre><code class="lang-javascript">
    readableStream.pipeTo(writableStream)
      .then(() => console.log("All data successfully written!"))
      .catch(e => console.error("Something went wrong!", e));
  </code></pre>
</div>

<div class="example" id="example-manual-write-batch">
  You can also write directly to writable streams by acquiring a <a>writer</a> and using its
  {{WritableStreamDefaultWriter/write()}} and {{WritableStreamDefaultWriter/close()}} methods. Since writable streams
  queue any incoming writes, and take care internally to forward them to the <a>underlying sink</a> in sequence, you can
  indiscriminately write to a writable stream without much ceremony:

  <pre><code class="lang-javascript">
    function writeArrayToStream(array, writableStream) {
      const writer = writableStream.getWriter();
      array.forEach(chunk => writer.write(chunk).catch(() => {}));

      return writer.close();
    }

    writeArrayToStream([1, 2, 3, 4, 5], writableStream)
      .then(() => console.log("All done!"))
      .catch(e => console.error("Error with the stream: " + e));
  </code></pre>

  Note how we use <code>.catch(() => {})</code> to suppress any rejections from the
  {{WritableStreamDefaultWriter/write()}} method; we'll be notified of any fatal errors via a rejection of the
  {{WritableStreamDefaultWriter/close()}} method, and leaving them un-caught would cause potential
  {{unhandledrejection}} events and console warnings.
</div>

<div class="example" id="example-manual-write-with-error-handling">
  In the previous example we only paid attention to the success or failure of the entire stream, by looking at the
  promise returned by the writer's {{WritableStreamDefaultWriter/close()}} method. That promise will reject if anything
  goes wrong with the stream—initializing it, writing to it, or closing it. And it will fulfill once the stream is
  successfully closed. Often this is all you care about.

  However, if you care about the success of writing a specific <a>chunk</a>, you can use the promise returned by the
  writer's {{WritableStreamDefaultWriter/write()}} method:

  <pre><code class="lang-javascript">
    writer.write("i am a chunk of data")
      .then(() => console.log("chunk successfully written!"))
      .catch(e => console.error(e));
  </code></pre>

  What "success" means is up to a given stream instance (or more precisely, its <a>underlying sink</a>) to decide. For
  example, for a file stream it could simply mean that the OS has accepted the write, and not necessarily that the
  chunk has been flushed to disk. Some streams might not be able to give such a signal at all, in which case the
  returned promise will fulfill immediately.
</div>

<div class="example" id="example-manual-write-with-backpressure">
  The {{WritableStreamDefaultWriter/desiredSize}} and {{WritableStreamDefaultWriter/ready}} properties of <a>writable
  stream writers</a> allow <a>producers</a> to more precisely respond to flow control signals from the stream, to keep
  memory usage below the stream's specified <a>high water mark</a>. The following example writes an infinite sequence of
  random bytes to a stream, using {{WritableStreamDefaultWriter/desiredSize}} to determine how many bytes to generate at
  a given time, and using {{WritableStreamDefaultWriter/ready}} to wait for the <a>backpressure</a> to subside.

  <pre><code class="lang-javascript">
  async function writeRandomBytesForever(writableStream) {
    const writer = writableStream.getWriter();

    while (true) {
      await writer.ready;

      const bytes = new Uint8Array(writer.desiredSize);
      crypto.getRandomValues(bytes);

      // Purposefully don't await; awaiting writer.ready is enough.
      writer.write(bytes).catch(() => {});
    }
  }

  writeRandomBytesForever(myWritableStream).catch(e => console.error("Something broke", e));
  </code></pre>

  Note how we don't <code>await</code> the promise returned by {{WritableStreamDefaultWriter/write()}}; this would be
  redundant with <code>await</code>ing the {{WritableStreamDefaultWriter/ready}} promise. Additionally, similar to <a
  href="#example-manual-write-batch">a previous example</a>, we use the <code>.catch(() => {})</code> pattern on the
  promises returned by {{WritableStreamDefaultWriter/write()}}; in this case we'll be notified about any failures
  <code>await</code>ing the {{WritableStreamDefaultWriter/ready}} promise.
</div>

<div class="example" id="example-manual-write-dont-await">
  To further emphasize how it's a bad idea to <code>await</code> the promise returned by
  {{WritableStreamDefaultWriter/write()}}, consider a modification of the above example, where we continue to use the
  {{WritableStreamDefaultWriter}} interface directly, but we don't control how many bytes we have to write at a given
  time. In that case, the <a>backpressure</a>-respecting code looks the same:

  <pre><code class="lang-javascript">
  async function writeSuppliedBytesForever(writableStream, getBytes) {
    const writer = writableStream.getWriter();

    while (true) {
      await writer.ready;

      const bytes = getBytes();
      writer.write(bytes).catch(() => {});
    }
  }
  </code></pre>

  Unlike the previous example, where—because we were always writing exactly
  {{WritableStreamDefaultWriter/desiredSize|writer.desiredSize}} bytes each time—the
  {{WritableStreamDefaultWriter/write()}} and {{WritableStreamDefaultWriter/ready}} promises were synchronized, in this
  case it's quite possible that the {{WritableStreamDefaultWriter/ready}} promise fulfills before the one returned by
  {{WritableStreamDefaultWriter/write()}} does. Remember, the {{WritableStreamDefaultWriter/ready}} promise fulfills
  when the <a lt="desired size to fill a stream's internal queue">desired size</a> becomes positive, which might be
  before the write succeeds (especially in cases with a larger <a>high water mark</a>).

  In other words, <code>await</code>ing the return value of {{WritableStreamDefaultWriter/write()}} means you never
  queue up writes in the stream's <a>internal queue</a>, instead only executing a write after the previous one succeeds,
  which can result in low throughput.
</div>

<h3 id="ws-class" interface lt="WritableStream">Class <code>WritableStream</code></h3>

<h4 id="ws-class-definition">Class definition</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{WritableStream}} class in something close to the syntax of [[!ECMASCRIPT]], it would look
like

<pre><code class="lang-javascript">
  class WritableStream {
    <a href="#ws-constructor">constructor</a>(<a href="#underlying-sink-api">underlyingSink</a> = {}, <a href="#qs-api">strategy</a> = {})

    get <a href="#ws-locked">locked</a>()

    <a href="#ws-abort">abort</a>(reason)
    <a href="#ws-close">close</a>()
    <a href="#ws-get-writer">getWriter</a>()
  }
</code></pre>

</div>

<h4 id="ws-internal-slots">Internal slots</h4>

Instances of {{WritableStream}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[backpressure]]
    <td class="non-normative">The backpressure signal set by the controller
  </tr>
  <tr>
    <td>\[[closeRequest]]
    <td class="non-normative">The promise returned from the writer {{WritableStreamDefaultWriter/close()}} method
  </tr>
  <tr>
    <td>\[[inFlightWriteRequest]]
    <td class="non-normative">A slot set to the promise for the current in-flight write operation while the
      <a>underlying sink</a>'s write algorithm is executing and has not yet fulfilled, used to prevent reentrant calls
  </tr>
  <tr>
    <td>\[[inFlightCloseRequest]]
    <td class="non-normative">A slot set to the promise for the current in-flight close operation while the
      <a>underlying sink</a>'s close algorithm is executing and has not yet fulfilled, used to prevent the
      {{WritableStreamDefaultWriter/abort()}} method from interrupting close
  </tr>
  <tr>
    <td>\[[pendingAbortRequest]]
    <td class="non-normative">A Record containing the promise returned from
      {{WritableStreamDefaultWriter/abort()}} and the <var>reason</var> passed to
      {{WritableStreamDefaultWriter/abort()}}
  </tr>
  <tr>
    <td>\[[state]]
    <td class="non-normative">A string containing the stream's current state, used internally; one of
      <code>"writable"</code>, <code>"closed"</code>, <code>"erroring"</code>, or <code>"errored"</code>
  </tr>
  <tr>
    <td>\[[storedError]]
    <td class="non-normative">A value indicating how the stream failed, to be given as a failure reason or exception
      when trying to operate on the stream while in the <code>"errored"</code> state
  </tr>
  <tr>
    <td>\[[writableStreamController]]
    <td class="non-normative">A {{WritableStreamDefaultController}} created with the ability to control the state and
      queue of this stream; also used for the <a href="#is-writable-stream">IsWritableStream</a> brand check
  </tr>
  <tr>
    <td>\[[writer]]
    <td class="non-normative">A {{WritableStreamDefaultWriter}} instance, if the stream is <a>locked to a writer</a>, or
      <emu-val>undefined</emu-val> if it is not
  </tr>
  <tr>
    <td>\[[writeRequests]]
    <td class="non-normative">A List of promises representing the stream's internal queue of write requests not yet
      processed by the <a>underlying sink</a>
  </tr>
</table>

<p class="note">
  The \[[inFlightCloseRequest]] slot and \[[closeRequest]] slot are mutually exclusive. Similarly, no element will be
  removed from \[[writeRequests]] while \[[inFlightWriteRequest]] is not <emu-val>undefined</emu-val>. Implementations
  can optimize storage for these slots based on these invariants.
</p>

<h4 id="ws-constructor" constructor for="WritableStream" lt="WritableStream(underlyingSink, strategy)">new
WritableStream(<var>underlyingSink</var> = {}, <var>strategy</var> = {})</h4>

<div class="note">
  The <code>underlyingSink</code> argument represents the <a>underlying sink</a>, as described in
  [[#underlying-sink-api]].

  The <code>strategy</code> argument represents the stream's <a>queuing strategy</a>, as described in [[#qs-api]]. If it
  is not provided, the default behavior will be the same as a {{CountQueuingStrategy}} with a <a>high water mark</a>
  of 1.
</div>

<emu-alg>
  1. Perform ! InitializeWritableStream(_this_).
  1. Let _size_ be ? GetV(_strategy_, `"size"`).
  1. Let _highWaterMark_ be ? GetV(_strategy_, `"highWaterMark"`).
  1. Let _type_ be ? GetV(_underlyingSink_, `"type"`).
  1. If _type_ is not *undefined*, throw a *RangeError* exception. <p class="note">This is to allow us to add new
     potential types in the future, without backward-compatibility concerns.</p>
  1. Let _sizeAlgorithm_ be ? MakeSizeAlgorithmFromSizeFunction(_size_).
  1. If _highWaterMark_ is *undefined*, let _highWaterMark_ be *1*.
  1. Set _highWaterMark_ to ? ValidateAndNormalizeHighWaterMark(_highWaterMark_).
  1. Perform ? SetUpWritableStreamDefaultControllerFromUnderlyingSink(*this*, _underlyingSink_, _highWaterMark_,
     _sizeAlgorithm_).
</emu-alg>

<h4 id="underlying-sink-api">Underlying sink API</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

The {{WritableStream()}} constructor accepts as its first argument a JavaScript object representing the <a>underlying
sink</a>. Such objects can contain any of the following properties:

<dl>
  <dt><dfn method for="underlying sink">start(<var>controller</var>)</dfn></dt>
  <dd>
    <p>A function that is called immediately during creation of the {{WritableStream}}.</p>

    <p>Typically this is used to acquire access to the <a>underlying sink</a> resource being represented.</p>

    <p>If this setup process is asynchronous, it can return a promise to signal success or failure; a rejected promise
    will error the stream. Any thrown exceptions will be re-thrown by the {{WritableStream()}} constructor.</p>
  </dd>

  <dt><dfn method for="underlying sink">write(<var>chunk</var>, <var>controller</var>)</dfn></dt>
  <dd>
    <p>A function that is called when a new <a>chunk</a> of data is ready to be written to the <a>underlying sink</a>.
    The stream implementation guarantees that this function will be called only after previous writes have succeeded,
    and never before {{underlying sink/start()}} has succeeded or after {{underlying sink/close()}} or
    {{underlying sink/abort()}} have been called.</p>

    <p>This function is used to actually send the data to the resource presented by the <a>underlying sink</a>, for
    example by calling a lower-level API.</p>

    <p>If the process of writing data is asynchronous, and communicates success or failure signals back to its user,
    then this function can return a promise to signal success or failure. This promise return value will be communicated
    back to the caller of {{WritableStreamDefaultWriter/write()|writer.write()}}, so they can monitor that individual
    write. Throwing an exception is treated the same as returning a rejected promise.</p>

    <p>Note that such signals are not always available; compare e.g. [[#example-ws-no-backpressure]] with
    [[#example-ws-backpressure]]. In such cases, it's best to not return anything.</p>

    <p>The promise potentially returned by this function also governs whether the given chunk counts as written for the
    purposes of computed the <a lt="desired size to fill a stream's internal queue">desired size to fill the stream's
    internal queue</a>. That is, during the time it takes the promise to settle,
    {{WritableStreamDefaultWriter/desiredSize|writer.desiredSize}} will stay at its previous value, only increasing to
    signal the desire for more chunks once the write succeeds.</p>
  </dd>

  <dt><dfn method for="underlying sink">close()</dfn></dt>
  <dd>
    <p>A function that is called after the <a>producer</a> signals, via
    {{WritableStreamDefaultWriter/close()|writer.close()}}, that they are done writing <a>chunks</a> to the stream, and
    subsequently all queued-up writes have successfully completed.</p>

    <p>This function can perform any actions necessary to finalize or flush writes to the <a>underlying sink</a>, and
    release access to any held resources.</p>

    <p>If the shutdown process is asynchronous, the function can return a promise to signal success or failure; the
    result will be communicated via the return value of the called
    {{WritableStreamDefaultWriter/close()|writer.close()}} method. Additionally, a rejected promise will error the
    stream, instead of letting it close successfully. Throwing an exception is treated the same as returning a rejected
    promise.</p>
  </dd>

  <dt><dfn method for="underlying sink">abort(<var>reason</var>)</dfn></dt>
  <dd>
    <p>A function that is called after the <a>producer</a> signals, via {{WritableStream/abort()|stream.abort()}} or
    {{WritableStreamDefaultWriter/abort()|writer.abort()}}, that they wish to <a lt="abort a writable stream">abort</a>
    the stream. It takes as its argument the same value as was passed to those methods by the producer.</p>

    <p>Writable streams can additionally be aborted under certain conditions during <a>piping</a>; see the definition
    of the {{ReadableStream/pipeTo()}} method for more details.</p>

    <p>This function can clean up any held resources, much like {{underlying sink/close()}}, but perhaps with some
    custom handling.</p>

    <p>If the shutdown process is asynchronous, the function can return a promise to signal success or failure; the
    result will be communicated via the return value of the called <code>abort()</code> method. Throwing an exception is
    treated the same as returning a rejected promise. Regardless, the stream will be errored with a new {{TypeError}}
    indicating that it was aborted.</p>
  </dd>
</dl>

The <code>controller</code> argument passed to {{underlying sink/start()}} and {{underlying sink/write()}} is an
instance of {{WritableStreamDefaultController}}, and has the ability to error the stream. This is mainly used for
bridging the gap with non-promise-based APIs, as seen for example in [[#example-ws-no-backpressure]].

</div>

<h4 id="ws-prototype">Properties of the {{WritableStream}} prototype</h4>

<h5 id="ws-locked" attribute for="WritableStream" lt="locked">get locked</h5>

<div class="note">
  The <code>locked</code> getter returns whether or not the writable stream is <a>locked to a writer</a>.
</div>

<emu-alg>
  1. If ! IsWritableStream(*this*) is *false*, throw a *TypeError* exception.
  1. Return ! IsWritableStreamLocked(*this*).
</emu-alg>

<h5 id="ws-abort" method for="WritableStream">abort(<var>reason</var>)</h5>

<div class="note">
  The <code>abort</code> method <a lt="abort a writable stream">aborts</a> the stream, signaling that the producer can
  no longer successfully write to the stream and it is to be immediately moved to an errored state, with any queued-up
  writes discarded. This will also execute any abort mechanism of the <a>underlying sink</a>.
</div>

<emu-alg>
  1. If ! IsWritableStream(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If ! IsWritableStreamLocked(*this*) is *true*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return ! WritableStreamAbort(*this*, _reason_).
</emu-alg>

<h5 id="ws-close" method for="WritableStream">close()</h5>

<div class="note">
  The <code>close</code> method closes the stream. The <a>underlying sink</a> will finish processing any
  previously-written <a>chunks</a>, before invoking its close behavior. During this time any further attempts to write
  will fail (without erroring the stream).

  The method returns a promise that is fulfilled with <emu-val>undefined</emu-val> if all remaining <a>chunks</a> are
  successfully written and the stream successfully closes, or rejects if an error is encountered during this process.
</div>

<emu-alg>
  1. If ! IsWritableStream(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If ! IsWritableStreamLocked(*this*) is *true*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If ! WritableStreamCloseQueuedOrInFlight(*this*) is *true*, return <a>a promise rejected with</a> a *TypeError*
  exception.
  1. Return ! WritableStreamClose(*this*).
</emu-alg>

<h5 id="ws-get-writer" method for="WritableStream">getWriter()</h5>

<div class="note">
  The <code>getWriter</code> method creates a <a>writer</a> (an instance of {{WritableStreamDefaultWriter}}) and <a
  lt="locked to a writer">locks</a> the stream to the new writer. While the stream is locked, no other writer can be
  acquired until this one is <a lt="release a write lock">released</a>.

  This functionality is especially useful for creating abstractions that desire the ability to write to a stream without
  interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at the same
  time, which would cause the resulting written data to be unpredictable and probably useless.
</div>

<emu-alg>
  1. If ! IsWritableStream(*this*) is *false*, throw a *TypeError* exception.
  1. Return ? AcquireWritableStreamDefaultWriter(*this*).
</emu-alg>

<h3 id="ws-abstract-ops">General writable stream abstract operations</h3>

The following abstract operations, unlike most in this specification, are meant to be generally useful by other
specifications, instead of just being part of the implementation of this spec's classes.

<h4 id="acquire-writable-stream-default-writer" aoid="AcquireWritableStreamDefaultWriter"
throws>AcquireWritableStreamDefaultWriter ( <var>stream</var> )</h4>

<emu-alg>
  1. Return ? Construct(`<a idl>WritableStreamDefaultWriter</a>`, « _stream_ »).
</emu-alg>

<h4 id="create-writable-stream" aoid="CreateWritableStream" throws>CreateWritableStream ( <var>startAlgorithm</var>,
<var>writeAlgorithm</var>, <var>closeAlgorithm</var>, <var>abortAlgorithm</var> [, <var>highWaterMark</var> [,
<var>sizeAlgorithm</var> ] ] )</h4>

This abstract operation is meant to be called from other specifications that wish to create {{WritableStream}}
instances. The <var>writeAlgorithm</var>, <var>closeAlgorithm</var> and <var>abortAlgorithm</var> algorithms must return
promises; if supplied, <var>sizeAlgorithm</var> must be an algorithm accepting <a>chunk</a> objects and returning a
number; and if supplied, <var>highWaterMark</var> must be a non-negative, non-NaN number.

<p class="note">CreateWritableStream throws an exception if and only if the supplied <var>startAlgorithm</var>
throws.</p>

<emu-alg>
  1. If _highWaterMark_ was not passed, set it to *1*.
  1. If _sizeAlgorithm_ was not passed, set it to an algorithm that returns *1*.
  1. Assert: ! IsNonNegativeNumber(_highWaterMark_) is *true*.
  1. Let _stream_ be ObjectCreate(the original value of `<a idl>WritableStream</a>`'s `prototype` property).
  1. Perform ! InitializeWritableStream(_stream_).
  1. Let _controller_ be ObjectCreate(the original value of `<a idl>WritableStreamDefaultController</a>`'s `prototype`
     property).
  1. Perform ? SetUpWritableStreamDefaultController(_stream_, _controller_, _startAlgorithm_, _writeAlgorithm_,
     _closeAlgorithm_, _abortAlgorithm_, _highWaterMark_, _sizeAlgorithm_).
  1. Return _stream_.
</emu-alg>

<h4 id="initialize-writable-stream" aoid="InitializeWritableStream" nothrow>InitializeWritableStream ( <var>stream</var>
)</h4>

<emu-alg>
  1. Set _stream_.[[state]] to `"writable"`.
  1. Set _stream_.[[storedError]], _stream_.[[writer]], _stream_.[[writableStreamController]],
     _stream_.[[inFlightWriteRequest]], _stream_.[[closeRequest]], _stream_.[[inFlightCloseRequest]] and
     _stream_.[[pendingAbortRequest]] to *undefined*.
  1. Set _stream_.[[writeRequests]] to a new empty List.
  1. Set _stream_.[[backpressure]] to *false*.
</emu-alg>

<h4 id="is-writable-stream" aoid="IsWritableStream" nothrow>IsWritableStream ( <var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have a [[writableStreamController]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="is-writable-stream-locked" aoid="IsWritableStreamLocked" nothrow>IsWritableStreamLocked ( <var>stream</var>
)</h4>

This abstract operation is meant to be called from other specifications that may wish to query whether or not a
writable stream is <a>locked to a writer</a>.

<emu-alg>
  1. Assert: ! IsWritableStream(_stream_) is *true*.
  1. If _stream_.[[writer]] is *undefined*, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="writable-stream-abort" aoid="WritableStreamAbort" nothrow>WritableStreamAbort ( <var>stream</var>,
<var>reason</var> )</h4>

<emu-alg>
  1. Let _state_ be _stream_.[[state]].
  1. If _state_ is `"closed"` or `"errored"`, return <a>a promise resolved with</a> *undefined*.
  1. If _stream_.[[pendingAbortRequest]] is not *undefined*, return _stream_.[[pendingAbortRequest]].[[promise]].
  1. Assert: _state_ is `"writable"` or `"erroring"`.
  1. Let _wasAlreadyErroring_ be *false*.
  1. If _state_ is `"erroring"`,
    1. Set _wasAlreadyErroring_ to *true*.
    1. Set _reason_ to *undefined*.
  1. Let _promise_ be <a>a new promise</a>.
  1. Set _stream_.[[pendingAbortRequest]] to Record {[[promise]]: _promise_, [[reason]]: _reason_,
     [[wasAlreadyErroring]]: _wasAlreadyErroring_}.
  1. If _wasAlreadyErroring_ is *false*, perform ! WritableStreamStartErroring(_stream_, _reason_).
  1. Return _promise_.
</emu-alg>

<h4 id="writable-stream-close" aoid="WritableStreamClose" nothrow>WritableStreamClose ( <var>stream</var> )</h4>

<emu-alg>
  1. Let _state_ be _stream_.[[state]].
  1. If _state_ is `"closed"` or `"errored"`, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Assert: _state_ is `"writable"` or `"erroring"`.
  1. Assert: ! WritableStreamCloseQueuedOrInFlight(_stream_) is *false*.
  1. Let _promise_ be <a>a new promise</a>.
  1. Set _stream_.[[closeRequest]] to _promise_.
  1. Let _writer_ be _stream_.[[writer]].
  1. If _writer_ is not *undefined*, and _stream_.[[backpressure]] is *true*, and _state_ is `"writable"`,
     <a>resolve</a> _writer_.[[readyPromise]] with *undefined*.
  1. Perform ! WritableStreamDefaultControllerClose(_stream_.[[writableStreamController]]).
  1. Return _promise_.
</emu-alg>

<h3 id="ws-abstract-ops-used-by-controllers">Writable stream abstract operations used by controllers</h3>

To allow future flexibility to add different writable stream behaviors (similar to the distinction between default
readable streams and <a>readable byte streams</a>), much of the internal state of a <a>writable stream</a> is
encapsulated by the {{WritableStreamDefaultController}} class.

The abstract operations in this section are interfaces that are used by the controller implementation to affect its
associated {{WritableStream}} object, translating the controller's internal state changes into developer-facing results
visible through the {{WritableStream}}'s public API.

<h4 id="writable-stream-add-write-request" aoid="WritableStreamAddWriteRequest" nothrow>WritableStreamAddWriteRequest (
<var>stream</var> )</h4>

<emu-alg>
  1. Assert: ! IsWritableStreamLocked(_stream_) is *true*.
  1. Assert: _stream_.[[state]] is `"writable"`.
  1. Let _promise_ be <a>a new promise</a>.
  1. Append _promise_ as the last element of _stream_.[[writeRequests]].
  1. Return _promise_.
</emu-alg>

<h4 id="writable-stream-deal-with-rejection" aoid="WritableStreamDealWithRejection"
nothrow>WritableStreamDealWithRejection ( <var>stream</var>, <var>error</var> )</h4>

<emu-alg>
  1. Let _state_ be _stream_.[[state]].
  1. If _state_ is `"writable"`,
    1. Perform ! WritableStreamStartErroring(_stream_, _error_).
    1. Return.
  1. Assert: _state_ is `"erroring"`.
  1. Perform ! WritableStreamFinishErroring(_stream_).
</emu-alg>

<h4 id="writable-stream-start-erroring" aoid="WritableStreamStartErroring" nothrow>WritableStreamStartErroring (
<var>stream</var>, <var>reason</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[storedError]] is *undefined*.
  1. Assert: _stream_.[[state]] is `"writable"`.
  1. Let _controller_ be _stream_.[[writableStreamController]].
  1. Assert: _controller_ is not *undefined*.
  1. Set _stream_.[[state]] to `"erroring"`.
  1. Set _stream_.[[storedError]] to _reason_.
  1. Let _writer_ be _stream_.[[writer]].
  1. If _writer_ is not *undefined*, perform !
     WritableStreamDefaultWriterEnsureReadyPromiseRejected(_writer_, _reason_).
  1. If ! WritableStreamHasOperationMarkedInFlight(_stream_) is *false* and _controller_.[[started]] is *true*, perform
     ! WritableStreamFinishErroring(_stream_).
</emu-alg>

<h4 id="writable-stream-finish-erroring" aoid="WritableStreamFinishErroring" nothrow>WritableStreamFinishErroring
( <var>stream</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[state]] is `"erroring"`.
  1. Assert: ! WritableStreamHasOperationMarkedInFlight(_stream_) is *false*.
  1. Set _stream_.[[state]] to `"errored"`.
  1. Perform ! _stream_.[[writableStreamController]].[[ErrorSteps]]().
  1. Let _storedError_ be _stream_.[[storedError]].
  1. Repeat for each _writeRequest_ that is an element of _stream_.[[writeRequests]],
    1. <a>Reject</a> _writeRequest_ with _storedError_.
  1. Set _stream_.[[writeRequests]] to an empty List.
  1. If _stream_.[[pendingAbortRequest]] is *undefined*,
    1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(_stream_).
    1. Return.
  1. Let _abortRequest_ be _stream_.[[pendingAbortRequest]].
  1. Set _stream_.[[pendingAbortRequest]] to *undefined*.
  1. If _abortRequest_.[[wasAlreadyErroring]] is *true*,
    1. <a>Reject</a> _abortRequest_.[[promise]] with _storedError_.
    1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(_stream_).
    1. Return.
  1. Let _promise_ be ! stream.[[writableStreamController]].[[AbortSteps]](_abortRequest_.[[reason]]).
  1. <a>Upon fulfillment</a> of _promise_,
    1. <a>Resolve</a> _abortRequest_.[[promise]] with *undefined*.
    1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(_stream_).
  1. <a>Upon rejection</a> of _promise_ with reason _reason_,
    1. <a>Reject</a> _abortRequest_.[[promise]] with _reason_.
    1. Perform ! WritableStreamRejectCloseAndClosedPromiseIfNeeded(_stream_).
</emu-alg>

<h4 id="writable-stream-finish-in-flight-write" aoid="WritableStreamFinishInFlightWrite"
nothrow>WritableStreamFinishInFlightWrite ( <var>stream</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[inFlightWriteRequest]] is not *undefined*.
  1. <a>Resolve</a> _stream_.[[inFlightWriteRequest]] with *undefined*.
  1. Set _stream_.[[inFlightWriteRequest]] to *undefined*.
</emu-alg>

<h4 id="writable-stream-finish-in-flight-write-with-error" aoid="WritableStreamFinishInFlightWriteWithError"
nothrow>WritableStreamFinishInFlightWriteWithError ( <var>stream</var>, <var>error</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[inFlightWriteRequest]] is not *undefined*.
  1. <a>Reject</a> _stream_.[[inFlightWriteRequest]] with _error_.
  1. Set _stream_.[[inFlightWriteRequest]] to *undefined*.
  1. Assert: _stream_.[[state]] is `"writable"` or `"erroring"`.
  1. Perform ! WritableStreamDealWithRejection(_stream_, _error_).
</emu-alg>

<h4 id="writable-stream-finish-in-flight-close" aoid="WritableStreamFinishInFlightClose"
nothrow>WritableStreamFinishInFlightClose ( <var>stream</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[inFlightCloseRequest]] is not *undefined*.
  1. <a>Resolve</a> _stream_.[[inFlightCloseRequest]] with *undefined*.
  1. Set _stream_.[[inFlightCloseRequest]] to *undefined*.
  1. Let _state_ be _stream_.[[state]].
  1. Assert: _stream_.[[state]] is `"writable"` or `"erroring"`.
  1. If _state_ is `"erroring"`,
    1. Set _stream_.[[storedError]] to *undefined*.
    1. If _stream_.[[pendingAbortRequest]] is not *undefined*,
      1. <a>Resolve</a> _stream_.[[pendingAbortRequest]].[[promise]] with *undefined*.
      1. Set _stream_.[[pendingAbortRequest]] to *undefined*.
  1. Set _stream_.[[state]] to `"closed"`.
  1. Let _writer_ be _stream_.[[writer]].
  1. If _writer_ is not *undefined*, <a>resolve</a> _writer_.[[closedPromise]] with *undefined*.
  1. Assert: _stream_.[[pendingAbortRequest]] is *undefined*.
  1. Assert: _stream_.[[storedError]] is *undefined*.
</emu-alg>

<h4 id="writable-stream-finish-in-flight-close-with-error" aoid="WritableStreamFinishInFlightCloseWithError"
nothrow>WritableStreamFinishInFlightCloseWithError ( <var>stream</var>, <var>error</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[inFlightCloseRequest]] is not *undefined*.
  1. <a>Reject</a> _stream_.[[inFlightCloseRequest]] with _error_.
  1. Set _stream_.[[inFlightCloseRequest]] to *undefined*.
  1. Assert: _stream_.[[state]] is `"writable"` or `"erroring"`.
  1. If _stream_.[[pendingAbortRequest]] is not *undefined*,
    1. <a>Reject</a> _stream_.[[pendingAbortRequest]].[[promise]] with _error_.
    1. Set _stream_.[[pendingAbortRequest]] to *undefined*.
  1. Perform ! WritableStreamDealWithRejection(_stream_, _error_).
</emu-alg>

<h4 id="writable-stream-close-queued-or-in-flight" aoid="WritableStreamCloseQueuedOrInFlight" nothrow>
WritableStreamCloseQueuedOrInFlight ( <var>stream</var> )</h4>

<emu-alg>
  1. If _stream_.[[closeRequest]] is *undefined* and _stream_.[[inFlightCloseRequest]] is *undefined*, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="writable-stream-has-operation-marked-in-flight" aoid="WritableStreamHasOperationMarkedInFlight"
nothrow>WritableStreamHasOperationMarkedInFlight ( <var>stream</var> )</h4>

<emu-alg>
  1. If _stream_.[[inFlightWriteRequest]] is *undefined* and _controller_.[[inFlightCloseRequest]] is *undefined*, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="writable-stream-mark-close-request-in-flight" aoid="WritableStreamMarkCloseRequestInFlight"
nothrow>WritableStreamMarkCloseRequestInFlight ( <var>stream</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[inFlightCloseRequest]] is *undefined*.
  1. Assert: _stream_.[[closeRequest]] is not *undefined*.
  1. Set _stream_.[[inFlightCloseRequest]] to _stream_.[[closeRequest]].
  1. Set _stream_.[[closeRequest]] to *undefined*.
</emu-alg>

<h4 id="writable-stream-mark-first-write-request-in-flight" aoid="WritableStreamMarkFirstWriteRequestInFlight"
nothrow>WritableStreamMarkFirstWriteRequestInFlight ( <var>stream</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[inFlightWriteRequest]] is *undefined*.
  1. Assert: _stream_.[[writeRequests]] is not empty.
  1. Let _writeRequest_ be the first element of _stream_.[[writeRequests]].
  1. Remove _writeRequest_ from _stream_.[[writeRequests]], shifting all other elements downward (so that the second
     becomes the first, and so on).
  1. Set _stream_.[[inFlightWriteRequest]] to _writeRequest_.
</emu-alg>

<h4 id="writable-stream-reject-close-and-closed-promise-if-needed"
aoid="WritableStreamRejectCloseAndClosedPromiseIfNeeded" nothrow>WritableStreamRejectCloseAndClosedPromiseIfNeeded (
<var>stream</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[state]] is `"errored"`.
  1. If _stream_.[[closeRequest]] is not *undefined*,
    1. Assert: _stream_.[[inFlightCloseRequest]] is *undefined*.
    1. <a>Reject</a> _stream_.[[closeRequest]] with _stream_.[[storedError]].
    1. Set _stream_.[[closeRequest]] to *undefined*.
  1. Let _writer_ be _stream_.[[writer]].
  1. If _writer_ is not *undefined*,
    1. <a>Reject</a> _writer_.[[closedPromise]] with _stream_.[[storedError]].
    1. Set _writer_.[[closedPromise]].[[PromiseIsHandled]] to *true*.
</emu-alg>

<h4 id="writable-stream-update-backpressure" aoid="WritableStreamUpdateBackpressure"
nothrow>WritableStreamUpdateBackpressure ( <var>stream</var>, <var>backpressure</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[state]] is `"writable"`.
  1. Assert: ! WritableStreamCloseQueuedOrInFlight(_stream_) is *false*.
  1. Let _writer_ be _stream_.[[writer]].
  1. If _writer_ is not *undefined* and _backpressure_ is not _stream_.[[backpressure]],
    1. If _backpressure_ is *true*, set _writer_.[[readyPromise]] to <a>a new promise</a>.
    1. Otherwise,
      1. Assert: _backpressure_ is *false*.
      1. <a>Resolve</a> _writer_.[[readyPromise]] with *undefined*.
  1. Set _stream_.[[backpressure]] to _backpressure_.
</emu-alg>

<h3 id="default-writer-class" interface lt="WritableStreamDefaultWriter">Class
<code>WritableStreamDefaultWriter</code></h3>

The {{WritableStreamDefaultWriter}} class represents a <a>writable stream writer</a> designed to be vended by a
{{WritableStream}} instance.

<h4 id="default-writer-class-definition">Class definition</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{WritableStreamDefaultWriter}} class in something close to the syntax of [[!ECMASCRIPT]], it
would look like

<pre><code class="lang-javascript">
  class WritableStreamDefaultWriter {
    <a href="#default-writer-constructor">constructor</a>(stream)

    get <a href="#default-writer-closed">closed</a>()
    get <a href="#default-writer-desired-size">desiredSize</a>()
    get <a href="#default-writer-ready">ready</a>()

    <a href="#default-writer-abort">abort</a>(reason)
    <a href="#default-writer-close">close</a>()
    <a href="#default-writer-release-lock">releaseLock</a>()
    <a href="#default-writer-write">write</a>(chunk)
  }
</code></pre>

</div>

<h4 id="default-writer-internal-slots">Internal slots</h4>

Instances of {{WritableStreamDefaultWriter}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[closedPromise]]
    <td class="non-normative">A promise returned by the writer's {{WritableStreamDefaultWriter/closed}} getter
  </tr>
  <tr>
    <td>\[[ownerWritableStream]]
    <td class="non-normative">A {{WritableStream}} instance that owns this writer
  </tr>
  <tr>
    <td>\[[readyPromise]]
    <td class="non-normative">A promise returned by the writer's {{WritableStreamDefaultWriter/ready}} getter
  </tr>
</table>

<h4 id="default-writer-constructor" constructor for="WritableStreamDefaultWriter"
lt="WritableStreamDefaultWriter(stream)">new WritableStreamDefaultWriter(<var>stream</var>)</h4>

<div class="note">
  The <code>WritableStreamDefaultWriter</code> constructor is generally not meant to be used directly; instead, a
  stream's {{WritableStream/getWriter()}} method ought to be used.
</div>

<emu-alg>
  1. If ! IsWritableStream(_stream_) is *false*, throw a *TypeError* exception.
  1. If ! IsWritableStreamLocked(_stream_) is *true*, throw a *TypeError* exception.
  1. Set *this*.[[ownerWritableStream]] to _stream_.
  1. Set _stream_.[[writer]] to *this*.
  1. Let _state_ be _stream_.[[state]].
  1. If _state_ is `"writable"`,
    1. If ! WritableStreamCloseQueuedOrInFlight(_stream_) is *false* and _stream_.[[backpressure]] is *true*,
       set *this*.[[readyPromise]] to <a>a new promise</a>.
    1. Otherwise, set *this*.[[readyPromise]] to <a>a promise resolved with</a> *undefined*.
    1. Set *this*.[[closedPromise]] to <a>a new promise</a>.
  1. Otherwise, if _state_ is `"erroring"`,
      1. Set *this*.[[readyPromise]] to <a>a promise rejected with</a> _stream_.[[storedError]].
      1. Set *this*.[[readyPromise]].[[PromiseIsHandled]] to *true*.
      1. Set *this*.[[closedPromise]] to <a>a new promise</a>.
  1. Otherwise, if _state_ is `"closed"`,
    1. Set *this*.[[readyPromise]] to <a>a promise resolved with</a> *undefined*.
    1. Set *this*.[[closedPromise]] to <a>a promise resolved with</a> *undefined*.
  1. Otherwise,
    1. Assert: _state_ is `"errored"`.
    1. Let _storedError_ be _stream_.[[storedError]].
    1. Set *this*.[[readyPromise]] to <a>a promise rejected with</a> _storedError_.
    1. Set *this*.[[readyPromise]].[[PromiseIsHandled]] to *true*.
    1. Set *this*.[[closedPromise]] to <a>a promise rejected with</a> _storedError_.
    1. Set *this*.[[closedPromise]].[[PromiseIsHandled]] to *true*.
</emu-alg>

<h4 id="default-writer-prototype">Properties of the {{WritableStreamDefaultWriter}} prototype</h4>

<h5 id="default-writer-closed" attribute for="WritableStreamDefaultWriter" lt="closed">get closed</h5>

<div class="note">
  The <code>closed</code> getter returns a promise that will be fulfilled when the stream becomes closed, or rejected if
  the stream ever errors or the writer's lock is <a lt="release a write lock">released</a> before the stream finishes
  closing.
</div>

<emu-alg>
  1. If ! IsWritableStreamDefaultWriter(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return *this*.[[closedPromise]].
</emu-alg>

<h5 id="default-writer-desired-size" attribute for="WritableStreamDefaultWriter" lt="desiredSize">get desiredSize</h5>

<div class="note">
  The <code>desiredSize</code> getter returns the <a lt="desired size to fill a stream's internal queue">desired size to
  fill the stream's internal queue</a>. It can be negative, if the queue is over-full. A <a>producer</a> can use this
  information to determine the right amount of data to write.

  It will be <emu-val>null</emu-val> if the stream cannot be successfully written to (due to either being errored, or
  having an abort queued up). It will return zero if the stream is closed. The getter will throw an exception if invoked
  when the writer's lock is <a lt="release a write lock">released</a>.
</div>

<emu-alg>
  1. If ! IsWritableStreamDefaultWriter(*this*) is *false*, throw a *TypeError* exception.
  1. If *this*.[[ownerWritableStream]] is *undefined*, throw a *TypeError* exception.
  1. Return ! WritableStreamDefaultWriterGetDesiredSize(*this*).
</emu-alg>

<h5 id="default-writer-ready" attribute for="WritableStreamDefaultWriter" lt="ready">get ready</h5>

<div class="note">
  The <code>ready</code> getter returns a promise that will be fulfilled when the <a lt="desired size to fill a stream's
  internal queue">desired size to fill the stream's internal queue</a> transitions from non-positive to positive,
  signaling that it is no longer applying <a>backpressure</a>. Once the <a lt="desired size to fill a stream's internal
  queue">desired size to fill the stream's internal queue</a> dips back to zero or below, the getter will return a new
  promise that stays pending until the next transition.

  If the stream becomes errored or aborted, or the writer's lock is <a lt="release a write lock">released</a>, the
  returned promise will become rejected.
</div>

<emu-alg>
  1. If ! IsWritableStreamDefaultWriter(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return *this*.[[readyPromise]].
</emu-alg>

<h5 id="default-writer-abort" method for="WritableStreamDefaultWriter">abort(<var>reason</var>)</h5>

<div class="note">
  If the writer is <a lt="active writer">active</a>, the <code>abort</code> method behaves the same as that for the
  associated stream. (Otherwise, it returns a rejected promise.)
</div>

<emu-alg>
  1. If ! IsWritableStreamDefaultWriter(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If *this*.[[ownerWritableStream]] is *undefined*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return ! WritableStreamDefaultWriterAbort(*this*, _reason_).
</emu-alg>

<h5 id="default-writer-close" method for="WritableStreamDefaultWriter">close()</h5>

<div class="note">
  If the writer is <a lt="active writer">active</a>, the <code>close</code> method behaves the same as that for the
  associated stream. (Otherwise, it returns a rejected promise.)
</div>

<emu-alg>
  1. If ! IsWritableStreamDefaultWriter(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Let _stream_ be *this*.[[ownerWritableStream]].
  1. If _stream_ is *undefined*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If ! WritableStreamCloseQueuedOrInFlight(_stream_) is *true*, return <a>a promise rejected with</a> a *TypeError*
     exception.
  1. Return ! WritableStreamDefaultWriterClose(*this*).
</emu-alg>

<h5 id="default-writer-release-lock" method for="WritableStreamDefaultWriter">releaseLock()</h5>

<div class="note">
  The <code>releaseLock</code> method <a lt="release a write lock">releases the writer's lock</a> on the corresponding
  stream. After the lock is released, the writer is no longer <a lt="active writer">active</a>. If the associated
  stream is errored when the lock is released, the writer will appear errored in the same way from now on; otherwise,
  the writer will appear closed.

  Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the promises
  returned from previous calls to {{WritableStreamDefaultWriter/write()}} have not yet settled). It's not necessary to
  hold the lock on the writer for the duration of the write; the lock instead simply prevents other <a>producers</a>
  from writing in an interleaved manner.
</div>

<emu-alg>
  1. If ! IsWritableStreamDefaultWriter(*this*) is *false*, throw a *TypeError* exception.
  1. Let _stream_ be *this*.[[ownerWritableStream]].
  1. If _stream_ is *undefined*, return.
  1. Assert: _stream_.[[writer]] is not *undefined*.
  1. Perform ! WritableStreamDefaultWriterRelease(*this*).
</emu-alg>

<h5 id="default-writer-write" method for="WritableStreamDefaultWriter">write(<var>chunk</var>)</h5>

<div class="note">
  The <code>write</code> method writes the given <a>chunk</a> to the writable stream, by waiting until any previous
  writes have finished successfully, and then sending the <a>chunk</a> to the <a>underlying sink</a>'s {{underlying
  sink/write()}} method. It will return a promise that fulfills with <emu-val>undefined</emu-val> upon a successful
  write, or rejects if the write fails or stream becomes errored before the writing process is initiated.

  Note that what "success" means is up to the <a>underlying sink</a>; it might indicate simply that the <a>chunk</a> has
  been accepted, and not necessarily that it is safely saved to its ultimate destination.
</div>

<emu-alg>
  1. If ! IsWritableStreamDefaultWriter(*this*) is *false*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. If *this*.[[ownerWritableStream]] is *undefined*, return <a>a promise rejected with</a> a *TypeError* exception.
  1. Return ! WritableStreamDefaultWriterWrite(*this*, _chunk_).
</emu-alg>

<h3 id="rs-writer-abstract-ops">Writable stream writer abstract operations</h3>

<h4 id="is-writable-stream-default-writer" aoid="IsWritableStreamDefaultWriter" nothrow>IsWritableStreamDefaultWriter (
<var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have an [[ownerWritableStream]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="writable-stream-default-writer-abort" aoid="WritableStreamDefaultWriterAbort"
nothrow>WritableStreamDefaultWriterAbort ( <var>writer</var>, <var>reason</var> )</h4>

<emu-alg>
  1. Let _stream_ be _writer_.[[ownerWritableStream]].
  1. Assert: _stream_ is not *undefined*.
  1. Return ! WritableStreamAbort(_stream_, _reason_).
</emu-alg>

<h4 id="writable-stream-default-writer-close" aoid="WritableStreamDefaultWriterClose"
nothrow>WritableStreamDefaultWriterClose ( <var>writer</var> )</h4>

<emu-alg>
  1. Let _stream_ be _writer_.[[ownerWritableStream]].
  1. Assert: _stream_ is not *undefined*.
  1. Return ! WritableStreamClose(_stream_).
</emu-alg>

<h4 id="writable-stream-default-writer-close-with-error-propagation" aoid="WritableStreamDefaultWriterCloseWithErrorPropagation"
nothrow>WritableStreamDefaultWriterCloseWithErrorPropagation ( <var>writer</var> )</h4>

<p class="note">This abstract operation helps implement the error propagation semantics of
{{ReadableStream/pipeTo()}}.</p>

<emu-alg>
  1. Let _stream_ be _writer_.[[ownerWritableStream]].
  1. Assert: _stream_ is not *undefined*.
  1. Let _state_ be _stream_.[[state]].
  1. If ! WritableStreamCloseQueuedOrInFlight(_stream_) is *true* or _state_ is `"closed"`, return
     <a>a promise resolved with</a> *undefined*.
  1. If _state_ is `"errored"`, return <a>a promise rejected with</a> _stream_.[[storedError]].
  1. Assert: _state_ is `"writable"` or `"erroring"`.
  1. Return ! WritableStreamDefaultWriterClose(_writer_).
</emu-alg>

<h4 id="writable-stream-default-writer-ensure-closed-promise-rejected"
aoid="WritableStreamDefaultWriterEnsureClosedPromiseRejected"
nothrow>WritableStreamDefaultWriterEnsureClosedPromiseRejected( <var>writer</var>, <var>error</var> )</h4>

<emu-alg>
  1. If _writer_.[[closedPromise]].[[PromiseState]] is `"pending"`, <a>reject</a> _writer_.[[closedPromise]] with
     _error_.
  1. Otherwise, set _writer_.[[closedPromise]] to <a>a promise rejected with</a> _error_.
  1. Set _writer_.[[closedPromise]].[[PromiseIsHandled]] to *true*.
</emu-alg>

<h4 id="writable-stream-default-writer-ensure-ready-promise-rejected"
aoid="WritableStreamDefaultWriterEnsureReadyPromiseRejected"
nothrow>WritableStreamDefaultWriterEnsureReadyPromiseRejected( <var>writer</var>, <var>error</var> )</h4>

<emu-alg>
  1. If _writer_.[[readyPromise]].[[PromiseState]] is `"pending"`, <a>reject</a> _writer_.[[readyPromise]] with _error_.
  1. Otherwise, set _writer_.[[readyPromise]] to <a>a promise rejected with</a> _error_.
  1. Set _writer_.[[readyPromise]].[[PromiseIsHandled]] to *true*.
</emu-alg>

<h4 id="writable-stream-default-writer-get-desired-size" aoid="WritableStreamDefaultWriterGetDesiredSize"
nothrow>WritableStreamDefaultWriterGetDesiredSize ( <var>writer</var> )</h4>

<emu-alg>
  1. Let _stream_ be _writer_.[[ownerWritableStream]].
  1. Let _state_ be _stream_.[[state]].
  1. If _state_ is `"errored"` or `"erroring"`, return *null*.
  1. If _state_ is `"closed"`, return *0*.
  1. Return ! WritableStreamDefaultControllerGetDesiredSize(_stream_.[[writableStreamController]]).
</emu-alg>

<h4 id="writable-stream-default-writer-release" aoid="WritableStreamDefaultWriterRelease"
nothrow>WritableStreamDefaultWriterRelease ( <var>writer</var> )</h4>

<emu-alg>
  1. Let _stream_ be _writer_.[[ownerWritableStream]].
  1. Assert: _stream_ is not *undefined*.
  1. Assert: _stream_.[[writer]] is _writer_.
  1. Let _releasedError_ be a new *TypeError*.
  1. Perform ! WritableStreamDefaultWriterEnsureReadyPromiseRejected(_writer_, _releasedError_).
  1. Perform ! WritableStreamDefaultWriterEnsureClosedPromiseRejected(_writer_, _releasedError_).
  1. Set _stream_.[[writer]] to *undefined*.
  1. Set _writer_.[[ownerWritableStream]] to *undefined*.
</emu-alg>

<h4 id="writable-stream-default-writer-write" aoid="WritableStreamDefaultWriterWrite"
nothrow>WritableStreamDefaultWriterWrite ( <var>writer</var>, <var>chunk</var> )</h4>

<emu-alg>
  1. Let _stream_ be _writer_.[[ownerWritableStream]].
  1. Assert: _stream_ is not *undefined*.
  1. Let _controller_ be _stream_.[[writableStreamController]].
  1. Let _chunkSize_ be ! WritableStreamDefaultControllerGetChunkSize(_controller_, _chunk_).
  1. If _stream_ is not equal to _writer_.[[ownerWritableStream]], return <a>a promise rejected with</a> a *TypeError*
     exception.
  1. Let _state_ be _stream_.[[state]].
  1. If _state_ is `"errored"`, return <a>a promise rejected with</a> _stream_.[[storedError]].
  1. If ! WritableStreamCloseQueuedOrInFlight(_stream_) is *true* or _state_ is `"closed"`, return
     <a>a promise rejected with</a> a *TypeError* exception indicating that the stream is closing or closed.
  1. If _state_ is `"erroring"`, return <a>a promise rejected with</a> _stream_.[[storedError]].
  1. Assert: _state_ is `"writable"`.
  1. Let _promise_ be ! WritableStreamAddWriteRequest(_stream_).
  1. Perform ! WritableStreamDefaultControllerWrite(_controller_, _chunk_, _chunkSize_).
  1. Return _promise_.
</emu-alg>

<h3 id="ws-default-controller-class" interface lt="WritableStreamDefaultController">Class
<code>WritableStreamDefaultController</code></h3>

The {{WritableStreamDefaultController}} class has methods that allow control of a {{WritableStream}}'s state. When
constructing a {{WritableStream}}, the <a>underlying sink</a> is given a corresponding
{{WritableStreamDefaultController}} instance to manipulate.

<h4 id="ws-default-controller-class-definition">Class definition</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{WritableStreamDefaultController}} class in something close to the syntax of [[!ECMASCRIPT]],
it would look like

<pre><code class="lang-javascript">
  class WritableStreamDefaultController {
    <a href="#ws-default-controller-constructor">constructor</a>() // always throws

    <a href="#ws-default-controller-error">error</a>(e)
  }
</code></pre>

</div>

<h4 id="ws-default-controller-internal-slots">Internal slots</h4>

Instances of {{WritableStreamDefaultController}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[abortAlgorithm]]
    <td class="non-normative">A promise-returning algorithm, taking one argument (the abort reason), which communicates
      a requested abort to the <a>underlying sink</a>
  </tr>
  <tr>
    <td>\[[closeAlgorithm]]
    <td class="non-normative">A promise-returning algorithm which communicates a requested close to the <a>underlying
      sink</a>
  </tr>
  <tr>
    <td>\[[controlledWritableStream]]
    <td class="non-normative">The {{WritableStream}} instance controlled
  </tr>
  <tr>
    <td>\[[queue]]
    <td class="non-normative">A List representing the stream's internal queue of <a>chunks</a>
  </tr>
  <tr>
    <td>\[[queueTotalSize]]
    <td class="non-normative">The total size of all the chunks stored in \[[queue]] (see [[#queue-with-sizes]])
  </tr>
  <tr>
    <td>\[[started]]
    <td class="non-normative">A boolean flag indicating whether the <a>underlying sink</a> has finished starting
  </tr>
  <tr>
    <td>\[[strategyHWM]]
    <td class="non-normative">A number supplied by the creator of the stream as part of the stream's <a>queuing
      strategy</a>, indicating the point at which the stream will apply <a>backpressure</a> to its <a>underlying
      sink</a>
  </tr>
  <tr>
    <td>\[[strategySizeAlgorithm]]
    <td class="non-normative">An algorithm to calculate the size of enqueued <a>chunks</a>, as part of the stream’s
      <a>queuing strategy</a>
  </tr>
  <tr>
    <td>\[[writeAlgorithm]]
    <td class="non-normative">A promise-returning algorithm, taking one argument (the <a>chunk</a> to write), which
      writes data to the <a>underlying sink</a>
  </tr>
</table>

<h4 id="ws-default-controller-constructor" constructor for="WritableStreamDefaultController"
lt="WritableStreamDefaultController()">new WritableStreamDefaultController()</h4>

<div class="note">
  The <code>WritableStreamDefaultController</code> constructor cannot be used directly;
  {{WritableStreamDefaultController}} instances are created automatically during {{WritableStream}} construction.
</div>

<emu-alg>
  1. Throw a *TypeError* exception.
</emu-alg>

<h4 id="ws-default-controller-prototype">Properties of the {{WritableStreamDefaultController}} prototype</h4>

<h5 id="ws-default-controller-error" method for="WritableStreamDefaultController">error(<var>e</var>)</h5>

<div class="note">
  The <code>error</code> method will error the writable stream, making all future interactions with it fail with the
  given error <code>e</code>.

  This method is rarely used, since usually it suffices to return a rejected promise from one of the <a>underlying
  sink</a>'s methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
  normal lifecycle of interactions with the <a>underlying sink</a>.
</div>

<emu-alg>
  1. If ! IsWritableStreamDefaultController(*this*) is *false*, throw a *TypeError* exception.
  1. Let _state_ be *this*.[[controlledWritableStream]].[[state]].
  1. If _state_ is not `"writable"`, return.
  1. Perform ! WritableStreamDefaultControllerError(*this*, _e_).
</emu-alg>

<h4 id="ws-default-controller-internal-methods">Writable stream default controller internal methods</h4>

The following are additional internal methods implemented by each {{WritableStreamDefaultController}} instance. The
writable stream implementation will call into these.

<p class="note">The reason these are in method form, instead of as abstract operations, is to make it clear that the
writable stream implementation is decoupled from the controller implementation, and could in the future be expanded with
other controllers, as long as those controllers implemented such internal methods. A similar scenario is seen for
readable streams, where there actually are multiple controller types and as such the counterpart internal methods are
used polymorphically.

<h5 id="ws-default-controller-private-abort" oldids="writable-stream-default-controller-abort">\[[AbortSteps]](
<var>reason</var> )</h5>

<emu-alg>
  1. Let _result_ be the result of performing *this*.[[abortAlgorithm]], passing _reason_.
  1. Perform ! WritableStreamDefaultControllerClearAlgorithms(*this*).
  1. Return _result_.
</emu-alg>

<h5 id="ws-default-controller-private-error">\[[ErrorSteps]]()</h5>

<emu-alg>
  1. Perform ! ResetQueue(*this*).
</emu-alg>

<h3 id="ws-default-controller-abstract-ops">Writable stream default controller abstract operations</h3>

<h4 id="is-writable-stream-default-controller" aoid="IsWritableStreamDefaultController"
nothrow>IsWritableStreamDefaultController ( <var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have an [[controlledWritableStream]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="set-up-writable-stream-default-controller" aoid="SetUpWritableStreamDefaultController"
throws>SetUpWritableStreamDefaultController ( <var>stream</var>, <var>controller</var>, <var>startAlgorithm</var>,
<var>writeAlgorithm</var>, <var>closeAlgorithm</var>, <var>abortAlgorithm</var>, <var>highWaterMark</var>, <var>sizeAlgorithm</var> )</h4>

<emu-alg>
  1. Assert: ! IsWritableStream(_stream_) is *true*.
  1. Assert: _stream_.[[writableStreamController]] is *undefined*.
  1. Set _controller_.[[controlledWritableStream]] to _stream_.
  1. Set _stream_.[[writableStreamController]] to _controller_.
  1. Perform ! ResetQueue(_controller_).
  1. Set _controller_.[[started]] to *false*.
  1. Set _controller_.[[strategySizeAlgorithm]] to _sizeAlgorithm_.
  1. Set _controller_.[[strategyHWM]] to _highWaterMark_.
  1. Set _controller_.[[writeAlgorithm]] to _writeAlgorithm_.
  1. Set _controller_.[[closeAlgorithm]] to _closeAlgorithm_.
  1. Set _controller_.[[abortAlgorithm]] to _abortAlgorithm_.
  1. Let _backpressure_ be ! WritableStreamDefaultControllerGetBackpressure(_controller_).
  1. Perform ! WritableStreamUpdateBackpressure(_stream_, _backpressure_).
  1. Let _startResult_ be the result of performing _startAlgorithm_. (This may throw an exception.)
  1. Let _startPromise_ be <a>a promise resolved with</a> _startResult_.
  1. <a>Upon fulfillment</a> of _startPromise_,
    1. Assert: _stream_.[[state]] is `"writable"` or `"erroring"`.
    1. Set _controller_.[[started]] to *true*.
    1. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(_controller_).
  1. <a>Upon rejection</a> of _startPromise_ with reason _r_,
    1. Assert: _stream_.[[state]] is `"writable"` or `"erroring"`.
    1. Set _controller_.[[started]] to *true*.
    1. Perform ! WritableStreamDealWithRejection(_stream_, _r_).
</emu-alg>

<h4 id="set-up-writable-stream-default-controller-from-underlying-sink"
aoid="SetUpWritableStreamDefaultControllerFromUnderlyingSink"
throws>SetUpWritableStreamDefaultControllerFromUnderlyingSink ( <var>stream</var>, <var>underlyingSink</var>,
<var>highWaterMark</var>, <var>sizeAlgorithm</var> )</h4>

<emu-alg>
  1. Assert: _underlyingSink_ is not *undefined*.
  1. Let _controller_ be ObjectCreate(the original value of `<a idl>WritableStreamDefaultController</a>`'s `prototype`
     property).
  1. Let _startAlgorithm_ be the following steps:
    1. Return ? InvokeOrNoop(_underlyingSink_, `"start"`, « _controller_ »).
  1. Let _writeAlgorithm_ be ? CreateAlgorithmFromUnderlyingMethod(_underlyingSink_, `"write"`, *1*, « _controller_ »).
  1. Let _closeAlgorithm_ be ? CreateAlgorithmFromUnderlyingMethod(_underlyingSink_, `"close"`, *0*, « »).
  1. Let _abortAlgorithm_ be ? CreateAlgorithmFromUnderlyingMethod(_underlyingSink_, `"abort"`, *1*, « »).
  1. Perform ? SetUpWritableStreamDefaultController(_stream_, _controller_, _startAlgorithm_, _writeAlgorithm_,
     _closeAlgorithm_, _abortAlgorithm_, _highWaterMark_, _sizeAlgorithm_).
</emu-alg>

<h4 id="writable-stream-default-controller-clear-algorithms" aoid="WritableStreamDefaultControllerClearAlgorithms"
nothrow>WritableStreamDefaultControllerClearAlgorithms ( <var>controller</var> )</h4>

This abstract operation is called once the stream is closed or errored and the algorithms will not be executed any more.
By removing the algorithm references it permits the <a>underlying sink</a> object to be garbage collected even if the
{{WritableStream}} itself is still referenced.

<p class="note">The results of this algorithm are not currently observable, but could become so if JavaScript eventually
adds <a href="https://github.com/tc39/proposal-weakrefs/">weak references</a>. But even without that factor,
implementations will likely want to include similar steps.</p>

<p class="note">This operation will be performed multiple times in some edge cases. After the first time it will do
nothing.</p>

<emu-alg>
  1. Set _controller_.[[writeAlgorithm]] to *undefined*.
  1. Set _controller_.[[closeAlgorithm]] to *undefined*.
  1. Set _controller_.[[abortAlgorithm]] to *undefined*.
  1. Set _controller_.[[strategySizeAlgorithm]] to *undefined*.
</emu-alg>

<h4 id="writable-stream-default-controller-close" aoid="WritableStreamDefaultControllerClose"
nothrow>WritableStreamDefaultControllerClose ( <var>controller</var> )</h4>

<emu-alg>
  1. Perform ! EnqueueValueWithSize(_controller_, `"close"`, *0*).
  1. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(_controller_).
</emu-alg>

<h4 id="writable-stream-default-controller-get-chunk-size" aoid="WritableStreamDefaultControllerGetChunkSize"
nothrow>WritableStreamDefaultControllerGetChunkSize ( <var>controller</var>, <var>chunk</var> )</h4>

<emu-alg>
  1. Let _returnValue_ be the result of performing _controller_.[[strategySizeAlgorithm]], passing in _chunk_, and
     interpreting the result as an ECMAScript completion value.
  1. If _returnValue_ is an abrupt completion,
    1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(_controller_, _returnValue_.[[Value]]).
    1. Return 1.
  1. Return _returnValue_.[[Value]].
</emu-alg>

<h4 id="writable-stream-default-controller-get-desired-size" aoid="WritableStreamDefaultControllerGetDesiredSize"
nothrow>WritableStreamDefaultControllerGetDesiredSize ( <var>controller</var> )</h4>

<emu-alg>
  1. Return _controller_.[[strategyHWM]] − _controller_.[[queueTotalSize]].
</emu-alg>

<h4 id="writable-stream-default-controller-write" aoid="WritableStreamDefaultControllerWrite"
nothrow>WritableStreamDefaultControllerWrite ( <var>controller</var>, <var>chunk</var>, <var ignore>chunkSize</var>
)</h4>

<emu-alg>
  1. Let _writeRecord_ be Record {[[chunk]]: _chunk_}.
  1. Let _enqueueResult_ be EnqueueValueWithSize(_controller_, _writeRecord_, _chunkSize_).
  1. If _enqueueResult_ is an abrupt completion,
    1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(_controller_, _enqueueResult_.[[Value]]).
    1. Return.
  1. Let _stream_ be _controller_.[[controlledWritableStream]].
  1. If ! WritableStreamCloseQueuedOrInFlight(_stream_) is *false* and _stream_.[[state]] is `"writable"`,
    1. Let _backpressure_ be ! WritableStreamDefaultControllerGetBackpressure(_controller_).
    1. Perform ! WritableStreamUpdateBackpressure(_stream_, _backpressure_).
  1. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(_controller_).
</emu-alg>

<h4 id="writable-stream-default-controller-advance-queue-if-needed"
aoid="WritableStreamDefaultControllerAdvanceQueueIfNeeded" nothrow>WritableStreamDefaultControllerAdvanceQueueIfNeeded (
<var>controller</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledWritableStream]].
  1. If _controller_.[[started]] is *false*, return.
  1. If _stream_.[[inFlightWriteRequest]] is not *undefined*, return.
  1. Let _state_ be _stream_.[[state]].
  1. Assert: _state_ is not `"closed"` or `"errored"`.
  1. If _state_ is `"erroring"`,
    1. Perform ! WritableStreamFinishErroring(_stream_).
    1. Return.
  1. If _controller_.[[queue]] is empty, return.
  1. Let _writeRecord_ be ! PeekQueueValue(_controller_).
  1. If _writeRecord_ is `"close"`, perform ! WritableStreamDefaultControllerProcessClose(_controller_).
  1. Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(_controller_, _writeRecord_.[[chunk]]).
</emu-alg>

<h4 id="writable-stream-default-controller-error-if-needed" aoid="WritableStreamDefaultControllerErrorIfNeeded"
nothrow>WritableStreamDefaultControllerErrorIfNeeded ( <var>controller</var>, <var>error</var> )</h4>

<emu-alg>
  1. If _controller_.[[controlledWritableStream]].[[state]] is `"writable"`, perform !
     WritableStreamDefaultControllerError(_controller_, _error_).
</emu-alg>

<h4 id="writable-stream-default-controller-process-close" aoid="WritableStreamDefaultControllerProcessClose"
nothrow>WritableStreamDefaultControllerProcessClose ( <var>controller</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledWritableStream]].
  1. Perform ! WritableStreamMarkCloseRequestInFlight(_stream_).
  1. Perform ! DequeueValue(_controller_).
  1. Assert: _controller_.[[queue]] is empty.
  1. Let _sinkClosePromise_ be the result of performing _controller_.[[closeAlgorithm]].
  1. Perform ! WritableStreamDefaultControllerClearAlgorithms(_controller_).
  1. <a>Upon fulfillment</a> of _sinkClosePromise_,
    1. Perform ! WritableStreamFinishInFlightClose(_stream_).
  1. <a>Upon rejection</a> of _sinkClosePromise_ with reason _reason_,
    1. Perform ! WritableStreamFinishInFlightCloseWithError(_stream_, _reason_).
</emu-alg>

<h4 id="writable-stream-default-controller-process-write" aoid="WritableStreamDefaultControllerProcessWrite"
nothrow>WritableStreamDefaultControllerProcessWrite ( <var>controller</var>, <var>chunk</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledWritableStream]].
  1. Perform ! WritableStreamMarkFirstWriteRequestInFlight(_stream_).
  1. Let _sinkWritePromise_ be the result of performing _controller_.[[writeAlgorithm]], passing in _chunk_.
  1. <a>Upon fulfillment</a> of _sinkWritePromise_,
    1. Perform ! WritableStreamFinishInFlightWrite(_stream_).
    1. Let _state_ be _stream_.[[state]].
    1. Assert: _state_ is `"writable"` or `"erroring"`.
    1. Perform ! DequeueValue(_controller_).
    1. If ! WritableStreamCloseQueuedOrInFlight(_stream_) is *false* and _state_ is `"writable"`,
      1. Let _backpressure_ be ! WritableStreamDefaultControllerGetBackpressure(_controller_).
      1. Perform ! WritableStreamUpdateBackpressure(_stream_, _backpressure_).
    1. Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(_controller_).
  1. <a>Upon rejection</a> of _sinkWritePromise_ with _reason_,
    1. If _stream_.[[state]] is `"writable"`, perform ! WritableStreamDefaultControllerClearAlgorithms(_controller_).
    1. Perform ! WritableStreamFinishInFlightWriteWithError(_stream_, _reason_).
</emu-alg>

<h4 id="writable-stream-default-controller-get-backpressure" aoid="WritableStreamDefaultControllerGetBackpressure"
nothrow>WritableStreamDefaultControllerGetBackpressure ( <var>controller</var> )</h4>

<emu-alg>
  1. Let _desiredSize_ be ! WritableStreamDefaultControllerGetDesiredSize(_controller_).
  1. Return _desiredSize_ ≤ *0*.
</emu-alg>

<h4 id="writable-stream-default-controller-error" aoid="WritableStreamDefaultControllerError"
nothrow>WritableStreamDefaultControllerError ( <var>controller</var>, <var>error</var> )</h4>

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledWritableStream]].
  1. Assert: _stream_.[[state]] is `"writable"`.
  1. Perform ! WritableStreamDefaultControllerClearAlgorithms(_controller_).
  1. Perform ! WritableStreamStartErroring(_stream_, _error_).
</emu-alg>

<h2 id="ts">Transform streams</h2>

<h3 id="ts-intro">Using transform streams</h3>

<div class="example" id="example-basic-pipe-through">
  The natural way to use a transform stream is to place it in a <a lt="piping">pipe</a> between a <a>readable stream</a>
  and a <a>writable stream</a>. <a>Chunks</a> that travel from the <a>readable stream</a> to the <a>writable stream</a>
  will be transformed as they pass through the transform stream. <a>Backpressure</a> is respected, so data will not be
  read faster than it can be transformed and consumed.

  <pre><code class="lang-javascript">
    readableStream
      .pipeThrough(transformStream)
      .pipeTo(writableStream)
      .then(() => console.log("All data successfully transformed!"))
      .catch(e => console.error("Something went wrong!", e));
  </code></pre>
</div>

<div class="example" id="example-transform-stream-properties">
  You can also use the {{TransformStream/readable}} and {{TransformStream/writable}} properties of a transform stream
  directly to access the usual interfaces of a <a>readable stream</a> and <a>writable stream</a>. In this example we
  supply data to the <a>writable side</a> of the stream using its <a>writer</a> interface. The <a>readable side</a> is
  then piped to <code>anotherWritableStream</code>.

  <pre><code class="lang-javascript">
    const writer = transformStream.writable.getWriter();
    writer.write("input chunk");
    transformStream.readable.pipeTo(anotherWritableStream);
  </code></pre>
</div>

<div class="example" id="example-transform-identity">
  One use of <a>identity transform streams</a> is to easily convert between readable and writable streams. For example,
  the {{fetch()}} API accepts a readable stream <a for="request" lt="body">request body</a>, but it can be more
  convenient to write data for uploading via a writable stream interface. Using an identity transform stream addresses
  this:

  <pre><code class="lang-javascript">
    const { writable, readable } = new TransformStream();
    fetch("...", { body: readable }).then(response => /* ... */);

    const writer = writable.getWriter();
    writer.write(new Uint8Array([0x73, 0x74, 0x72, 0x65, 0x61, 0x6D, 0x73, 0x21]));
    writer.close();
  </code></pre>

  Another use of identity transform streams is to add additional buffering to a <a>pipe</a>. In this example we add
  extra buffering between <code>readableStream</code> and <code>writableStream</code>.

  <pre><code class="lang-javascript">
    const writableStrategy = new ByteLengthQueuingStrategy({ highWaterMark: 1024 * 1024 });

    readableStream
      .pipeThrough(new TransformStream(undefined, writableStrategy))
      .pipeTo(writableStream);
  </code></pre>
</div>

<h3 id="ts-class" interface lt="TransformStream">Class <code>TransformStream</code></h3>

<h4 id="ts-class-definition">Class definition</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{TransformStream}} class in something close to the syntax of [[!ECMASCRIPT]], it would look
like

<pre><code class="lang-javascript">
  class TransformStream {
    <a href="#ts-constructor">constructor</a>(<a href="#transformer-api">transformer</a> = {}, <a
    href="#qs-api">writableStrategy</a> = {}, <a href="#qs-api">readableStrategy</a> = {})

    get <a href="#ts-readable">readable</a>()
    get <a href="#ts-writable">writable</a>()
  }
</code></pre>

</div>

<h4 id="ts-internal-slots">Internal slots</h4>

Instances of {{TransformStream}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[backpressure]]
    <td class="non-normative">Whether there was backpressure on \[[readable]] the last time it was observed
  </tr>
  <tr>
    <td>\[[backpressureChangePromise]]
    <td class="non-normative">A promise which is fulfilled and replaced every time the value of \[[backpressure]]
    changes
  </tr>
  <tr>
    <td>\[[readable]]
    <td class="non-normative">The {{ReadableStream}} instance controlled by this object
  </tr>
  <tr>
    <td>\[[transformStreamController]]
    <td class="non-normative">A {{TransformStreamDefaultController}} created with the ability to control \[[readable]]
    and \[[writable]]; also used for the <a href="#is-transform-stream">IsTransformStream</a> brand check
  </tr>
  <tr>
    <td>\[[writable]]
    <td class="non-normative">The {{WritableStream}} instance controlled by this object
  </tr>
</table>

<h4 id="ts-constructor" constructor for="TransformStream" lt="TransformStream(transformer, writableStrategy,
readableStrategy)">new TransformStream(<var>transformer</var> = {}, <var ignore>writableStrategy</var> = {},
<var ignore>readableStrategy</var> = {})</h4>

<div class="note">
  The <code>transformer</code> argument represents the <a>transformer</a>, as described in [[#transformer-api]].

  The <code>writableStrategy</code> and <code>readableStrategy</code> arguments are the <a>queuing strategy</a> objects
  for the writable and readable sides respectively. These are used in the construction of the {{WritableStream}} and
  {{ReadableStream}} objects and can be used to add buffering to a {{TransformStream}}, in order to smooth out
  variations in the speed of the transformation, or to increase the amount of buffering in a <a>pipe</a>. If they are
  not provided, the default behavior will be the same as a {{CountQueuingStrategy}}, with respective <a>high water
  marks</a> of 1 and 0.
</div>

<emu-alg>
  1. Let _writableSizeFunction_ be ? GetV(_writableStrategy_, `"size"`).
  1. Let _writableHighWaterMark_ be ? GetV(_writableStrategy_, `"highWaterMark"`).
  1. Let _readableSizeFunction_ be ? GetV(_readableStrategy_, `"size"`).
  1. Let _readableHighWaterMark_ be ? GetV(_readableStrategy_, `"highWaterMark"`).
  1. Let _writableType_ be ? GetV(_transformer_, `"writableType"`).
  1. If _writableType_ is not *undefined*, throw a *RangeError* exception.
  1. Let _writableSizeAlgorithm_ be ? MakeSizeAlgorithmFromSizeFunction(_writableSizeFunction_).
  1. If _writableHighWaterMark_ is *undefined*, set _writableHighWaterMark_ to *1*.
  1. Set _writableHighWaterMark_ to ? ValidateAndNormalizeHighWaterMark(_writableHighWaterMark_).
  1. Let _readableType_ be ? GetV(_transformer_, `"readableType"`).
  1. If _readableType_ is not *undefined*, throw a *RangeError* exception.
  1. Let _readableSizeAlgorithm_ be ? MakeSizeAlgorithmFromSizeFunction(_readableSizeFunction_).
  1. If _readableHighWaterMark_ is *undefined*, set _readableHighWaterMark_ to *0*.
  1. Set _readableHighWaterMark_ be ? ValidateAndNormalizeHighWaterMark(_readableHighWaterMark_).
  1. Let _startPromise_ be <a>a new promise</a>.
  1. Perform ! InitializeTransformStream(*this*, _startPromise_, _writableHighWaterMark_, _writableSizeAlgorithm_,
     _readableHighWaterMark_, _readableSizeAlgorithm_).
  1. Perform ? SetUpTransformStreamDefaultControllerFromTransformer(*this*, _transformer_).
  1. Let _startResult_ be ? InvokeOrNoop(_transformer_, `"start"`, « *this*.[[transformStreamController]] »).
  1. <a>Resolve</a> _startPromise_ with _startResult_.
</emu-alg>

<h4 id="transformer-api">Transformer API</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

The {{TransformStream()}} constructor accepts as its first argument a JavaScript object representing the
<a>transformer</a>. Such objects can contain any of the following methods:

<dl>
  <dt><dfn method for="transformer">start(<var>controller</var>)</dfn></dt>
  <dd>
    <p>A function that is called immediately during creation of the {{TransformStream}}.</p>

    <p>Typically this is used to enqueue prefix <a>chunks</a>, using
    {{TransformStreamDefaultController/enqueue()|controller.enqueue()}}. Those chunks will be read from the <a>readable
    side</a> but don't depend on any writes to the <a>writable side</a>.</p>

    <p>If this initial process is asynchronous, for example because it takes some effort to acquire the prefix
    chunks, the function can return a promise to signal success or failure; a rejected promise will error the stream.
    Any thrown exceptions will be re-thrown by the {{TransformStream()}} constructor.</p>
  </dd>

  <dt><dfn method for="transformer">transform(<var>chunk</var>, <var>controller</var>)</dfn></dt>
  <dd>
    <p>A function called when a new <a>chunk</a> originally written to the <a>writable side</a> is ready to be
    transformed. The stream implementation guarantees that this function will be called only after previous transforms
    have succeeded, and never before {{underlying sink/start()}} has completed or after {{transformer/flush()}} has been
    called.</p>

    <p>This function performs the actual transformation work of the transform stream. It can enqueue the results using
    {{TransformStreamDefaultController/enqueue()|controller.enqueue()}}. This permits a single chunk written to the
    writable side to result in zero or multiple chunks on the <a>readable side</a>, depending on how many times
    {{TransformStreamDefaultController/enqueue()|controller.enqueue()}} is called. [[#example-ts-lipfuzz]] demonstrates
    this by sometimes enqueuing zero chunks.</p>

    <p>If the process of transforming is asynchronous, this function can return a promise to signal success or failure
    of the transformation. A rejected promise will error both the readable and writable sides of the transform
    stream.</p>

    <p>If no {{transformer/transform()}} is supplied, the identity transform is used, which enqueues chunks unchanged
    from the writable side to the readable side.</p>
  </dd>

  <dt><dfn method for="transformer">flush(<var>controller</var>)</dfn></dt>
  <dd>
    <p>A function called after all <a>chunks</a> written to the <a>writable side</a> have been transformed by
    successfully passing through {{transformer/transform()}}, and the writable side is about to be closed.</p>

    <p>Typically this is used to enqueue suffix chunks to the <a>readable side</a>, before that too becomes closed. An
    example can be seen in [[#example-ts-lipfuzz]].</p>

    <p>If the flushing process is asynchronous, the function can return a promise to signal success or failure; the
    result will be communicated to the caller of {{WritableStreamDefaultWriter/write()|stream.writable.write()}}.
    Additionally, a rejected promise will error both the readable and writable sides of the stream. Throwing an
    exception is treated the same as returning a rejected promise.</p>

    <p>(Note that there is no need to call {{TransformStreamDefaultController/terminate()|controller.terminate()}}
    inside {{transformer/flush()}}; the stream is already in the process of successfully closing down, and terminating
    it would be counterproductive.)</p>
  </dd>
</dl>

The <code>controller</code> object passed to {{transformer/start()}}, {{transformer/transform()}}, and
{{transformer/flush()}} is an instance of {{TransformStreamDefaultController}}, and has the ability to enqueue
<a>chunks</a> to the <a>readable side</a>, or to terminate or error the stream.

</div>

<h4 id="ts-prototype">Properties of the {{TransformStream}} prototype</h4>

<h5 id="ts-readable" attribute for="TransformStream" lt="readable">get readable</h5>

<div class="note">
  The <code>readable</code> getter gives access to the <a>readable side</a> of the transform stream.
</div>

<emu-alg>
  1. If ! IsTransformStream(*this*) is *false*, throw a *TypeError* exception.
  1. Return *this*.[[readable]].
</emu-alg>

<h5 id="ts-writable" attribute for="TransformStream" lt="writable">get writable</h5>

<div class="note">
  The <code>writable</code> getter gives access to the <a>writable side</a> of the transform stream.
</div>

<emu-alg>
  1. If ! IsTransformStream(*this*) is *false*, throw a *TypeError* exception.
  1. Return *this*.[[writable]].
</emu-alg>

<h3 id="ts-abstract-ops">General transform stream abstract operations</h3>

<h4 id="create-transform-stream" aoid="CreateTransformStream" throws export>CreateTransformStream (
<var>startAlgorithm</var>, <var>transformAlgorithm</var>, <var>flushAlgorithm</var>
[, <var>writableHighWaterMark</var> [, <var>writableSizeAlgorithm</var> [, <var>readableHighWaterMark</var> [,
<var>readableSizeAlgorithm</var> ] ] ] ] )</h4>

This abstract operation is meant to be called from other specifications that wish to create {{TransformStream}}
instances. The <var>transformAlgorithm</var> and <var>flushAlgorithm</var> algorithms must return promises; if supplied,
<var>writableHighWaterMark</var> and <var>readableHighWaterMark</var> must be non-negative, non-NaN numbers; and if
supplied, <var>writableSizeAlgorithm</var> and <var>readableSizeAlgorithm</var> must be algorithms accepting
<a>chunk</a> objects and returning numbers.

<p class="note">CreateTransformStream throws an exception if and only if the supplied <var>startAlgorithm</var>
throws.</p>

<emu-alg>
  1. If _writableHighWaterMark_ was not passed, set it to *1*.
  1. If _writableSizeAlgorithm_ was not passed, set it to an algorithm that returns *1*.
  1. If _readableHighWaterMark_ was not passed, set it to *0*.
  1. If _readableSizeAlgorithm_ was not passed, set it to an algorithm that returns *1*.
  1. Assert: ! IsNonNegativeNumber(_writableHighWaterMark_) is *true*.
  1. Assert: ! IsNonNegativeNumber(_readableHighWaterMark_) is *true*.
  1. Let _stream_ be ObjectCreate(the original value of `<a idl>TransformStream</a>`'s `prototype` property).
  1. Let _startPromise_ be <a>a new promise</a>.
  1. Perform ! InitializeTransformStream(_stream_, _startPromise_, _writableHighWaterMark_, _writableSizeAlgorithm_,
     _readableHighWaterMark_, _readableSizeAlgorithm_).
  1. Let _controller_ be ObjectCreate(the original value of `<a idl>TransformStreamDefaultController</a>`'s `prototype`
     property).
  1. Perform ! SetUpTransformStreamDefaultController(_stream_, _controller_, _transformAlgorithm_, _flushAlgorithm_).
  1. Let _startResult_ be the result of performing _startAlgorithm_. (This may throw an exception.)
  1. <a>Resolve</a> _startPromise_ with _startResult_.
  1. Return _stream_.
</emu-alg>

<h4 id="initialize-transform-stream" aoid="InitializeTransformStream" nothrow>InitializeTransformStream (
<var>stream</var>, <var ignore>startPromise</var>, <var>writableHighWaterMark</var>, <var>writableSizeAlgorithm</var>,
<var>readableHighWaterMark</var>, <var>readableSizeAlgorithm</var> )</h4>

<emu-alg>
  1. Let _startAlgorithm_ be an algorithm that returns _startPromise_.
  1. Let _writeAlgorithm_ be the following steps, taking a _chunk_ argument:
    1. Return ! TransformStreamDefaultSinkWriteAlgorithm(_stream_, _chunk_).
  1. Let _abortAlgorithm_ be the following steps, taking a _reason_ argument:
    1. Return ! TransformStreamDefaultSinkAbortAlgorithm(_stream_, _reason_).
  1. Let _closeAlgorithm_ be the following steps:
    1. Return ! TransformStreamDefaultSinkCloseAlgorithm(_stream_).
  1. Set _stream_.[[writable]] to ! CreateWritableStream(_startAlgorithm_, _writeAlgorithm_, _closeAlgorithm_,
     _abortAlgorithm_, _writableHighWaterMark_, _writableSizeAlgorithm_).
  1. Let _pullAlgorithm_ be the following steps:
    1. Return ! TransformStreamDefaultSourcePullAlgorithm(_stream_).
  1. Let _cancelAlgorithm_ be the following steps, taking a _reason_ argument:
    1. Perform ! TransformStreamErrorWritableAndUnblockWrite(_stream_, _reason_).
    1. Return <a>a promise resolved with</a> *undefined*.
  1. Set _stream_.[[readable]] to ! CreateReadableStream(_startAlgorithm_, _pullAlgorithm_, _cancelAlgorithm_,
     _readableHighWaterMark_, _readableSizeAlgorithm_).
  1. Set _stream_.[[backpressure]] and _stream_.[[backpressureChangePromise]] to *undefined*.
     <p class="note">The [[backpressure]] slot is set to *undefined* so that it can be initialized by
     TransformStreamSetBackpressure. Alternatively, implementations can use a strictly boolean value for
     [[backpressure]] and change the way it is initialized. This will not be visible to user code so long as the
     initialization is correctly completed before _transformer_'s <l>{{transformer/start()}}</l> method is called.</p>
  1. Perform ! TransformStreamSetBackpressure(_stream_, *true*).
  1. Set _stream_.[[transformStreamController]] to *undefined*.
</emu-alg>

<h4 id="is-transform-stream" aoid="IsTransformStream" nothrow>IsTransformStream ( <var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have a [[transformStreamController]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="transform-stream-error" aoid="TransformStreamError" nothrow>TransformStreamError ( <var>stream</var>,
<var>e</var> )</h4>

<emu-alg>
  1. Perform ! ReadableStreamDefaultControllerError(_stream_.[[readable]].[[readableStreamController]], _e_).
  1. Perform ! TransformStreamErrorWritableAndUnblockWrite(_stream_, _e_).
</emu-alg>

<p class="note">This operation works correctly when one or both sides are already errored. As a result, calling
algorithms do not need to check stream states when responding to an error condition.</p>

<h4 id="transform-stream-error-writable-and-unblock-write" aoid="TransformStreamErrorWritableAndUnblockWrite"
nothrow>TransformStreamErrorWritableAndUnblockWrite ( <var>stream</var>, <var>e</var> )</h4>

<emu-alg>
  1. Perform ! TransformStreamDefaultControllerClearAlgorithms(_stream_.[[transformStreamController]]).
  1. Perform ! WritableStreamDefaultControllerErrorIfNeeded(_stream_.[[writable]].[[writableStreamController]], _e_).
  1. If _stream_.[[backpressure]] is *true*, perform ! TransformStreamSetBackpressure(_stream_, *false*).
</emu-alg>

<p class="note">The TransformStreamDefaultSinkWriteAlgorithm abstract operation could be waiting for the promise
stored in the \[[backpressureChangePromise]] slot to resolve. This call to TransformStreamSetBackpressure ensures that
the promise always resolves.</p>

<h4 id="transform-stream-set-backpressure" aoid="TransformStreamSetBackpressure" nothrow>TransformStreamSetBackpressure
( <var>stream</var>, <var>backpressure</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[backpressure]] is not _backpressure_.
  1. If _stream_.[[backpressureChangePromise]] is not *undefined*, <a>resolve</a>
     stream.[[backpressureChangePromise]] with *undefined*.
  1. Set _stream_.[[backpressureChangePromise]] to <a>a new promise</a>.
  1. Set _stream_.[[backpressure]] to _backpressure_.
</emu-alg>

<h3 id="ts-default-controller-class" interface lt="TransformStreamDefaultController">Class
<code>TransformStreamDefaultController</code></h3>

The {{TransformStreamDefaultController}} class has methods that allow manipulation of the associated {{ReadableStream}}
and {{WritableStream}}. When constructing a {{TransformStream}}, the <a>transformer</a> object is given a corresponding
{{TransformStreamDefaultController}} instance to manipulate.

<h4 id="ts-default-controller-class-definition">Class definition</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{TransformStreamDefaultController}} class in something close to the syntax of [[!ECMASCRIPT]],
it would look like

<pre><code class="lang-javascript">
  class TransformStreamDefaultController {
    <a href="#ts-default-controller-constructor">constructor</a>() // always throws

    get <a href="#ts-default-controller-desired-size">desiredSize</a>()

    <a href="#ts-default-controller-enqueue">enqueue</a>(chunk)
    <a href="#ts-default-controller-error">error</a>(reason)
    <a href="#ts-default-controller-terminate">terminate</a>()
  }
</code></pre>

</div>

<h4 id="ts-default-controller-internal-slots">Internal slots</h4>

Instances of {{TransformStreamDefaultController}} are created with the internal slots described in the following table:

<table>
  <thead>
    <tr>
      <th>Internal Slot</th>
      <th>Description (<em>non-normative</em>)</th>
    </tr>
  </thead>
  <tr>
    <td>\[[controlledTransformStream]]
    <td class="non-normative">The {{TransformStream}} instance controlled; also used for the
      IsTransformStreamDefaultController brand check
  </tr>
  <tr>
    <td>\[[flushAlgorithm]]
    <td class="non-normative">A promise-returning algorithm which communicates a requested close to the
      <a>transformer</a>
  </tr>
  <tr>
    <td>\[[transformAlgorithm]]
    <td class="non-normative">A promise-returning algorithm, taking one argument (the <a>chunk</a> to transform), which
      requests the <a>transformer</a> perform its transformation
</table>

<h4 id="ts-default-controller-constructor" constructor for="TransformStreamDefaultController"
lt="TransformStreamDefaultController()">new TransformStreamDefaultController()</h4>

<div class="note">
  The <code>TransformStreamDefaultController</code> constructor cannot be used directly;
  {{TransformStreamDefaultController}} instances are created automatically during {{TransformStream}} construction.
</div>

<emu-alg>
  1. Throw a *TypeError* exception.
</emu-alg>

<h4 id="ts-default-controller-prototype">Properties of the {{TransformStreamDefaultController}} prototype</h4>

<h5 id="ts-default-controller-desired-size" attribute for="TransformStreamDefaultController" lt="desiredSize">get
desiredSize</h5>

<div class="note">
  The <code>desiredSize</code> getter returns the <a lt="desired size to fill a stream's internal queue">desired size
  to fill the readable side's internal queue</a>. It can be negative, if the queue is over-full.
</div>

<emu-alg>
  1. If ! IsTransformStreamDefaultController(*this*) is *false*, throw a *TypeError* exception.
  1. Let _readableController_ be *this*.[[controlledTransformStream]].[[readable]].[[readableStreamController]].
  1. Return ! ReadableStreamDefaultControllerGetDesiredSize(_readableController_).
</emu-alg>

<h5 id="ts-default-controller-enqueue" method for="TransformStreamDefaultController">enqueue(<var>chunk</var>)</h5>

<div class="note">
  The <code>enqueue</code> method will enqueue a given <a>chunk</a> in the <a>readable side</a>.
</div>

<emu-alg>
  1. If ! IsTransformStreamDefaultController(*this*) is *false*, throw a *TypeError* exception.
  1. Perform ? TransformStreamDefaultControllerEnqueue(*this*, _chunk_).
</emu-alg>

<h5 id="ts-default-controller-error" method for="TransformStreamDefaultController">error(<var>reason</var>)</h5>

<div class="note">
  The <code>error</code> method will error both the <a>readable side</a> and the <a>writable side</a> of the controlled
  <a>transform stream</a>, making all future interactions fail with the given <code>reason</code>. Any <a>chunks</a>
  queued for transformation will be discarded.
</div>

<emu-alg>
  1. If ! IsTransformStreamDefaultController(*this*) is *false*, throw a *TypeError* exception.
  1. Perform ! TransformStreamDefaultControllerError(*this*, _reason_).
</emu-alg>

<h5 id="ts-default-controller-terminate" method for="TransformStreamDefaultController">terminate()</h5>

<div class="note">
  The <code>terminate</code> method will close the <a>readable side</a> and error the <a>writable side</a> of the
  controlled <a>transform stream</a>. This is useful when the <a>transformer</a> only needs to consume a portion of the
  <a>chunks</a> written to the <a>writable side</a>.
</div>

<emu-alg>
  1. If ! IsTransformStreamDefaultController(*this*) is *false*, throw a *TypeError* exception.
  1. Perform ! TransformStreamDefaultControllerTerminate(*this*).
</emu-alg>

<h3 id="ts-default-controller-abstract-ops">Transform stream default controller abstract operations</h3>

<h4 id="is-transform-stream-default-controller" aoid="IsTransformStreamDefaultController"
nothrow>IsTransformStreamDefaultController ( <var>x</var> )</h4>

<emu-alg>
  1. If Type(_x_) is not Object, return *false*.
  1. If _x_ does not have an [[controlledTransformStream]] internal slot, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="set-up-transform-stream-default-controller" aoid="SetUpTransformStreamDefaultController"
nothrow>SetUpTransformStreamDefaultController ( <var>stream</var>, <var>controller</var>, <var>transformAlgorithm</var>,
<var>flushAlgorithm</var> )</h4>

<emu-alg>
  1. Assert: ! IsTransformStream(_stream_) is *true*.
  1. Assert: _stream_.[[transformStreamController]] is *undefined*.
  1. Set _controller_.[[controlledTransformStream]] to _stream_.
  1. Set _stream_.[[transformStreamController]] to _controller_.
  1. Set _controller_.[[transformAlgorithm]] to _transformAlgorithm_.
  1. Set _controller_.[[flushAlgorithm]] to _flushAlgorithm_.
</emu-alg>

<h4 id="set-up-transform-stream-default-controller-from-transformer"
aoid="SetUpTransformStreamDefaultControllerFromTransformer"
throws>SetUpTransformStreamDefaultControllerFromTransformer ( <var>stream</var>, <var>transformer</var> )</h4>

<emu-alg>
  1. Assert: _transformer_ is not *undefined*.
  1. Let _controller_ be ObjectCreate(the original value of `<a idl>TransformStreamDefaultController</a>`'s `prototype`
     property).
  1. Let _transformAlgorithm_ be the following steps, taking a _chunk_ argument:
    1. Let _result_ be TransformStreamDefaultControllerEnqueue(_controller_, _chunk_).
    1. If _result_ is an abrupt completion, return <a>a promise rejected with</a> _result_.[[Value]].
    1. Otherwise, return <a>a promise resolved with</a> *undefined*.
  1. Let _transformMethod_ be ? GetV(_transformer_, `"transform"`).
  1. If _transformMethod_ is not *undefined*,
    1. If ! IsCallable(_transformMethod_) is *false*, throw a *TypeError* exception.
    1. Set _transformAlgorithm_ to the following steps, taking a _chunk_ argument:
      1. Return ! PromiseCall(_transformMethod_, _transformer_, « _chunk_, _controller_ »).
  1. Let _flushAlgorithm_ be ? CreateAlgorithmFromUnderlyingMethod(_transformer_, `"flush"`, *0*, « controller »).
  1. Perform ! SetUpTransformStreamDefaultController(_stream_, _controller_, _transformAlgorithm_, _flushAlgorithm_).
</emu-alg>

<h4 id="transform-stream-default-controller-clear-algorithms" aoid="TransformStreamDefaultControllerClearAlgorithms"
nothrow>TransformStreamDefaultControllerClearAlgorithms ( <var>controller</var> )</h4>

This abstract operation is called once the stream is closed or errored and the algorithms will not be executed any more.
By removing the algorithm references it permits the <a>transformer</a> object to be garbage collected even if the
{{TransformStream}} itself is still referenced.

<p class="note">The results of this algorithm are not currently observable, but could become so if JavaScript eventually
adds <a href="https://github.com/tc39/proposal-weakrefs/">weak references</a>. But even without that factor,
implementations will likely want to include similar steps.</p>

<emu-alg>
  1. Set _controller_.[[transformAlgorithm]] to *undefined*.
  1. Set _controller_.[[flushAlgorithm]] to *undefined*.
</emu-alg>

<h4 id="transform-stream-default-controller-enqueue" aoid="TransformStreamDefaultControllerEnqueue"
throws export>TransformStreamDefaultControllerEnqueue ( <var>controller</var>, <var>chunk</var> )</h4>

This abstract operation can be called by other specifications that wish to enqueue <a>chunks</a> in the <a>readable
side</a>, in the same way a developer would enqueue chunks using the stream's associated controller object.
Specifications should <em>not</em> do this to streams they did not create.

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledTransformStream]].
  1. Let _readableController_ be _stream_.[[readable]].[[readableStreamController]].
  1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(_readableController_) is *false*, throw a *TypeError*
     exception.
  1. Let _enqueueResult_ be ReadableStreamDefaultControllerEnqueue(_readableController_, _chunk_).
  1. If _enqueueResult_ is an abrupt completion,
    1. Perform ! TransformStreamErrorWritableAndUnblockWrite(_stream_, _enqueueResult_.[[Value]]).
    1. Throw _stream_.[[readable]].[[storedError]].
  1. Let _backpressure_ be ! ReadableStreamDefaultControllerHasBackpressure(_readableController_).
  1. If _backpressure_ is not _stream_.[[backpressure]],
    1. Assert: _backpressure_ is *true*.
    1. Perform ! TransformStreamSetBackpressure(_stream_, *true*).
</emu-alg>

<h4 id="transform-stream-default-controller-error" aoid="TransformStreamDefaultControllerError"
nothrow export>TransformStreamDefaultControllerError ( <var>controller</var>, <var>e</var> )</h4>

This abstract operation can be called by other specifications that wish to move a transform stream to an errored state,
in the same way a developer would error a stream using its associated controller object. Specifications should
<em>not</em> do this to streams they did not create.

<emu-alg>
  1. Perform ! TransformStreamError(_controller_.[[controlledTransformStream]], _e_).
</emu-alg>

<h4 id="transform-stream-default-controller-perform-transform" aoid="TransformStreamDefaultControllerPerformTransform"
nothrow>TransformStreamDefaultControllerPerformTransform ( <var>controller</var>, <var>chunk</var> )</h4>

<emu-alg>
  1. Let _transformPromise_ be the result of performing _controller_.[[transformAlgorithm]], passing _chunk_.
  1. Return the result of <a>reacting</a> to _transformPromise_ with the following rejection steps given the
     argument _r_:
    1. Perform ! TransformStreamError(_controller_.[[controlledTransformStream]], _r_).
    1. Throw _r_.
</emu-alg>

<h4 id="transform-stream-default-controller-terminate" aoid="TransformStreamDefaultControllerTerminate"
nothrow export>TransformStreamDefaultControllerTerminate ( <var>controller</var> )</h4>

This abstract operation can be called by other specifications that wish to terminate a transform stream, in the same way
a developer-created stream would be closed by its associated controller object. Specifications should <em>not</em> do
this to streams they did not create.

<emu-alg>
  1. Let _stream_ be _controller_.[[controlledTransformStream]].
  1. Let _readableController_ be _stream_.[[readable]].[[readableStreamController]].
  1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(_readableController_) is *true*, perform !
     ReadableStreamDefaultControllerClose(_readableController_).
  1. Let _error_ be a *TypeError* exception indicating that the stream has been terminated.
  1. Perform ! TransformStreamErrorWritableAndUnblockWrite(_stream_, _error_).
</emu-alg>

<h3 id="ts-default-sink-abstract-ops">Transform stream default sink abstract operations</h3>

<h4 id="transform-stream-default-sink-write-algorithm" aoid="TransformStreamDefaultSinkWriteAlgorithm"
nothrow>TransformStreamDefaultSinkWriteAlgorithm ( <var>stream</var>, <var>chunk</var> )</h4>

<emu-alg>
  1. Assert: _stream_.[[writable]].[[state]] is `"writable"`.
  1. Let _controller_ be _stream_.[[transformStreamController]].
  1. If _stream_.[[backpressure]] is *true*,
    1. Let _backpressureChangePromise_ be _stream_.[[backpressureChangePromise]].
    1. Assert: _backpressureChangePromise_ is not *undefined*.
    1. Return the result of <a>reacting</a> to _backpressureChangePromise_ with the following fulfillment steps:
      1. Let _writable_ be _stream_.[[writable]].
      1. Let _state_ be _writable_.[[state]].
      1. If _state_ is `"erroring"`, throw _writable_.[[storedError]].
      1. Assert: _state_ is `"writable"`.
      1. Return ! TransformStreamDefaultControllerPerformTransform(_controller_, _chunk_).
  1. Return ! TransformStreamDefaultControllerPerformTransform(_controller_, _chunk_).
</emu-alg>

<h4 id="transform-stream-default-sink-abort-algorithm" aoid="TransformStreamDefaultSinkAbortAlgorithm"
nothrow>TransformStreamDefaultSinkAbortAlgorithm ( <var>stream</var>, <var>reason</var> )</h4>

<emu-alg>
  1. Perform ! TransformStreamError(_stream_, _reason_).
  1. Return <a>a promise resolved with</a> *undefined*.
</emu-alg>

<h4 id="transform-stream-default-sink-close-algorithm" aoid="TransformStreamDefaultSinkCloseAlgorithm"
nothrow>TransformStreamDefaultSinkCloseAlgorithm( <var>stream</var> )</h4>

<emu-alg>
  1. Let _readable_ be _stream_.[[readable]].
  1. Let _controller_ be _stream_.[[transformStreamController]].
  1. Let _flushPromise_ be the result of performing _controller_.[[flushAlgorithm]].
  1. Perform ! TransformStreamDefaultControllerClearAlgorithms(_controller_).
  1. Return the result of <a>reacting</a> to _flushPromise_:
    1. If _flushPromise_ was fulfilled, then:
      1. If _readable_.[[state]] is `"errored"`, throw _readable_.[[storedError]].
      1. Let _readableController_ be _readable_.[[readableStreamController]].
      1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(_readableController_) is *true*, perform !
         ReadableStreamDefaultControllerClose(_readableController_).
    1. If _flushPromise_ was rejected with reason _r_, then:
      1. Perform ! TransformStreamError(_stream_, _r_).
      1. Throw _readable_.[[storedError]].
</emu-alg>

<h3 id="ts-default-source-abstract-ops">Transform stream default source abstract operations</h3>

<h4 id="transform-stream-default-source-pull"
aoid="TransformStreamDefaultSourcePullAlgorithm" nothrow>TransformStreamDefaultSourcePullAlgorithm( <var>stream</var>
)</h4>

<emu-alg>
  1. Assert: _stream_.[[backpressure]] is *true*.
  1. Assert: _stream_.[[backpressureChangePromise]] is not *undefined*.
  1. Perform ! TransformStreamSetBackpressure(_stream_, *false*).
  1. Return _stream_.[[backpressureChangePromise]].
</emu-alg>

<h2 id="other-stuff">Other stream APIs and operations</h2>

<h3 id="qs">Queuing strategies</h3>

<h4 id="qs-api">The queuing strategy API</h4>

<div class="non-normative">

<em>This section is non-normative.</em>

The {{ReadableStream()}}, {{WritableStream()}}, and {{TransformStream()}} constructors all accept at least one argument
representing an appropriate <a>queuing strategy</a> for the stream being created. Such objects contain the following
properties:

<dl>
  <dt><dfn method for="queuing strategy">size(<var>chunk</var>)</dfn> (non-byte streams only)</dt>
  <dd>
    <p>A function that computes and returns the finite non-negative size of the given <a>chunk</a> value.</p>

    <p>The result is used to determine <a>backpressure</a>, manifesting via the appropriate <code>desiredSize</code>
    property: either
    {{ReadableStreamDefaultController/desiredSize|defaultController.desiredSize}},
    {{ReadableByteStreamController/desiredSize|byteController.desiredSize}}, or
    {{WritableStreamDefaultWriter/desiredSize|writer.desiredSize}}, depending on where the queuing strategy is being
    used. For readable streams, it also governs when the <a>underlying source</a>'s {{underlying source/pull()}} method
    is called.</p>

    <p>This function has to be idempotent and not cause side effects; very strange results can occur otherwise.</p>

    <p>For <a>readable byte streams</a>, this function is not used, as chunks are always measured in bytes.</p>
  </dd>

  <dt><dfn for="queuing strategy"><code>highWaterMark</code></dfn></dt>
  <dd>
    <p>A non-negative number indicating the <a>high water mark</a> of the stream using this queuing strategy.</p>
  </dd>
</dl>

Any object with these properties can be used when a queuing strategy object is expected. However, we provide two
built-in queuing strategy classes that provide a common vocabulary for certain cases: {{ByteLengthQueuingStrategy}} and
{{CountQueuingStrategy}}.

</div>

<h4 id="blqs-class" interface lt="ByteLengthQueuingStrategy">Class <code>ByteLengthQueuingStrategy</code></h4>

A common <a>queuing strategy</a> when dealing with bytes is to wait until the accumulated <code>byteLength</code>
properties of the incoming <a>chunks</a> reaches a specified high-water mark. As such, this is provided as a built-in
<a>queuing strategy</a> that can be used when constructing streams.

<div class="example" id="example-blqs">
  When creating a <a>readable stream</a> or <a>writable stream</a>, you can supply a byte-length queuing strategy
  directly:

  <pre><code class="lang-javascript">
    const stream = new ReadableStream(
      { ... },
      new ByteLengthQueuingStrategy({ highWaterMark: 16 * 1024 })
    );
  </code></pre>

  In this case, 16 KiB worth of <a>chunks</a> can be enqueued by the readable stream's <a>underlying source</a> before
  the readable stream implementation starts sending <a>backpressure</a> signals to the underlying source.

  <pre><code class="lang-javascript">
    const stream = new WritableStream(
      { ... },
      new ByteLengthQueuingStrategy({ highWaterMark: 32 * 1024 })
    );
  </code></pre>

  In this case, 32 KiB worth of <a>chunks</a> can be accumulated in the writable stream's internal queue, waiting for
  previous writes to the <a>underlying sink</a> to finish, before the writable stream starts sending
  <a>backpressure</a> signals to any <a>producers</a>.
</div>

<p class="note">
  It is not necessary to use {{ByteLengthQueuingStrategy}} with <a>readable byte streams</a>, as they always measure
  chunks in bytes. Attempting to construct a byte stream with a {{ByteLengthQueuingStrategy}} will fail.
</p>

<h5 id="blqs-class-definition">Class definition</h5>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{ByteLengthQueuingStrategy}} class in something close to the syntax of [[!ECMASCRIPT]], it
would look like

<pre><code class="lang-javascript">
  class ByteLengthQueuingStrategy {
    <a href="#blqs-constructor">constructor</a>({ highWaterMark })
    <a href="#blqs-size">size</a>(chunk)
  }
</code></pre>

Each {{ByteLengthQueuingStrategy}} instance will additionally have an own data property
<code>highWaterMark</code> set by its constructor.

</div>

<h5 id="blqs-constructor" constructor for="ByteLengthQueuingStrategy" lt="ByteLengthQueuingStrategy(options)">new
ByteLengthQueuingStrategy({ <var>highWaterMark</var> })</h5>

<div class="note">
  The constructor takes a non-negative number for the high-water mark, and stores it on the object as a property.
</div>

<emu-alg>
  1. Perform ! CreateDataProperty(*this*, `"highWaterMark"`, _highWaterMark_).
</emu-alg>

<h5 id="blqs-prototype">Properties of the {{ByteLengthQueuingStrategy}} prototype</h5>

<h6 id="blqs-size" method for="ByteLengthQueuingStrategy">size(<var>chunk</var>)</h6>

<div class="note">
  The <code>size</code> method returns the given chunk's <code>byteLength</code> property. (If the chunk doesn't have
  one, it will return <emu-val>undefined</emu-val>, causing the stream using this strategy to error.)

  This method is intentionally generic; it does not require that its <emu-val>this</emu-val> value be a
  <code>ByteLengthQueuingStrategy</code> object.
</div>

<emu-alg>
  1. Return ? GetV(_chunk_, `"byteLength"`).
</emu-alg>

<h4 id="cqs-class" interface lt="CountQueuingStrategy">Class <code>CountQueuingStrategy</code></h4>

A common <a>queuing strategy</a> when dealing with streams of generic objects is to simply count the number of chunks
that have been accumulated so far, waiting until this number reaches a specified high-water mark. As such, this
strategy is also provided out of the box.

<div class="example" id="example-cqs">
  When creating a <a>readable stream</a> or <a>writable stream</a>, you can supply a count queuing strategy directly:

  <pre><code class="lang-javascript">
    const stream = new ReadableStream(
      { ... },
      new CountQueuingStrategy({ highWaterMark: 10 })
    );
  </code></pre>

  In this case, 10 <a>chunks</a> (of any kind) can be enqueued by the readable stream's <a>underlying source</a> before
  the readable stream implementation starts sending <a>backpressure</a> signals to the underlying source.

  <pre><code class="lang-javascript">
    const stream = new WritableStream(
      { ... },
      new CountQueuingStrategy({ highWaterMark: 5 })
    );
  </code></pre>

  In this case, five <a>chunks</a> (of any kind) can be accumulated in the writable stream's internal queue, waiting
  for previous writes to the <a>underlying sink</a> to finish, before the writable stream starts sending
  <a>backpressure</a> signals to any <a>producers</a>.
</div>

<h5 id="cqs-class-definition">Class definition</h5>

<div class="non-normative">

<em>This section is non-normative.</em>

If one were to write the {{CountQueuingStrategy}} class in something close to the syntax of [[!ECMASCRIPT]], it would
look like

<pre><code class="lang-javascript">
  class CountQueuingStrategy {
    <a href="#cqs-constructor">constructor</a>({ highWaterMark })
    <a href="#cqs-size">size</a>(chunk)
  }
</code></pre>

Each {{CountQueuingStrategy}} instance will additionally have an own data property <code>highWaterMark</code>
set by its constructor.

</div>

<h5 id="cqs-constructor" constructor for="CountQueuingStrategy" lt="CountQueuingStrategy(options)">new
CountQueuingStrategy({ <var>highWaterMark</var> })</h5>

<div class="note">
  The constructor takes a non-negative number for the high-water mark, and stores it on the object as a property.
</div>

<emu-alg>
  1. Perform ! CreateDataProperty(*this*, `"highWaterMark"`, _highWaterMark_).
</emu-alg>

<h5 id="cqs-prototype">Properties of the {{CountQueuingStrategy}} prototype</h5>

<h6 id="cqs-size" method for="CountQueuingStrategy">size()</h6>

<div class="note">
  The <code>size</code> method returns one always, so that the total queue size is a count of the number of chunks in
  the queue.

  This method is intentionally generic; it does not require that its <emu-val>this</emu-val> value be a
  <code>CountQueuingStrategy</code> object.
</div>

<emu-alg>
  1. Return *1*.
</emu-alg>

<h3 id="queue-with-sizes">Queue-with-sizes operations</h3>

The streams in this specification use a "queue-with-sizes" data structure to store queued up values, along with their
determined sizes. Various specification objects contain a queue-with-sizes, represented by the object having two paired
internal slots, always named \[[queue]] and \[[queueTotalSize]]. \[[queue]] is a List of Records with \[[value]] and
\[[size]] fields, and \[[queueTotalSize]] is a JavaScript {{Number}}, i.e. a double-precision floating point number.

The following abstract operations are used when operating on objects that contain queues-with-sizes, in order to ensure
that the two internal slots stay synchronized.

<p class="warning">Due to the limited precision of floating-point arithmetic, the framework specified here, of keeping a
running total in the \[[queueTotalSize]] slot, is <em>not</em> equivalent to adding up the size of all <a>chunks</a> in
\[[queue]]. (However, this only makes a difference when there is a huge (~10<sup>15</sup>) variance in size between
chunks, or when trillions of chunks are enqueued.)</p>

<h4 id="dequeue-value" aoid="DequeueValue" nothrow>DequeueValue ( <var>container</var> )</h4>

<emu-alg>
  1. Assert: _container_ has [[queue]] and [[queueTotalSize]] internal slots.
  1. Assert: _container_.[[queue]] is not empty.
  1. Let _pair_ be the first element of _container_.[[queue]].
  1. Remove _pair_ from _container_.[[queue]], shifting all other elements downward (so that the second becomes the
     first, and so on).
  1. Set _container_.[[queueTotalSize]] to _container_.[[queueTotalSize]] − _pair_.[[size]].
  1. If _container_.[[queueTotalSize]] < *0*, set _container_.[[queueTotalSize]] to *0*. (This can occur due to
     rounding errors.)
  1. Return _pair_.[[value]].
</emu-alg>

<h4 id="enqueue-value-with-size" aoid="EnqueueValueWithSize" throws>EnqueueValueWithSize ( <var>container</var>,
<var ignore>value</var>, <var>size</var> )</h4>

<emu-alg>
  1. Assert: _container_ has [[queue]] and [[queueTotalSize]] internal slots.
  1. Let _size_ be ? ToNumber(_size_).
  1. If ! IsFiniteNonNegativeNumber(_size_) is *false*, throw a *RangeError* exception.
  1. Append Record {[[value]]: _value_, [[size]]: _size_} as the last element of _container_.[[queue]].
  1. Set _container_.[[queueTotalSize]] to _container_.[[queueTotalSize]] + _size_.
</emu-alg>

<h4 id="peek-queue-value" aoid="PeekQueueValue" nothrow>PeekQueueValue ( <var>container</var> )</h4>

<emu-alg>
  1. Assert: _container_ has [[queue]] and [[queueTotalSize]] internal slots.
  1. Assert: _container_.[[queue]] is not empty.
  1. Let _pair_ be the first element of _container_.[[queue]].
  1. Return _pair_.[[value]].
</emu-alg>

<h4 id="reset-queue" aoid="ResetQueue" nothrow>ResetQueue ( <var>container</var> )</h4>

<emu-alg>
  1. Assert: _container_ has [[queue]] and [[queueTotalSize]] internal slots.
  1. Set _container_.[[queue]] to a new empty List.
  1. Set _container_.[[queueTotalSize]] to *0*.
</emu-alg>

<h3 id="misc-abstract-ops">Miscellaneous operations</h3>

A few abstract operations are used in this specification for utility purposes. We define them here.

<h4 id="create-algorithm-from-underlying-method" aoid="CreateAlgorithmFromUnderlyingMethod"
throws>CreateAlgorithmFromUnderlyingMethod ( <var ignore>underlyingObject</var>, <var ignore>methodName</var>,
<var ignore>algoArgCount</var>, <var ignore>extraArgs</var> )</h4>

<emu-alg>
  1. Assert: _underlyingObject_ is not *undefined*.
  1. Assert: ! IsPropertyKey(_methodName_) is *true*.
  1. Assert: _algoArgCount_ is *0* or *1*.
  1. Assert: _extraArgs_ is a List.
  1. Let _method_ be ? GetV(_underlyingObject_, _methodName_).
  1. If _method_ is not *undefined*,
    1. If ! IsCallable(_method_) is *false*, throw a *TypeError* exception.
    1. If _algoArgCount_ is *0*, return an algorithm that performs the following steps:
      1. Return ! PromiseCall(_method_, _underlyingObject_, _extraArgs_).
    1. Otherwise, return an algorithm that performs the following steps, taking an _arg_ argument:
      1. Let _fullArgs_ be a List consisting of _arg_ followed by the elements of _extraArgs_ in order.
      1. Return ! PromiseCall(_method_, _underlyingObject_, _fullArgs_).
  1. Return an algorithm which returns <a>a promise resolved with</a> *undefined*.
</emu-alg>

<h4 id="invoke-or-noop" aoid="InvokeOrNoop" throws>InvokeOrNoop ( <var>O</var>, <var ignore>P</var>, <var>args</var>
)</h4>

<div class="note">
  InvokeOrNoop is a slight modification of the [[!ECMASCRIPT]] <a abstract-op>Invoke</a> abstract operation to return
  <emu-val>undefined</emu-val> when the method is not present.
</div>

<emu-alg>
  1. Assert: _O_ is not *undefined*.
  1. Assert: ! IsPropertyKey(_P_) is *true*.
  1. Assert: _args_ is a List.
  1. Let _method_ be ? GetV(_O_, _P_).
  1. If _method_ is *undefined*, return *undefined*.
  1. Return ? Call(_method_, _O_, _args_).
</emu-alg>

<h4 id="is-finite-non-negative-number" aoid="IsFiniteNonNegativeNumber" nothrow>IsFiniteNonNegativeNumber ( <var>v</var>
)</h4>

<emu-alg>
  1. If ! IsNonNegativeNumber(_v_) is *false*, return *false*.
  1. If _v_ is *+∞*, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="is-non-negative-number" aoid="IsNonNegativeNumber" nothrow>IsNonNegativeNumber ( <var>v</var> )</h4>

<emu-alg>
  1. If Type(_v_) is not Number, return *false*.
  1. If _v_ is *NaN*, return *false*.
  1. If _v_ < *0*, return *false*.
  1. Return *true*.
</emu-alg>

<h4 id="promise-call" aoid="PromiseCall" nothrow>PromiseCall ( <var ignore>F</var>, <var ignore>V</var>,
<var>args</var> )</h4>

<div class="note">
  This encapsulates the relevant promise-related parts of the Web IDL <a>call a user object's operation</a> algorithm
  for use while we work on <a href="https://github.com/whatwg/streams/issues/963">moving to Web IDL</a>.
</div>

<emu-alg>
  1. Assert: ! IsCallable(_F_) is *true*.
  1. Assert: _V_ is not *undefined*.
  1. Assert: _args_ is a List.
  1. Let _returnValue_ be Call(_F_, _V_, _args_).
  1. If _returnValue_ is an abrupt completion, return <a>a promise rejected with</a> _returnValue_.[[Value]].
  1. Otherwise, return <a>a promise resolved with</a> _returnValue_.[[Value]].
</emu-alg>

<h4 id="transfer-array-buffer" aoid="TransferArrayBuffer" nothrow>TransferArrayBuffer ( <var>O</var> )</h4>

<emu-alg>
  1. Assert: Type(_O_) is Object.
  1. Assert: _O_ has an [[ArrayBufferData]] internal slot.
  1. Assert: ! IsDetachedBuffer(_O_) is *false*.
  1. Let _arrayBufferData_ be _O_.[[ArrayBufferData]].
  1. Let _arrayBufferByteLength_ be _O_.[[ArrayBufferByteLength]].
  1. Perform ! DetachArrayBuffer(_O_).
  1. Return a new <a interface><code>ArrayBuffer</code></a> object (created in the current Realm Record) whose
     [[ArrayBufferData]] internal slot value is _arrayBufferData_ and whose [[ArrayBufferByteLength]] internal slot
     value is _arrayBufferByteLength_.
</emu-alg>

<h4 id="validate-and-normalize-high-water-mark" aoid="ValidateAndNormalizeHighWaterMark"
throws>ValidateAndNormalizeHighWaterMark ( <var>highWaterMark</var> )</h4>

<emu-alg>
  1. Set _highWaterMark_ to ? ToNumber(_highWaterMark_).
  1. If _highWaterMark_ is *NaN* or _highWaterMark_ < *0*, throw a *RangeError* exception.
     <p class="note">*+∞* is explicitly allowed as a valid <a>high water mark</a>. It causes <a>backpressure</a> to never be applied.</p>
  1. Return _highWaterMark_.
</emu-alg>

<h4 id="make-size-algorithm-from-size-function" aoid="MakeSizeAlgorithmFromSizeFunction"
throws>MakeSizeAlgorithmFromSizeFunction ( <var>size</var> )</h4>

<emu-alg>
  1. If _size_ is *undefined*, return an algorithm that returns *1*.
  1. If ! IsCallable(_size_) is *false*, throw a *TypeError* exception.
  1. Return an algorithm that performs the following steps, taking a _chunk_ argument:
    1. Return ? Call(_size_, *undefined*, « _chunk_ »).
</emu-alg>

<h2 id="globals">Global properties</h2>

The following constructors must be exposed on the global object as data properties of the same name:

<ul class="brief">
  <li> {{ReadableStream}}
  <li> {{WritableStream}}
  <li> {{TransformStream}}
  <li> {{ByteLengthQueuingStrategy}}
  <li> {{CountQueuingStrategy}}
</ul>

The attributes of these properties must be { \[[Writable]]: <emu-val>true</emu-val>, \[[Enumerable]]: <emu-val>false</emu-val>,
\[[Configurable]]: <emu-val>true</emu-val> }.

<div class="note">
  The {{ReadableStreamDefaultReader}}, {{ReadableStreamBYOBReader}}, {{ReadableStreamDefaultController}},
  {{ReadableByteStreamController}}, {{WritableStreamDefaultWriter}}, {{WritableStreamDefaultController}}, and
  {{TransformStreamDefaultController}} classes are specifically not exposed, as they are not independently useful.
</div>

<h2 id="creating-examples">Examples of creating streams</h2>

<div class="non-normative">

<em>This section, and all its subsections, are non-normative.</em>

The previous examples throughout the standard have focused on how to use streams. Here we show how to create a stream,
using the {{ReadableStream}} or {{WritableStream}} constructors.

<h3 id="example-rs-push-no-backpressure">A readable stream with an underlying push source (no backpressure support)</h3>

The following function creates <a>readable streams</a> that wrap {{WebSocket}} instances [[HTML]], which are <a>push sources</a>
that do not support backpressure signals. It illustrates how, when adapting a push source, usually most of the work
happens in the {{underlying source/start()}} function.

<pre><code class="lang-javascript">
  function makeReadableWebSocketStream(url, protocols) {
    const ws = new WebSocket(url, protocols);
    ws.binaryType = "arraybuffer";

    return new ReadableStream({
      start(controller) {
        ws.onmessage = event => controller.enqueue(event.data);
        ws.onclose = () => controller.close();
        ws.onerror = () => controller.error(new Error("The WebSocket errored!"));
      },

      cancel() {
        ws.close();
      }
    });
  }
</code></pre>

We can then use this function to create readable streams for a web socket, and pipe that stream to an arbitrary
writable stream:

<pre><code class="lang-javascript">
  const webSocketStream = makeReadableWebSocketStream("wss://example.com:443/", "protocol");

  webSocketStream.pipeTo(writableStream)
    .then(() => console.log("All data successfully written!"))
    .catch(e => console.error("Something went wrong!", e));
</code></pre>

<div class="note" id="note-web-socket-wrapping-examples">
  This specific style of wrapping a web socket interprets web socket messages directly as <a>chunks</a>.
  This can be a convenient abstraction, for example when <a>piping</a> to a <a>writable stream</a> or <a>transform
  stream</a> for which each web socket message makes sense as a chunk to consume or transform.

  However, often when people talk about "adding streams support to web sockets", they are hoping instead for a new
  capability to send an individual web socket message in a streaming fashion, so that e.g. a file could be transferred
  in a single message without holding all of its contents in memory on the client side. To accomplish this goal, we'd
  instead want to allow individual web socket messages to themselves be {{ReadableStream}} instances. That isn't what we
  show in the above example.

  For more background, see <a href="https://github.com/w3c/webrtc-pc/issues/1732#issuecomment-358428651">this
  discussion</a>.
</div>

<h3 id="example-rs-push-backpressure">A readable stream with an underlying push source and backpressure support</h3>

The following function returns <a>readable streams</a> that wrap "backpressure sockets," which are hypothetical objects
that have the same API as web sockets, but also provide the ability to pause and resume the flow of data with their
<code>readStop</code> and <code>readStart</code> methods. In doing so, this example shows how to apply
<a>backpressure</a> to <a>underlying sources</a> that support it.

<pre><code class="lang-javascript">
  function makeReadableBackpressureSocketStream(host, port) {
    const socket = createBackpressureSocket(host, port);

    return new ReadableStream({
      start(controller) {
        socket.ondata = event => {
          controller.enqueue(event.data);

          if (controller.desiredSize <= 0) {
            // The internal queue is full, so propagate
            // the backpressure signal to the underlying source.
            socket.readStop();
          }
        };

        socket.onend = () => controller.close();
        socket.onerror = () => controller.error(new Error("The socket errored!"));
      },

      pull() {
        // This is called if the internal queue has been emptied, but the
        // stream's consumer still wants more data. In that case, restart
        // the flow of data if we have previously paused it.
        socket.readStart();
      },

      cancel() {
        socket.close();
      }
    });
  }
</code></pre>

We can then use this function to create readable streams for such "backpressure sockets" in the same way we do for web
sockets. This time, however, when we pipe to a destination that cannot accept data as fast as the socket is producing
it, or if we leave the stream alone without reading from it for some time, a backpressure signal will be sent to the
socket.

<h3 id="example-rbs-push">A readable byte stream with an underlying push source (no backpressure support)</h3>

The following function returns <a>readable byte streams</a> that wraps a hypothetical UDP socket API, including a
promise-returning <code>select2()</code> method that is meant to be evocative of the POSIX select(2) system call.

Since the UDP protocol does not have any built-in backpressure support, the backpressure signal given by
{{ReadableByteStreamController/desiredSize}} is ignored, and the stream ensures that when data is available from the
socket but not yet requested by the developer, it is enqueued in the stream's <a>internal queue</a>, to avoid overflow
of the kernel-space queue and a consequent loss of data.

This has some interesting consequences for how <a>consumers</a> interact with the stream. If the consumer does not read
data as fast as the socket produces it, the <a>chunks</a> will remain in the stream's <a>internal queue</a>
indefinitely. In this case, using a <a>BYOB reader</a> will cause an extra copy, to move the data from the stream's
internal queue to the developer-supplied buffer. However, if the consumer consumes the data quickly enough, a <a>BYOB
reader</a> will allow zero-copy reading directly into developer-supplied buffers.

(You can imagine a more complex version of this example which uses {{ReadableByteStreamController/desiredSize}} to
inform an out-of-band backpressure signaling mechanism, for example by sending a message down the socket to adjust the
rate of data being sent. That is left as an exercise for the reader.)

<pre><code class="lang-javascript">
  const DEFAULT_CHUNK_SIZE = 65536;

  function makeUDPSocketStream(host, port) {
    const socket = createUDPSocket(host, port);

    return new ReadableStream({
      type: "bytes",

      start(controller) {
        readRepeatedly().catch(e => controller.error(e));

        function readRepeatedly() {
          return socket.select2().then(() => {
            // Since the socket can become readable even when there’s
            // no pending BYOB requests, we need to handle both cases.
            let bytesRead;
            if (controller.byobRequest) {
              const v = controller.byobRequest.view;
              bytesRead = socket.readInto(v.buffer, v.byteOffset, v.byteLength);
              controller.byobRequest.respond(bytesRead);
            } else {
              const buffer = new ArrayBuffer(DEFAULT_CHUNK_SIZE);
              bytesRead = socket.readInto(buffer, 0, DEFAULT_CHUNK_SIZE);
              controller.enqueue(new Uint8Array(buffer, 0, bytesRead));
            }

            if (bytesRead === 0) {
              controller.close();
              return;
            }

            return readRepeatedly();
          });
        }
      },

      cancel() {
        socket.close();
      }
    });
  }
</code></pre>

{{ReadableStream}} instances returned from this function can now vend <a>BYOB readers</a>, with all of the
aforementioned benefits and caveats.

<h3 id="example-rs-pull">A readable stream with an underlying pull source</h3>

The following function returns <a>readable streams</a> that wrap portions of the
<a href="https://nodejs.org/api/fs.html">Node.js file system API</a> (which themselves map fairly directly to C's
<code>fopen</code>, <code>fread</code>, and <code>fclose</code> trio). Files are a typical example of <a>pull
sources</a>. Note how in contrast to the examples with push sources, most of the work here happens on-demand in the
{{underlying source/pull()}} function, and not at startup time in the {{underlying source/start()}} function.

<pre><code class="lang-javascript">
  const fs = require("pr/fs"); // https://github.com/jden/pr
  const CHUNK_SIZE = 1024;

  function makeReadableFileStream(filename) {
    let fd;
    let position = 0;

    return new ReadableStream({
      start() {
        return fs.open(filename, "r").then(result => {
          fd = result;
        });
      },

      pull(controller) {
        const buffer = new ArrayBuffer(CHUNK_SIZE);

        return fs.read(fd, buffer, 0, CHUNK_SIZE, position).then(bytesRead => {
          if (bytesRead === 0) {
            return fs.close(fd).then(() => controller.close());
          } else {
            position += bytesRead;
            controller.enqueue(new Uint8Array(buffer, 0, bytesRead));
          }
        });
      },

      cancel() {
        return fs.close(fd);
      }
    });
  }
</code></pre>

We can then create and use readable streams for files just as we could before for sockets.

<h3 id="example-rbs-pull">A readable byte stream with an underlying pull source</h3>

The following function returns <a>readable byte streams</a> that allow efficient zero-copy reading of files, again
using the <a href="https://nodejs.org/api/fs.html">Node.js file system API</a>. Instead of using a predetermined chunk
size of 1024, it attempts to fill the developer-supplied buffer, allowing full control.

<pre><code class="lang-javascript">
  const fs = require("pr/fs"); // https://github.com/jden/pr
  const DEFAULT_CHUNK_SIZE = 1024;

  function makeReadableByteFileStream(filename) {
    let fd;
    let position = 0;

    return new ReadableStream({
      type: "bytes",

      start() {
        return fs.open(filename, "r").then(result => {
          fd = result;
        });
      },

      pull(controller) {
        // Even when the consumer is using the default reader, the auto-allocation
        // feature allocates a buffer and passes it to us via byobRequest.
        const v = controller.byobRequest.view;

        return fs.read(fd, v.buffer, v.byteOffset, v.byteLength, position).then(bytesRead => {
          if (bytesRead === 0) {
            return fs.close(fd).then(() => controller.close());
          } else {
            position += bytesRead;
            controller.byobRequest.respond(bytesRead);
          }
        });
      },

      cancel() {
        return fs.close(fd);
      },

      autoAllocateChunkSize: DEFAULT_CHUNK_SIZE
    });
  }
</code></pre>

With this in hand, we can create and use <a>BYOB readers</a> for the returned {{ReadableStream}}. But we can
also create <a>default readers</a>, using them in the same simple and generic manner as usual. The adaptation between
the low-level byte tracking of the <a>underlying byte source</a> shown here, and the higher-level chunk-based
consumption of a <a>default reader</a>, is all taken care of automatically by the streams implementation. The
auto-allocation feature, via the <code><a for="underlying source">autoAllocateChunkSize</a></code> option, even allows
us to write less code, compared to the manual branching in [[#example-rbs-push]].

<h3 id="example-ws-no-backpressure">A writable stream with no backpressure or success signals</h3>

The following function returns a <a>writable stream</a> that wraps a {{WebSocket}} [[HTML]]. Web sockets do not provide
any way to tell when a given chunk of data has been successfully sent (without awkward polling of
{{WebSocket/bufferedAmount}}, which we leave as an exercise to the reader). As such, this writable stream has no ability
to communicate accurate <a>backpressure</a> signals or write success/failure to its <a>producers</a>. That is, the
promises returned by its <a>writer</a>'s {{WritableStreamDefaultWriter/write()}} method and
{{WritableStreamDefaultWriter/ready}} getter will always fulfill immediately.

<pre><code class="lang-javascript">
  function makeWritableWebSocketStream(url, protocols) {
    const ws = new WebSocket(url, protocols);

    return new WritableStream({
      start(controller) {
        ws.onerror = () => {
          controller.error(new Error("The WebSocket errored!"));
          ws.onclose = null;
        };
        ws.onclose = () => controller.error(new Error("The server closed the connection unexpectedly!"));
        return new Promise(resolve => ws.onopen = resolve);
      },

      write(chunk) {
        ws.send(chunk);
        // Return immediately, since the web socket gives us no easy way to tell
        // when the write completes.
      },

      close() {
        return closeWS(1000);
      },

      abort(reason) {
        return closeWS(4000, reason && reason.message);
      },
    });

    function closeWS(code, reasonString) {
      return new Promise((resolve, reject) => {
        ws.onclose = e => {
          if (e.wasClean) {
            resolve();
          } else {
            reject(new Error("The connection was not closed cleanly"));
          }
        };
        ws.close(code, reasonString);
      });
    }
  }
</code></pre>

We can then use this function to create writable streams for a web socket, and pipe an arbitrary readable stream to it:

<pre><code class="lang-javascript">
  const webSocketStream = makeWritableWebSocketStream("wss://example.com:443/", "protocol");

  readableStream.pipeTo(webSocketStream)
    .then(() => console.log("All data successfully written!"))
    .catch(e => console.error("Something went wrong!", e));
</code></pre>

<p class="note">See <a href="#note-web-socket-wrapping-examples">the earlier note</a> about this style of wrapping web
sockets into streams.</p>

<h3 id="example-ws-backpressure">A writable stream with backpressure and success signals</h3>

The following function returns <a>writable streams</a> that wrap portions of the <a
href="https://nodejs.org/api/fs.html">Node.js file system API</a> (which themselves map fairly directly to C's
<code>fopen</code>, <code>fwrite</code>, and <code>fclose</code> trio). Since the API we are wrapping provides a way to
tell when a given write succeeds, this stream will be able to communicate <a>backpressure</a> signals as well as whether
an individual write succeeded or failed.

<pre><code class="lang-javascript">
  const fs = require("pr/fs"); // https://github.com/jden/pr

  function makeWritableFileStream(filename) {
    let fd;

    return new WritableStream({
      start() {
        return fs.open(filename, "w").then(result => {
          fd = result;
        });
      },

      write(chunk) {
        return fs.write(fd, chunk, 0, chunk.length);
      },

      close() {
        return fs.close(fd);
      },

      abort() {
        return fs.close(fd);
      }
    });
  }
</code></pre>

We can then use this function to create a writable stream for a file, and write individual <a>chunks</a> of data to it:

<pre><code class="lang-javascript">
  const fileStream = makeWritableFileStream("/example/path/on/fs.txt");
  const writer = fileStream.getWriter();

  writer.write("To stream, or not to stream\n");
  writer.write("That is the question\n");

  writer.close()
    .then(() => console.log("chunks written and stream closed successfully!"))
    .catch(e => console.error(e));
</code></pre>

Note that if a particular call to <code>fs.write</code> takes a longer time, the returned promise will fulfill later.
In the meantime, additional writes can be queued up, which are stored in the stream's internal queue. The accumulation
of chunks in this queue can change the stream to return a pending promise from the {{WritableStreamDefaultWriter/ready}}
getter, which is a signal to <a>producers</a> that they would benefit from backing off and stopping writing, if
possible.

The way in which the writable stream queues up writes is especially important in this case, since as stated in
<a href="https://nodejs.org/api/fs.html#fs_fs_write_fd_data_position_encoding_callback">the documentation for
<code>fs.write</code></a>, "it is unsafe to use <code>fs.write</code> multiple times on the same file without waiting
for the [promise]." But we don't have to worry about that when writing the <code>makeWritableFileStream</code>
function, since the stream implementation guarantees that the <a>underlying sink</a>'s {{underlying sink/write()}}
method will not be called until any promises returned by previous calls have fulfilled!

<h3 id="example-both">A { readable, writable } stream pair wrapping the same underlying resource</h3>

The following function returns an object of the form <code>{ readable, writable }</code>, with the
<code>readable</code> property containing a readable stream and the <code>writable</code> property containing a
writable stream, where both streams wrap the same underlying web socket resource. In essence, this combines
[[#example-rs-push-no-backpressure]] and [[#example-ws-no-backpressure]].

While doing so, it illustrates how you can use JavaScript classes to create reusable underlying sink and underlying
source abstractions.

<pre><code class="lang-javascript">
  function streamifyWebSocket(url, protocol) {
    const ws = new WebSocket(url, protocols);
    ws.binaryType = "arraybuffer";

    return {
      readable: new ReadableStream(new WebSocketSource(ws)),
      writable: new WritableStream(new WebSocketSink(ws))
    };
  }

  class WebSocketSource {
    constructor(ws) {
      this._ws = ws;
    }

    start(controller) {
      this._ws.onmessage = event => controller.enqueue(event.data);
      this._ws.onclose = () => controller.close();

      this._ws.addEventListener("error", () => {
        controller.error(new Error("The WebSocket errored!"));
      });
    }

    cancel() {
      this._ws.close();
    }
  }

  class WebSocketSink {
    constructor(ws) {
      this._ws = ws;
    }

    start(controller) {
      this._ws.onclose = () => controller.error(new Error("The server closed the connection unexpectedly!"));
      this._ws.addEventListener("error", () => {
        controller.error(new Error("The WebSocket errored!"));
        this._ws.onclose = null;
      });

      return new Promise(resolve => this._ws.onopen = resolve);
    }

    write(chunk) {
      this._ws.send(chunk);
    }

    close() {
      return this._closeWS(1000);
    }

    abort(reason) {
      return this._closeWS(4000, reason && reason.message);
    }

    _closeWS(code, reasonString) {
      return new Promise((resolve, reject) => {
        this._ws.onclose = e => {
          if (e.wasClean) {
            resolve();
          } else {
            reject(new Error("The connection was not closed cleanly"));
          }
        };
        this._ws.close(code, reasonString);
      });
    }
  }
</code></pre>

We can then use the objects created by this function to communicate with a remote web socket, using the standard stream
APIs:

<pre><code class="lang-javascript">
  const streamyWS = streamifyWebSocket("wss://example.com:443/", "protocol");
  const writer = streamyWS.writable.getWriter();
  const reader = streamyWS.readable.getReader();

  writer.write("Hello");
  writer.write("web socket!");

  reader.read().then(({ value, done }) => {
    console.log("The web socket says: ", value);
  });
</code></pre>

Note how in this setup canceling the <code>readable</code> side will implicitly close the <code>writable</code> side,
and similarly, closing or aborting the <code>writable</code> side will implicitly close the <code>readable</code> side.

<p class="note">See <a href="#note-web-socket-wrapping-examples">the earlier note</a> about this style of wrapping web
sockets into streams.</p>

</div>

<h3 id="example-ts-lipfuzz">A transform stream that replaces template tags</h3>

It's often useful to substitute tags with variables on a stream of data, where the parts that need to be replaced are
small compared to the overall data size. This example presents a simple way to do that. It maps strings to strings,
transforming a template like <code>"Time: \{{time}} Message: \{{message}}"</code> to <code>"Time: 15:36 Message:
hello"</code> assuming that <code>{ time: "15:36", message: "hello" }</code> was passed in the
<code>substitutions</code> parameter to <code>LipFuzzTransformer</code>.

This example also demonstrates one way to deal with a situation where a chunk contains partial data that cannot be
transformed until more data is received. In this case, a partial template tag will be accumulated in the
<code>partialChunk</code> instance variable until either the end of the tag is found or the end of the stream is
reached.

<pre><code class="lang-javascript">
  class LipFuzzTransformer {
    constructor(substitutions) {
      this.substitutions = substitutions;
      this.partialChunk = "";
      this.lastIndex = undefined;
    }

    transform(chunk, controller) {
      chunk = this.partialChunk + chunk;
      this.partialChunk = "";
      // lastIndex is the index of the first character after the last substitution.
      this.lastIndex = 0;
      chunk = chunk.replace(/\{\{([a-zA-Z0-9_-]+)\}\}/g, this.replaceTag.bind(this));
      // Regular expression for an incomplete template at the end of a string.
      const partialAtEndRegexp = /\{(\{([a-zA-Z0-9_-]+(\})?)?)?$/g;
      // Avoid looking at any characters that have already been substituted.
      partialAtEndRegexp.lastIndex = this.lastIndex;
      this.lastIndex = undefined;
      const match = partialAtEndRegexp.exec(chunk);
      if (match) {
        this.partialChunk = chunk.substring(match.index);
        chunk = chunk.substring(0, match.index);
      }
      controller.enqueue(chunk);
    }

    flush(controller) {
      if (this.partialChunk.length > 0) {
        controller.enqueue(this.partialChunk);
      }
    }

    replaceTag(match, p1, offset) {
      let replacement = this.substitutions[p1];
      if (replacement === undefined) {
        replacement = "";
      }
      this.lastIndex = offset + replacement.length;
      return replacement;
    }
  }
</code></pre>

In this case we define the <a>transformer</a> to be passed to the {{TransformStream}} constructor as a class. This is
useful when there is instance data to track.

The class would be used in code like:

<pre><code class="lang-javascript">
  const data = { userName, displayName, icon, date };
  const ts = new TransformStream(new LipFuzzTransformer(data));

  fetchEvent.respondWith(
    fetch(fetchEvent.request.url).then(response => {
      const transformedBody = response.body
        // Decode the binary-encoded response to string
        .pipeThrough(new TextDecoderStream())
        // Apply the LipFuzzTransformer
        .pipeThrough(ts)
        // Encode the transformed string
        .pipeThrough(new TextEncoderStream());
      return new Response(transformedBody);
    })
  );
</code></pre>

<div class="warning">For simplicity, <code>LipFuzzTransformer</code> performs unescaped text substitutions. In real
applications, a template system that performs context-aware escaping is good practice for security and robustness.</div>

<h3 id="example-ts-sync-mapper">A transform stream created from a sync mapper function</h3>

The following function allows creating new {{TransformStream}} instances from synchronous "mapper" functions, of the
type you would normally pass to {{Array.prototype/map|Array.prototype.map}}. It demonstrates that the API is concise
even for trivial transforms.

<pre><code class="lang-javascript">
  function mapperTransformStream(mapperFunction) {
    return new TransformStream({
      transform(chunk, controller) {
        controller.enqueue(mapperFunction(chunk));
      }
    });
  }
</code></pre>

This function can then be used to create a {{TransformStream}} that uppercases all its inputs:

<pre><code class="lang-javascript">
  const ts = mapperTransformStream(chunk => chunk.toUpperCase());
  const writer = ts.writable.getWriter();
  const reader = ts.readable.getReader();

  writer.write("No need to shout");

  // Logs "NO NEED TO SHOUT":
  reader.read().then(({ value }) => console.log(value));
</code></pre>

Although a synchronous transform never causes backpressure itself, it will only transform chunks as long as there is no
backpressure, so resources will not be wasted.

Exceptions error the stream in a natural way:

<pre><code class="lang-javascript">
  const ts = mapperTransformStream(chunk => JSON.parse(chunk));
  const writer = ts.writable.getWriter();
  const reader = ts.readable.getReader();

  writer.write("[1, ");

  // Logs a SyntaxError, twice:
  reader.read().catch(e => console.error(e));
  writer.write("{}").catch(e => console.error(e));
</code></pre>

<h2 id="conventions" class="no-num">Conventions</h2>

This specification depends on the Infra Standard. [[!INFRA]]

This specification uses algorithm conventions very similar to those of [[!ECMASCRIPT]], whose rules should be used to
interpret it (apart from the exceptions enumerated below). In particular, the objects specified here should be treated
as <a href="https://tc39.github.io/ecma262/#sec-ecmascript-standard-built-in-objects">built-in objects</a>. For example,
their <code>name</code> and <code>length</code> properties are derived as described by that specification, as are the
default property descriptor values and the treatment of missing, <emu-val>undefined</emu-val>, or surplus arguments.

We also depart from the [[!ECMASCRIPT]] conventions in the following ways, mostly for brevity. It is hoped (and vaguely
planned) that the conventions of ECMAScript itself will evolve in these ways.

<ul>
  <li> We prefix section headings with <code>new</code> to indicate they are defining constructors; when doing so, we
  assume that NewTarget will be checked before the algorithm starts.
  <li> We use the default argument notation <code>= {}</code> in a couple of cases, meaning that before the algorithm
    starts, <emu-val>undefined</emu-val> (including the implicit <emu-val>undefined</emu-val> when no argument is
    provided) is instead treated as a new object created as if by ObjectCreate(%ObjectPrototype%). (This object may then
    be destructured, if combined with the below destructuring convention.)
  <li> We use destructuring notation in function and method declarations, and assume that <a
    abstract-op>DestructuringAssignmentEvaluation</a> was performed appropriately before the algorithm starts.
  <li> We use "<emu-val>this</emu-val>" instead of "<emu-val>this</emu-val> value".
</ul>

It's also worth noting that, as in [[!ECMASCRIPT]], all numbers are represented as double-precision floating point
values, and all arithmetic operations performed on them must be done in the standard way for such values.

<h2 id="acks" class="no-num">Acknowledgments</h2>

The editors would like to thank
Anne van Kesteren,
AnthumChris,
Arthur Langereis,
Ben Kelly,
Bert Belder,
Brian di Palma,
Calvin Metcalf,
Dominic Tarr,
Ed Hager,
Forbes Lindesay,
Forrest Norvell,
Gary Blackwood,
Gorgi Kosev,
Gus Caplan,
贺师俊 (hax),
Isaac Schlueter,
isonmad,
Jake Archibald,
Jake Verbaten,
Janessa Det,
Jason Orendorff,
Jens Nockert,
Lennart Grahl,
Mangala Sadhu Sangeet Singh Khalsa,
Marcos Caceres,
Marvin Hagemeister,
Mattias Buelens,
Michael Mior,
Mihai Potra,
Romain Bellessort, <!-- rombel on GitHub -->
Simon Menke,
Stephen Sugden,
Surma,
Tab Atkins,
Tanguy Krotoff,
Thorsten Lorenz,
Till Schneidereit,
Tim Caswell,
Trevor Norris,
tzik,
Will Chan,
Youenn Fablet,
平野裕 (Yutaka Hirano),
and
Xabier Rodríguez
for their contributions to this specification. Community involvement in this specification has been above and beyond; we
couldn't have done it without you.

This standard is written by Adam Rice (<a href="https://google.com">Google</a>, <a
href="mailto:ricea@chromium.org">ricea@chromium.org</a>), <a href="https://domenic.me/">Domenic Denicola</a> (<a
href="https://google.com">Google</a>, <a href="mailto:d@domenic.me">d@domenic.me</a>), and 吉野剛史 (Takeshi Yoshino, <a
href="https://google.com">Google</a>, <a href="mailto:tyoshino@chromium.org">tyoshino@chromium.org</a>).
