Skip to content

Commit 8e8c749

Browse files
authored
perf: let jsx-ast and html start on their dependency's first chunk
With more than one thread, jsx-ast builds pages as their entries arrive and html compiles, bundles and renders them as it receives them, so page building and rendering overlap with the generators before them. The generated files are unchanged. jsx-ast yields its pages in the order their entries arrived, and once every page has, a { manifest } item with all their heads in that order. html compiles each page as it comes, bundles the component library and the client assets as soon as the manifest does, and has the workers render the pages as they are compiled. To list the pages as the site does, headingSortFn is now exported. Bundler adapters' compile can now run before and alongside buildServer and buildClient. createChannel is the queue html hands its compiled pages to the workers on, and merge yields from several async iterables as items arrive: jsx-ast announces the manifest next to its pages with it. Assisted-by: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent f24ad17 commit 8e8c749

20 files changed

Lines changed: 1150 additions & 130 deletions

File tree

‎.changeset/stream-pages.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@doc-kit/core': minor
3+
'@doc-kit/generator-react': minor
4+
---
5+
6+
`jsx-ast` and `html` stream their input: with more than one thread, page building and rendering overlap with the generators before them. `html` bundles as soon as every page's metadata is known, and renders pages as they are built. Streaming leaves the generated files unchanged, but `jsx-ast` now yields pages in the order their entries arrive, not the order the site lists them, and, once every page has arrived, a `{ manifest }` item listing their heads in that order. To list the pages as the site does, skip the `{ manifest }` item and sort them with `headingSortFn`, now exported from `@doc-kit/generator-react/jsx-ast/utils/getSortedHeadNodes`, as `pages.toSorted((a, b) => headingSortFn(a.data, b.data))`, keeping the synthetic pages (`data.synthetic`) last. Bundler adapters' `compile` can now be called before and while `buildServer` and `buildClient` run. `createChannel` and `merge`, from `@doc-kit/core/utils`, are the queue and the merge of async iterables they are built on.
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import { deepStrictEqual } from 'node:assert';
2+
import { describe, it } from 'node:test';
3+
4+
import { createChannel } from '../channel.mjs';
5+
6+
/**
7+
* Reads every batch of an async iterable.
8+
*
9+
* @template T
10+
* @param {AsyncIterable<T[]>} iterable
11+
* @returns {Promise<T[][]>}
12+
*/
13+
async function readBatches(iterable) {
14+
const batches = [];
15+
16+
for await (const batch of iterable) {
17+
batches.push(batch);
18+
}
19+
20+
return batches;
21+
}
22+
23+
describe('createChannel', () => {
24+
it('gives the batches as they are added, until it ends', async () => {
25+
const channel = createChannel();
26+
const reading = readBatches(channel);
27+
28+
channel.push([1]);
29+
await new Promise(resolve => setImmediate(resolve));
30+
channel.push([2]);
31+
channel.end();
32+
33+
const batches = await reading;
34+
35+
deepStrictEqual(batches, [[1], [2]]);
36+
});
37+
38+
it('gives a prepended batch before those not read yet', async () => {
39+
const channel = createChannel();
40+
41+
channel.push([1]);
42+
channel.push([2]);
43+
channel.prepend([0]);
44+
channel.end();
45+
46+
const batches = await readBatches(channel);
47+
48+
deepStrictEqual(batches, [[0], [1], [2]]);
49+
});
50+
51+
it('drops the batches not read yet when cleared', async () => {
52+
const channel = createChannel();
53+
54+
channel.push([1]);
55+
channel.clear();
56+
channel.push([2]);
57+
channel.end();
58+
59+
const batches = await readBatches(channel);
60+
61+
deepStrictEqual(batches, [[2]]);
62+
});
63+
});

‎packages/core/src/utils/__tests__/generators.test.mjs‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
getVersionFromSemVer,
88
coerceSemVer,
99
getCompatibleVersions,
10+
merge,
1011
toBatches,
1112
} from '../generators.mjs';
1213

