UNPKG

histoire

Version:

A fast story book powered by Vite

172 lines (171 loc) • 6.84 kB
import { cpus } from 'node:os'; import { MessageChannel } from 'node:worker_threads'; import Tinypool from '@akryum/tinypool'; import { createBirpc } from 'birpc'; import path from 'pathe'; import pc from 'picocolors'; import { ViteNodeServer } from 'vite-node/server'; import { getContextRegistry } from '../runtime/registry.js'; import { slash } from '../util/fs.js'; import { readStorySourceSha256 } from './catalog-cache.js'; import { formatThrown } from './errors.js'; import { finalizeCollectedStoryFile } from './finalize.js'; import { getCollectThreadCount } from './threads.js'; /** Owns one project's collection workers, transforms, ports and invalidations. */ export function useCollectStories(options, ctx) { const { server, mainServer } = options; const node = new ViteNodeServer(server, { deps: { inline: [ /histoire\/dist/, /histoire\/client/, /histoire\/network/, /@histoire\/[\w-]+\/dist/, /histoire-[\w-]+\/dist/, /@vue\/devtools-api/, // @TODO temporary fix for https://github.com/histoire-dev/histoire/issues/409 /vite\w*\/dist\/client\/(client|env).mjs/, ...ctx.config.viteNodeInlineDeps ?? [], new RegExp(path.resolve(getContextRegistry(ctx).tempDir, 'plugins').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), ], fallbackCJS: true, }, transformMode: ctx.config.viteNodeTransformMode, }); const threadsCount = getCollectThreadCount(ctx.mode, cpus().length, ctx.config.collectMaxThreads); console.log(pc.blue(`Using ${threadsCount} thread${threadsCount === 1 ? '' : 's'} for story collection`)); const threadPool = new Tinypool({ filename: new URL('./worker.js', import.meta.url).href, // WebContainer compatibility (Stackblitz) useAtomics: typeof process.versions.webcontainer !== 'string', minThreads: threadsCount, maxThreads: threadsCount, }); const ports = new Set(); let stopped = false; let destroying; let invalidationRevision = 0; let invalidateAll = false; const invalidatedFiles = new Set(); /** Clears Vite transforms for this collection server only. */ function clearCache() { server.moduleGraph.invalidateAll(); node.fetchCache.clear(); } /** Registers an RPC channel immediately so failure/close can release it. */ function createChannel() { const channel = new MessageChannel(); const port = channel.port2; const workerPort = channel.port1; ports.add(port); createBirpc({ fetchModule: id => node.fetchModule(id), resolveId: (id, importer) => node.resolveId(id, importer), }, { post: data => port.postMessage(data), on: data => port.on('message', data), }); return { port, workerPort, }; } /** Invalidates only this pool; removed when its owning collector stops. */ function invalidate(file) { if (!stopped) { file = slash(file); invalidationRevision++; // Every pool worker receives its own captured revision at task admission. // Parent-port messages alone can be delayed by Tinypool's idle Atomics.wait. if (!invalidateAll) { invalidatedFiles.add(file); if (invalidatedFiles.size > 4096) { invalidateAll = true; invalidatedFiles.clear(); } } threadPool.broadcastMessage({ kind: 'hst:invalidate', file, }); } } mainServer?.watcher.on('change', invalidate); /** Executes registered source and records success without trusting stale metadata. */ async function executeStoryFile(storyFile) { let port; try { const sourceSha256 = await readStorySourceSha256(ctx, storyFile); const channel = createChannel(); port = channel.port; const { workerPort } = channel; const payload = { root: server.config.root, base: server.config.base, storyFile, port: workerPort, invalidation: { revision: invalidationRevision, files: [...invalidatedFiles], all: invalidateAll }, }; const { storyData } = await threadPool.run(payload, { transferList: [ workerPort, ], }); if (storyData.length === 0) { console.warn(pc.yellow(`⚠️ No story found for ${storyFile.path}`)); delete storyFile.story; delete storyFile.treePath; delete storyFile.treeFile; return { status: 'empty', sourceSha256 }; } else if (storyData.length > 1) { console.warn(pc.yellow(`⚠️ Multiple stories not supported: ${storyFile.path}`)); } // Finalization mutates the collected data; the catalog cache keeps the raw copy. const story = structuredClone(storyData[0]); // Shared with the browser collection: the two collection modes must not // produce different story metadata for the same story file. finalizeCollectedStoryFile(storyFile, ctx, storyData[0]); return { status: 'collected', sourceSha256, story }; } catch (e) { delete storyFile.story; delete storyFile.treePath; delete storyFile.treeFile; console.error(pc.red(`Error while collecting story ${storyFile.path}:\n${e?.frame ? `${pc.bold(e.message)}\n${e.frame}` : formatThrown(e)}`)); if (options.throws) { throw e; } return { status: 'failed', error: e }; } finally { if (port) { ports.delete(port); port.close(); } } } /** Stops invalidations and releases RPC ports even when worker teardown fails. */ function destroy() { if (!destroying) { stopped = true; mainServer?.watcher.off('change', invalidate); destroying = (async () => { try { await threadPool.destroy(); } finally { for (const port of ports) port.close(); ports.clear(); } })(); } return destroying; } return { clearCache, executeStoryFile, destroy, }; }