Deferred work
A handler can't wait for a file or a fetch. It starts that work with ctx.defer(node, task) and the parse goes on:
const titles = {
name: 'titles',
parse: {
link: {
parse(node, ctx) {
return () =>
ctx.defer(node, async (node, ctx) => {
const page = await fetch(node.attrs.href).then((r) => r.text());
node.attrs.title = page.match(/<title>(.*?)<\/title>/)?.[1];
ctx.add('links', node.attrs.href);
});
}
}
}
};- The task gets a node and a
ctxof its own and changes the document through them. Its changes apply once it has finished and the parser is sure of the node. If the parser takes the node back, they are dropped. - The Vite plugin waits for deferred work before it renders the document, and so do
?dataand?textimports. Withcompile, usecompile_async. In dev it warns when a document has waited five seconds, naming the plugin and the document. - What a task adds compiles as if it were written. An image whose
srca task set is imported, and a fence it adds withsrc=shows its file, and the same goes for adocumenthook.
- A task changes its own node and what is inside it, and writes data for it. Anything else throws a
TypeError. So the result does not depend on which task finishes first.
Work that needs the whole document goes in a document hook. It runs once, after the parse and after every deferred task, and gets the root of the tree. It may be async:
const summary = {
name: 'summary',
parse: {
async document(root, ctx) {
let headings = 0;
for (let child = root.first_child; child !== null; child = child.next)
if (child.type === 'heading') headings++;
ctx.set('headings', headings);
}
}
};Hooks run in plugin order, each awaited before the next. One that returns a promise needs compile_async, as deferred work does.
Loading files
A plugin loads what it needs itself, and tells mdsvex what it read:
ctx.depend(path) names a file the output depends on, by its absolute path. When it changes, the Vite plugin compiles the document again, and its ?data and ?text imports, in dev and in a watch build, and it watches files outside the project root too.
compile returns them as dependencies for any other host to watch.
ctx.read(path) reads a file and depends on it. ctx.resolve(specifier) resolves a specifier as an import from the document would.
The Vite plugin supplies both. With compile_async, pass read and resolve options, mdsvex/compile reads no files itself.
ctx.cached(key, load) shares one load between documents: a bibliography read once for every page. A key that is a path is a dependency, and the Vite plugin drops it when that file changes, so a dev server never serves a stale copy.
ctx.defer(node, async (node, ctx) => {
const path = await ctx.resolve(ctx.frontmatter.bibliography);
const bib = await ctx.cached(path, (path) => ctx.read(path).then(parse_bib));
node.attrs.label = bib.get(node.text_content)?.short;
});