@@ -148,3 +149,56 @@ describe('toBatches', () => {
148149
assert.equal(toBatches(streamed), streamed);
149150
});
150151
});
152+
153+
describe('merge', () => {
154+
it('yields each item as soon as it arrives, until every source ends', async () => {
155+
const gate = Promise.withResolvers();
156+
157+
async function* slow() {
158+
await gate.promise;
159+
160+
yield 'slow';
161+
}
162+
163+
async function* fast() {
164+
yield 'fast';
165+
yield 'faster';
166+
}
167+
168+
const items = [];
169+
170+
for await (const item of merge(slow(), fast())) {
171+
items.push(item);
172+
173+
if (item === 'faster') {
174+
gate.resolve();
175+
}
176+
}
177+
178+
assert.deepEqual(items, ['fast', 'faster', 'slow']);
179+
});
180+
181+
it('throws a failure without waiting for the other sources', async () => {
182+
async function* never() {
183+
await new Promise(() => {});
184+
185+
yield 'never';
186+
}
187+
188+
async function* failing() {
189+
yield 'before';
190+
191+
throw new Error('merged failure');
192+
}
193+
194+
const items = [];
195+
196+
await assert.rejects(async () => {
197+
for await (const item of merge(never(), failing())) {
198+
items.push(item);
199+
}
200+
}, /merged failure/);
201+
202+
assert.deepEqual(items, ['before']);
203+
});
204+
});
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
'use strict';
2+
3+
import { createSignal } from './misc.mjs';
4+
5+
/**
6+
* Creates a queue of batches that can be read as an async iterable while it is
7+
* still being filled.
8+
*
9+
* @template T
10+
*/
11+
export const createChannel = () => {
12+
/** @type {Array<T[]>} */
13+
const batches = [];
14+
15+
// Notified as batches are added, and at the end
16+
const added = createSignal();
17+
18+
let ended = false;
19+
20+
return {
21+
/**
22+
* Adds a batch, after those not read yet.
23+
*
24+
* @param {T[]} batch
25+
*/
26+
push(batch) {
27+
batches.push(batch);
28+
added.notify();
29+
},
30+
31+
/**
32+
* Adds a batch, before those not read yet.
33+
*
34+
* @param {T[]} batch
35+
*/
36+
prepend(batch) {
37+
batches.unshift(batch);
38+
added.notify();
39+
},
40+
41+
/**
42+
* Drops the batches not read yet.
43+
*/
44+
clear() {
45+
batches.length = 0;
46+
},
47+
48+
/**
49+
* Ends the channel: the reader stops once it has read every batch.
50+
*/
51+
end() {
52+
ended = true;
53+
added.notify();
54+
},
55+
56+
/**
57+
* Reads the batches as they are added, until the channel ends.
58+
*
59+
* @returns {AsyncGenerator<T[]>}
60+
*/
61+
async *[Symbol.asyncIterator]() {
62+
for (;;) {
63+
while (batches.length === 0) {
64+
if (ended) {
65+
return;
66+
}
67+
68+
await added.wait();
69+
}
70+
71+
yield batches.shift();
72+
}
73+
},
74+
};
75+
};

‎packages/core/src/utils/generators.mjs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { coerce, major } from 'semver';
44

5+
import { createChannel } from './channel.mjs';
56
import { isAsyncIterable } from './misc.mjs';
67
import { transformNodeToString } from './unist.mjs';
78

@@ -59,6 +60,54 @@ export const toBatches = input => {
5960
return [input];
6061
};
6162

