histoire
Version:
A fast story book powered by Vite
108 lines (107 loc) • 5.17 kB
JavaScript
import { randomUUID } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { deserialize, serialize } from 'node:v8';
import fs from 'fs-extra';
import { join, relative } from 'pathe';
import { resolveConfigFile } from '../config/load.js';
import { isPathWithinRoot, readRegisteredText } from '../runtime/content/files.js';
import { hashContent } from '../runtime/content/hash.js';
import { captureInlineDocs, getInlineDocs } from '../runtime/content/inline.js';
import { getContextRegistry } from '../runtime/registry.js';
import { markGeneratedDir } from '../util/generated-dir.js';
import { getCollectionCacheFile, getProjectCacheDir } from '../util/temp-paths.js';
/** Bumped whenever the stored shape or the meaning of a stored outcome changes. */
const FORMAT = 1;
/**
* Fingerprint of a story file's registered source (module code of virtual
* stories), `undefined` when it can't be read.
*/
export async function readStorySourceSha256(ctx, storyFile) {
try {
return storyFile.virtual ? hashContent(storyFile.moduleCode ?? '') : (await readRegisteredText(ctx.root, storyFile.path)).sha256;
}
catch {
// Content availability does not change trusted collection policy.
// Unavailable source is diagnosed by the catalog projector.
return undefined;
}
}
/** Histoire's own version: collection code of another release may produce other metadata. */
async function readHistoireVersion() {
try {
// `src/node/collect` and `dist/node/collect` are both three levels below the package root.
return JSON.parse(await readFile(new URL('../../../package.json', import.meta.url), 'utf8')).version ?? '';
}
catch {
return '';
}
}
/**
* Cache of the dev story catalog in `.histoire/cache/collection`. It only
* spares the wait for a first collection: the dev server still collects every
* story again in the background and publishes any difference.
*/
export function createCollectionCache(ctx, file = getCollectionCacheFile(ctx.root)) {
const tempDir = getContextRegistry(ctx).tempDir;
let key;
/** Generated stories live in a per-run temp dir; match them by their path inside it. */
function getEntryId(storyFile) {
return isPathWithinRoot(tempDir, storyFile.path) ? `run:${relative(tempDir, storyFile.path)}` : storyFile.relativePath;
}
/** Config and Histoire release, as far as they can be read without running anything. */
function getKey() {
return key ??= (async () => {
const configFile = resolveConfigFile(ctx.root, ctx.configFile);
const config = configFile ? await readFile(configFile, 'utf8').catch(() => '') : '';
const plugins = ctx.config.plugins?.map(plugin => plugin.name) ?? [];
return hashContent(JSON.stringify([FORMAT, await readHistoireVersion(), config, plugins]));
})();
}
async function read(storyFiles) {
let data;
try {
data = deserialize(await readFile(file));
}
catch {
return undefined;
}
if (data?.key !== await getKey() || !Array.isArray(data.entries))
return undefined;
const entries = new Map(data.entries);
const outcomes = new Map();
for (const storyFile of storyFiles) {
const entry = entries.get(getEntryId(storyFile));
if (!entry || entry.sourceSha256 !== await readStorySourceSha256(ctx, storyFile))
return undefined;
outcomes.set(storyFile.path, { status: entry.status, sourceSha256: entry.sourceSha256, ...(entry.story ? { story: entry.story } : {}) });
}
for (const storyFile of storyFiles) {
const { inlineDocs } = entries.get(getEntryId(storyFile));
if (inlineDocs)
captureInlineDocs(ctx, storyFile.path, inlineDocs);
}
return outcomes;
}
async function write(storyFiles, outcomes) {
const entries = [];
for (const storyFile of storyFiles) {
const outcome = outcomes.get(storyFile.path);
if (!outcome?.sourceSha256)
continue;
const inlineDocs = getInlineDocs(ctx, storyFile.path, outcome.sourceSha256);
if (outcome.status === 'collected' && outcome.story)
entries.push([getEntryId(storyFile), { status: 'collected', sourceSha256: outcome.sourceSha256, story: outcome.story, ...(inlineDocs ? { inlineDocs: { ...inlineDocs } } : {}) }]);
else if (outcome.status === 'empty')
entries.push([getEntryId(storyFile), { status: 'empty', sourceSha256: outcome.sourceSha256 }]);
}
const data = { key: await getKey(), entries };
// Another dev server of the same project may read it at any time:
// publish the whole file at once.
const temp = join(file, '..', `.stories-${randomUUID()}.tmp`);
markGeneratedDir(getProjectCacheDir(ctx.root));
await fs.ensureDir(join(file, '..'));
await fs.writeFile(temp, serialize(data));
await fs.rename(temp, file);
}
return { read, write };
}