Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/brisk-pipes-flush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'preact-render-to-string': patch
---

`renderToPipeableStream` flushes a destination that has a `flush()` method, such as a response behind Express's `compression()` middleware, so the shell and each boundary reach the browser as they render instead of all at the end. `pipe()` returns the destination, and a response that `onShellError` already ended is no longer destroyed.
2 changes: 1 addition & 1 deletion src/stream-node.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface RenderToPipeableStreamOptions {

interface PipeableStream {
abort: (reason?: unknown) => void;
pipe: (writable: Writable) => void;
pipe: <T extends Writable>(writable: T) => T;
}

export function renderToPipeableStream<P = {}>(
Expand Down
27 changes: 24 additions & 3 deletions src/stream-node.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { renderToChunks } from './lib/chunked.js';
/**
* @typedef {object} PipeableStream
* @property {() => void} abort
* @property {(writable: import('stream').Writable) => void} pipe
* @property {<T extends import('stream').Writable>(writable: T) => T} pipe
*/

/**
Expand Down Expand Up @@ -75,18 +75,39 @@ export function renderToPipeableStream(vnode, options, context) {
return {
abort,
/**
* @param {import("stream").Writable} writable
* @template {import("stream").Writable} T
* @param {T} writable
* @returns {T}
*/
pipe(writable) {
stream.pipe(writable, { end: true });
// Compression middleware buffers until it is told to flush. This runs
// after pipe's own listener, once a tick's chunks reached the writable.
if (typeof writable.flush == 'function') {
let scheduled = false;
stream.on('data', () => {
if (scheduled) return;
scheduled = true;
setImmediate(() => {
scheduled = false;
if (!writable.destroyed && !writable.writableEnded) {
writable.flush();
}
});
});
}
stream.once('close', () => {
if (!stream.readableEnded) writable.destroy();
// onShellError may have answered with its own response already
if (!stream.readableEnded && !writable.writableEnded) {
writable.destroy();
}
});
writable.once('close', () => {
if (!writable.writableFinished) {
abort(new Error('The destination stream closed early.'));
}
});
return writable;
}
};
}
63 changes: 63 additions & 0 deletions test/compat/stream-node.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -241,4 +241,67 @@ describe('renderToPipeableStream', () => {
createSubtree(id, '')
]);
});

it('should flush a destination that buffers once the written chunks reached it', async () => {
const first = createSuspender();
const second = createSuspender();
const sink = createSink();
const decoder = new TextDecoder();
let received = '';
const flushed = [];
sink.stream.on('data', (chunk) => (received += decoder.decode(chunk)));
sink.stream.flush = () => flushed.push(received);
const { pipe } = renderToPipeableStream(
<div>
<Suspense fallback="first...">
<first.Suspender>first</first.Suspender>
</Suspense>
<Suspense fallback="second...">
<second.Suspender>second</second.Suspender>
</Suspense>
</div>,
{ onShellReady: () => pipe(sink.stream) }
);
await new Promise((r) => setTimeout(r, 10));

expect(flushed).to.have.length(1);
expect(flushed[0]).to.contain('second...');
expect(flushed[0]).to.contain(createInitScript());

first.suspended.resolve();
await new Promise((r) => setTimeout(r, 10));

expect(flushed).to.have.length(2);
expect(flushed[1]).to.contain('>first</template>');

second.suspended.resolve();
await sink.promise;
await new Promise((r) => setTimeout(r, 10));

expect(flushed).to.have.length(2);
});

it('should return the destination from pipe', async () => {
const sink = createSink();
const { pipe } = renderToPipeableStream(<div />, {});
expect(pipe(sink.stream)).to.equal(sink.stream);
await sink.promise;
});

it('should not destroy a destination that onShellError ended', async () => {
function Thrower() {
throw new Error('shell failed');
}
const destination = new PassThrough({ autoDestroy: false });
const output = streamToString(destination);
const { pipe } = renderToPipeableStream(<Thrower />, {
onError() {},
onShellError: () => destination.end('error page')
});
pipe(destination);

expect(await output.promise).to.deep.equal(['error page']);
await new Promise((r) => setTimeout(r));
expect(destination.destroyed).to.equal(false);
});
});
Loading