63+
/**
64+
* Reads several async iterables at once, yielding each item as soon as it
65+
* arrives, until they have all ended. A failure is thrown once the items that
66+
* arrived before it are yielded, without waiting for the other iterables.
67+
*
68+
* @template T
69+
* @param {...AsyncIterable<T>} sources
70+
* @returns {AsyncGenerator<T>}
71+
*/
72+
export async function* merge(...sources) {
73+
const channel = createChannel();
74+
75+
let pending = sources.length;
76+
let failure;
77+
78+
/**
79+
* Passes a source's items on as they arrive, and ends the channel once every
80+
* source has ended, or one fails.
81+
*
82+
* @param {AsyncIterable<T>} source
83+
*/
84+
const pipe = async source => {
85+
try {
86+
for await (const item of source) {
87+
channel.push(item);
88+
}
89+
} catch (error) {
90+
failure ??= { error };
91+
} finally {
92+
pending--;
93+
94+
if (failure || pending === 0) {
95+
channel.end();
96+
}
97+
}
98+
};
99+
100+
for (const source of sources) {
101+
pipe(source);
102+
}
103+
104+
yield* channel;
105+
106+
if (failure) {
107+
throw failure.error;
108+
}
109+
}
110+
62111
/**
63112
* Parses the SemVer string into a Node.js-alike version
64113
*

‎packages/react/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"./html/ui/*": "./src/html/ui/*",
1616
"./html/bundlers/vite": "./src/html/bundlers/vite.mjs",
1717
"./jsx-ast": "./src/jsx-ast/index.mjs",
18+
"./jsx-ast/utils/getSortedHeadNodes": "./src/jsx-ast/utils/getSortedHeadNodes.mjs",
1819
"./llms-txt": "./src/llms-txt/index.mjs",
1920
"./llms-txt-full": "./src/llms-txt-full/index.mjs",
2021
"./orama-db": "./src/orama-db/index.mjs",

‎packages/react/src/html/README.md‎

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@ assets, written to `output`. Vite is the default bundler adapter, but projects
66
can supply an adapter for webpack or another bundler. The generator is
77
output-only and does not return an in-memory copy of its HTML or CSS.
88

9-
The site is built in pieces that are each as small as they can be. The bundler
10-
builds the component library once and the client assets once. Each page's
11-
program is then compiled — JSX to a plain module — and the worker pool imports,
12-
renders, templates, minifies and writes the pages one at a time, so memory
13-
scales with the largest page rather than with the site. `all.html` is assembled
14-
from the module pages' compiled content rather than built again from scratch.
9+
The site is built in pieces that are each as small as they can be, each as
10+
soon as what it needs is there. Each page's program is compiled — JSX to a
11+
plain module — as `jsx-ast` builds the page. The bundler builds the component
12+
library once and the client assets once, as soon as every page's metadata is
13+
known, and the worker pool imports, renders, templates, minifies and writes
14+
the pages one at a time as they are compiled, so memory scales with the largest
15+
page rather than with the site. With one thread, each step waits for the one
16+
before it to finish. `all.html` is assembled from the module pages' compiled
17+
content rather than built again from scratch.
1518

1619
## Configuring
1720

@@ -201,16 +204,21 @@ for a particular build system.
201204
`buildServer` receives `{ entry, virtualImports, outDir, config }`. The `entry`
202205
is the component library's source: re-exports of every component a page may
203206
render, Preact's `h` and `Fragment`, and `renderToStringAsync`. It must be
204-
bundled into one self-contained module written under `outDir` (a temporary
205-
directory the generator removes afterwards), since the page programs import it
206-
from wherever they are compiled to.
207+
bundled into one self-contained module written under `outDir` (an empty
208+
temporary directory the generator removes afterwards), since the page programs
209+
import it from wherever they are compiled to.
207210

208211
`compile(code, fileName)` receives one page program: a module that imports the
209212
library and exports the page's `content` and a default function rendering the
210-
page from its layout props, written in JSX. It must return plain JavaScript. The JSX must compile with the classic
211-
runtime to calls of the `_jsx` and `_Fragment` bindings the program imports
212-
(these names are exported as `JSX_PRAGMA` and `JSX_PRAGMA_FRAG` from the
213-
generator's `constants.mjs`), so that the page and the library share one Preact.
213+
page from its layout props, written in JSX. It must return plain JavaScript.
214+
Pages are compiled as they are built, so `compile` can be called before
215+
`buildServer`, and while `buildServer` or `buildClient` still runs: it must
216+
leave the program's imports as they are, since the library they point to may
217+
not exist yet, and must not depend on the builds. The JSX must compile with the
218+
classic runtime to calls of the `_jsx` and `_Fragment` bindings the program
219+
imports (these names are exported as `JSX_PRAGMA` and `JSX_PRAGMA_FRAG` from
220+
the generator's `constants.mjs`), so that the page and the library share one
221+
Preact.
214222
215223
`buildClient` receives `{ entry, virtualImports, config }`. The client `entry`
216224
is a single program shared by every page. It must be bundled into

0 commit comments

Comments
 (0)