Skip to content
Closed
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
8 changes: 8 additions & 0 deletions .changeset/bundler-worker-clone.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@doc-kit/core': patch
'@doc-kit/generator-react': patch
---

Omit `bundler` from the configuration sent to worker threads so a custom HTML
bundler adapter (including `createViteBundler(...)`) no longer throws
`DataCloneError` when builds use more than one thread.
4 changes: 3 additions & 1 deletion docs/creating-generators.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,9 @@ Filtering entries is light work, but heavier work takes the same shape.
are copied between threads with the
[structured clone algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
Functions can't be copied (passing one throws a `DataCloneError`), and class
instances arrive as plain objects.
instances arrive as plain objects. Keys that are expected to hold functions
(such as `html.bundler`) are omitted from the worker copy: those adapters
run only on the main thread that builds assets.
- Each worker imports your module on its own, so `processChunk` sees nothing
`generate` set up: pass what it needs in `deps`. A module only
`processChunk` uses can be imported inside it, as the `metadata` generator
Expand Down
42 changes: 42 additions & 0 deletions packages/core/src/threading/__tests__/parallel.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,48 @@ describe('createParallelWorker', () => {
await pool.destroy();
});

it('omits bundler adapters from the configuration sent to workers', async () => {
let captured;

const pool = {
run: async task => {
captured = task;
return task.input;
},
};

const bundler = {
buildServer: async () => 'file:///library.js',
compile: async code => code,
buildClient: async () => ({ scripts: [], preloads: [], stylesheets: [] }),
};

const worker = createParallelWorker(
'html',
{
name: 'html',
processChunk: async (input, indices) => indices.map(i => input[i]),
},
pool,
{
threads: 2,
chunkSize: 10,
html: {
output: '/tmp/out',
bundler,
},
}
);

await collectStream(worker.stream([{ id: 1 }, { id: 2 }, { id: 3 }], {}));

ok(captured);
deepStrictEqual(captured.configuration.html.output, '/tmp/out');
strictEqual(captured.configuration.html.bundler, undefined);
// structured clone would throw if bundler were still present
structuredClone(captured.configuration);
});

it('should handle empty items array', async () => {
const pool = createWorkerPool(2);
const worker = createParallelWorker('ast-js', astJsGenerator, pool, {
Expand Down
23 changes: 20 additions & 3 deletions packages/core/src/threading/parallel.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
'use strict';

import logger from '#logger/index.mjs';
import { isAsyncIterable } from '#utils/misc.mjs';
import { isAsyncIterable, omitKeys } from '#utils/misc.mjs';

import { CHUNKS_PER_THREAD } from './constants.mjs';

/**
* Configuration keys that may hold functions (or other non-cloneable values).
* Worker threads only need the rest of the generator options for rendering;
* adapters such as `html.bundler` stay on the main thread that builds assets.
*
* @see https://github.com/nodejs/doc-kit/issues/1201
*/
const NON_CLONEABLE_CONFIG_KEYS = ['bundler'];

const parallelLogger = logger.child('parallel');

/**
Expand Down Expand Up @@ -45,16 +54,24 @@ const createTask = (
generatorSpecifier,
generatorName
) => {
const generatorConfiguration = configuration[generatorName];

return {
generatorSpecifier,
// Only send the items needed for this chunk (reduces serialization overhead)
input: indices.map(i => fullInput[i]),
// Remap indices to 0-based for the sliced array
itemIndices: indices.map((_, i) => i),
extra,
// Only pass the needed configuration to this generator
// Only pass the needed configuration to this generator. Drop keys that
// hold functions (e.g. a custom `bundler` adapter): workers receive a
// structured clone of this object, and those adapters are only used on
// the main thread before pages are farmed out.
configuration: {
[generatorName]: configuration[generatorName],
[generatorName]:
generatorConfiguration && typeof generatorConfiguration === 'object'
? omitKeys(generatorConfiguration, NON_CLONEABLE_CONFIG_KEYS)
: generatorConfiguration,
},
};
};
Expand Down
13 changes: 5 additions & 8 deletions packages/react/src/html/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -534,11 +534,10 @@ When you customize the site, keep in mind that:
The `bundler` option takes a small adapter, so the site can be built with Vite
(the default) or any other bundler.

> [!WARNING]
> Worker threads receive a copy of the configuration, and functions can't be
> copied. A configuration that sets `bundler`, the Vite adapter included, must
> build with `threads: 1` (or `--threads 1`). With more threads, the build
> fails with a `DataCloneError`.
The adapter stays on the main thread that builds the component library and
client assets. Worker threads that render pages receive the rest of the `html`
configuration without `bundler`, so a custom adapter (including
`createViteBundler(...)`) works with the default thread count.

### Writing an adapter

Expand Down Expand Up @@ -584,7 +583,7 @@ CSS modules, resolve the `config.imports` aliases, and serve the
indefinitely.

An adapter can live in your project, without changes to doc-kit. Pass it as
`bundler`, with `threads: 1`:
`bundler`:

```js displayName="webpack-bundler.mjs"
export const createWebpackBundler = webpackOptions => ({
Expand Down Expand Up @@ -617,8 +616,6 @@ import { createViteBundler } from '@doc-kit/generator-react/html/bundlers/vite';
import myVitePlugin from './my-vite-plugin.mjs';

export default {
threads: 1,

html: {
bundler: createViteBundler({
plugins: [myVitePlugin()],
Expand Down