UNPKG

histoire

Version:

A fast story book powered by Vite

66 lines (65 loc) • 2.8 kB
import { CatalogContentChangedError } from '../content/files.js'; import { createRuntimeCatalog } from './publication.js'; /** One canonical provider per runtime generation, shared by attached adapters. */ const attachments = new WeakMap(); /** Context discovery seam for Vite virtual source modules created before handle attachment. */ const contexts = new WeakMap(); /** Connects generation-owned collection completion to atomic catalog/content publication. */ function createAttachment(runtime, options) { let disposed = false; const catalog = createRuntimeCatalog({ ...options, root: runtime.context.root, isActive: () => !disposed && runtime.isActive() }); /** Keeps readable last completion when watcher input overtakes collection bytes. */ async function publish(outcomes = runtime.collectionOutcomes) { try { await catalog.publish(runtime.context, outcomes); } catch (error) { if (!(error instanceof CatalogContentChangedError)) throw error; catalog.markUpdating(); } } const off = runtime.onCollection(async (event) => { if (disposed || !runtime.isActive()) return; // A restored catalog stays executable while it is collected again. if (event.phase === 'started' && !event.revalidate) catalog.markUpdating(); if (event.phase === 'completed') await publish(event.outcomes); if (event.phase === 'failed') { const outcomes = new Map(event.outcomes); for (const file of event.files.length ? event.files : runtime.context.storyFiles) outcomes.set(file.path, { status: 'failed', error: event.error }); await publish(outcomes); } }); const ready = runtime.ready.then(async () => { if (!catalog.current) await publish(); }); void ready.catch(() => { }); return { catalog, ready, /** Invalidates immediately; outstanding hashing cannot publish after disposal. */ close() { disposed = true; off(); contexts.delete(runtime.context); }, }; } /** Obtains canonical provider without duplicate collector observers or source readers. */ export function attachRuntimeCatalog(runtime, options) { let attachment = attachments.get(runtime); if (!attachment) { attachments.set(runtime, attachment = createAttachment(runtime, { ...options, epoch: runtime.epoch })); contexts.set(runtime.context, attachment); } return attachment; } /** Looks up shared generation publication without creating another provider or collector. */ export function getRuntimeCatalogForContext(context) { return contexts.get(context); }