
# Streams

Phasis implementuje celý [standard WHATWG Streams](https://streams.spec.whatwg.org/). Každá třída, každý režim čtečky, každá pomocná funkce. Stejný kód, který funguje v Node a moderních prohlížečích, funguje i v Phasis.

Implementace je ta, kterou `fetch` používá interně — `Response.body` je skutečný `ReadableStream`, `Request` přijímá proudová těla a funguje i `tee()` potřebné ke klonování Response.

## Co je k dispozici

| Třída | Stav |
|---|---|
| `ReadableStream` | Úplné |
| `ReadableStreamDefaultController` | Úplné |
| `ReadableByteStreamController` | Úplné |
| `ReadableStreamDefaultReader` | Úplné |
| `ReadableStreamBYOBReader` | Úplné |
| `ReadableStreamBYOBRequest` | Úplné |
| `WritableStream` | Úplné |
| `WritableStreamDefaultController` | Úplné |
| `WritableStreamDefaultWriter` | Úplné |
| `TransformStream` | Úplné |
| `TransformStreamDefaultController` | Úplné |
| `ByteLengthQueuingStrategy` | Úplné |
| `CountQueuingStrategy` | Úplné |

A také metody, které se nejčastěji používají: `pipeTo`, `pipeThrough`, `tee`, `getReader`, asynchronní iterace, `Symbol.asyncIterator`, čtení BYOB pomocí `{ min }`.

## Vytváření

```js
// Pull-based — only generates values when read
const counter = new ReadableStream({
  start(controller) { this.n = 0; },
  pull(controller) {
    if (this.n >= 5) { controller.close(); return; }
    controller.enqueue(this.n++);
  },
});

for await (const v of counter) console.log(v);  // 0,1,2,3,4
```

```js
// Push-based — start enqueues everything eagerly
const small = new ReadableStream({
  start(c) {
    [10, 20, 30].forEach(n => c.enqueue(n));
    c.close();
  },
});
```

## Čtení

Tři způsoby čtení:

```js
// 1. Reader
const reader = stream.getReader();
while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  console.log(value);
}
reader.releaseLock();

// 2. Async iteration (preferred)
for await (const chunk of stream) {
  console.log(chunk);
}

// 3. tee + parallel pipes
const [a, b] = stream.tee();
await Promise.all([a.pipeTo(sinkA), b.pipeTo(sinkB)]);
```

## Transformace

```js
const upper = new TransformStream({
  transform(chunk, controller) {
    controller.enqueue(chunk.toUpperCase());
  },
});

const result = new ReadableStream({
  start(c) { ['hi', 'there'].forEach(s => c.enqueue(s)); c.close(); }
}).pipeThrough(upper);

for await (const v of result) console.log(v);  // HI, THERE
```

## Bajtové proudy (BYOB)

```js
const bytes = new ReadableStream({
  type: 'bytes',
  start(controller) {
    controller.enqueue(new Uint8Array([1, 2, 3, 4, 5, 6]));
    controller.close();
  },
});

const reader = bytes.getReader({ mode: 'byob' });
const buf = new Uint8Array(4);
const { value, done } = await reader.read(buf);
// value is a Uint8Array of length 4, sharing buffer with `buf`
```

`{ min: N }` je podporováno — `read(view, { min: 2 })` se vyřeší až ve chvíli, kdy jsou k dispozici alespoň 2 prvky.

## Zpětný tlak

`desiredSize` a `ready` fungují podle specifikace. Pomocí strategie fronty můžete producentovi předat zpětnou vazbu:

```js
const stream = new ReadableStream({
  pull(controller) {
    if (controller.desiredSize <= 0) return;  // back off
    controller.enqueue(nextChunk());
  },
}, new CountQueuingStrategy({ highWaterMark: 4 }));
```

## S fetch

```js
// Response body is a ReadableStream
const res = await fetch('https://example.com/big.txt');
let total = 0;
for await (const chunk of res.body) {
  total += chunk.byteLength;
}

// Request bodies can stream too
const upload = new ReadableStream({
  start(c) { c.enqueue(new TextEncoder().encode('hello')); c.close(); }
});
await fetch('https://example.com/upload', { method: 'POST', body: upload });
```

## Rozdělení proudu pro ukládání do mezipaměti

Běžný vzor: přečíst tělo dvakrát.

```js
const res = await fetch(url);
const [forCache, forUse] = res.body.tee();
await Promise.all([
  forCache.pipeTo(cacheWritable),
  parseJson(forUse),
]);
```

`Response.clone()` to udělá za vás a vrátí nový `Response`.

## Omezení

- **Pouze synchronní producenti.** `pull()`, který provádí blokující I/O PHP, zablokuje skript. Pro HTTP použijte přenosový hook fetch; u souborů je lepší nejprve načíst celý obsah do paměti. K dispozici jsou `setTimeout` / `setInterval` (viz [Smyčka událostí](https://phasis.inline0.dev/cs/docs/api#event-loop)), ale modul ve výchozím nastavení používá **virtuální čas** — `pull()` uvnitř `setTimeout(cb, 1000)` nespí PHP, ale posune hodiny smyčky. Pro běh v reálném čase musí hostitel řídit `tickEventLoop()` podle skutečných hodin.

## Viz také

- [Webová API (WPT)](https://phasis.inline0.dev/cs/docs/compatibility/web-apis) — tabulka úspěšnosti WPT pro podtesty Streams.
- [Přenos fetch](https://phasis.inline0.dev/cs/docs/interop/fetch-transport) — jak těla požadavků a odpovědí překračují hranici PHP/JS.
- [Vzorové použití AbortController](https://phasis.inline0.dev/cs/docs/interop/abort-patterns) — rušení probíhajícího čtení.
