@anhur/core
v0.3.0
Published
Typed content from Markdown, MDX, YAML and JSON files: define collections, validate with Zod, import generated modules
Downloads
1,604
Maintainers
Readme
@anhur/core
❤️ The heart of Anhur.
It reads content files from your repo (Markdown, MDX, YAML, JSON), checks them against Zod schemas you write, and generates typed modules your app can import.
📦 Install
bun add @anhur/core zodThis also installs the anhur CLI. Run it from package scripts or with bunx anhur / npx anhur.
| Entry | For |
| -------------------- | --------------------------------------------------------------- |
| @anhur/core | anhur.config.ts: defineConfig, collections, views, schema |
| @anhur/core/build | Hosts and scripts: build, check, watch, createAnhur |
| @anhur/core/plugin | Writing plugins, loaders and custom fields |
Optional extras:
- MDX bodies →
@anhur/mdx - Markdown → HTML →
@anhur/markdown - Images and files (optional CDN sync) →
@anhur/assets - Full-text search →
@anhur/orama - Vite integration →
@anhur/vite
🚀 Example
// anhur.config.ts
import {
defineCollection,
defineConfig,
defineSingleton,
schema as s,
} from "@anhur/core";
const authors = defineCollection({
name: "authors",
directory: "content/authors",
include: "*.yml",
localized: false,
schema: s.object({ name: s.string() }),
});
const posts = defineCollection({
name: "posts",
directory: "content/posts",
include: "**/*.md",
schema: s.object({
title: s.string(),
slug: s.slug(),
publishedAt: s.isodate(),
author: s.reference("authors", { embed: true }),
excerpt: s.excerpt({ length: 160 }),
body: s.raw(),
}),
transform: (doc) => ({
...doc,
url: `/${doc._meta.locale}/posts/${doc.slug}`,
}),
});
const settings = defineSingleton({
name: "settings",
directory: "content/settings",
schema: s.object({ siteName: s.string() }),
});
export default defineConfig({
localization: {
strategy: "folder",
locales: ["en", "de"],
defaultLocale: "en",
},
content: [authors, posts, settings],
});content/
authors/ada.yml
posts/en/hello.md → id "hello", locale "en"
posts/de/hello.md → id "hello", locale "de"
settings/en/index.yml (localized singleton: one file per locale folder)
settings/de/index.ymlimport {
allPosts,
getPost,
getSettings,
locales,
type Post,
} from "anhur/generated";
allPosts.filter((post) => post._meta.locale === "en"); // light list (no body)
const post = await getPost({ locale: "de", slug: "hello" }); // full document or null
post?.author.name; // embedded reference
const settings = await getSettings({ locale: "en" });Point TypeScript at the output: "paths": { "anhur/generated": ["./.anhur/generated"] } in tsconfig.json. With @anhur/vite the import also resolves at runtime; without Vite, add the same alias to your bundler.
🧩 Schema helpers
schema is Zod (s.object, s.string, s.array, …) plus content fields:
| Helper | Value |
| ------------------------------ | -------------------------------------------------------------------------------------------------------- |
| s.raw() | the document body as a string ("" for YAML/JSON) |
| s.slug(opts) | the slug from the file, or derived from the id; validated, unique per locale |
| s.unique(opts) | a string that must be unique (scope: locale / collection / project) |
| s.reference("authors", opts) | id (or by: "slug") of another document; checked; embed: true inlines it |
| s.isodate({ output }) | ISO date string (datetime, UTC, or date); strict parsing |
| s.excerpt({ length }) | plain-text excerpt of the body |
| s.metadata() | { readingTime, wordCount } of the body (any script) |
| s.toc({ maxDepth }) | heading tree; markdown() / mdx() build it with the body's pipeline, so anchors match the heading ids |
Content fields also work inside .optional(), .default(), nested objects and arrays. Plain z.union of objects cannot hold content fields (use z.discriminatedUnion).
🔄 Build pipeline
- Files are found (
include/excludeglobs; hidden files andnode_modulesskipped; ids are NFC-normalized) and parsed (front matter must be YAML). - Content fields compile, then Zod validates. Every error in every file is reported, with its field path. Schemas must produce plain data (strings, numbers, booleans, arrays, objects,
Date,Map,Set) — aURLor class instance is reported with its field path. transform(doc, ctx)adds or reshapes fields.ctx.documents(otherSource)reads another source's validated documents;return ctx.skip("reason")drops a document.- Documents with
draft: trueat the top level of the file are dropped, even when the schema does not declaredraft(they are still validated). Drafts and skipped documents never cause duplicate-slug errors, and references to them fail. prepare(sources)may edit or remove the final documents.- References are checked and embedded, uniqueness is checked, views are derived, plugins generate extra modules. With scopes, this step and the next run again for each scope, on the documents it keeps.
- Output is written: only changed files (a file edited by hand is rewritten), atomically, with a lock against concurrent builds. Anhur only deletes files it created (tracked in
.anhur-manifest.json) and refuses to write into a folder it does not own. onSuccesshooks andcomplete(sources, { projectDir, outputDir })run.
Builds of one session (createAnhur, watch, the Vite plugin) run one at a time. The config file and every relative module it imports (also outside the project folder) are watched; installed packages and path aliases are not.
A failed build writes nothing; the previous output stays. Errors are AnhurBuildErrors with a list of diagnostics (code, message, file, fieldPath, hint).
⚡ Speed
Anhur is built for sites with thousands of files. A build does work only for what changed.
| Situation | What Anhur does |
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Rebuild in a session (dev server, watch) | One stat per file. An unchanged document is not read, compiled, checked, serialized or written again. |
| New session, files unchanged | Validated documents come from .anhur/cache/documents. Files are not read, parsed or compiled. |
| New session after a checkout | Files with new times are read once and compared by content. The next session does not read them. |
| New session after a config change | Documents are validated again. Compiled fields (Markdown, MDX, images) come from .anhur/cache/fields, unless their options hold functions (see below). |
| First build | Documents are compiled in worker threads when that is faster (see workers below). |
Numbers for your project: anhur build --timings prints the time of each stage, how many documents came from a cache, and which sources are not kept on disk and why. The same is in result.timings, result.reuse and result.notStored. A failed build has its stage times in error.timings.
Rules that make this safe:
Documents are frozen. Data from the schema, a transform or
preparecannot be changed later, also below a Zod.readonly().transformandprepareget their own copies; hooks, views and plugins get read-only documents and read-only lists of them ([...source.documents].sort(), notsource.documents.sort()). An unchanged document is the same object in every build of a session, so a plugin can compare by identity. That also holds when apreparehook or a transform runs again and gives the same data.transformruns again only when its document changed, or when a source it read throughctx.documents()changed. A transform that reads something else (a file, an environment variable, the network) setstransformCache: falseon the collection and runs on every build.A stored document is reused only when everything it was made from is the same:
- the file, and the files a field reported (
addDependency, assets): size, times and inode; - the config file and every module it imports that is not an installed package (relative paths, package
importssuch as#cms/notes, workspace packages,pathsaliases under Bun); - the lockfile, and the entry file of each installed package the config imports;
- the schema (shape, checks, defaults, the source of its functions), the loaders and the plugins.
- the file, and the files a field reported (
What Anhur cannot see: a schema that reads something else when it runs (the clock, an environment variable, the network) in a
.transform(),.refine()or default. SetdocumentCache: falseon that collection: it is then validated in every new session, in the main thread.A view, index or group is resolved again only when a document it is made from changed.
generate: { cache: false }resolves it on every build, for awhere,select, key function orcomparethat reads something else.A file is "unchanged" when its size, times and inode are the same. A file modified in the last seconds is compared by content instead, so two quick saves are never missed.
Compiled fields with functions in their options (
remarkPlugins,rehypePlugins,documentLink) compile again after every config change: a function is only known by its source.devandbuildhave their own cache folders, sovite devafteranhur buildis still a warm start.workersindefineConfig:true(default): when 128 or more documents with cached compiled fields wait, Anhur validates some in the main thread to learn what one costs. It starts 2 to 6 worker threads when the rest would take longer than about a second.- A number: start that many when 128 or more such documents wait, without measuring.
false: no workers.
Each worker loads the config file and the compilers itself and runs the
setuphook of every plugin, so workers trade memory for time. Useworkers: falsewhen a custom field or loader keeps state in memory that another part of the config reads (a list read by a plugin hook, a counter shared between documents), or when the config computes a value at load time that documents use through a function (a build id from the clock): each worker computes its own.cacheDir: falseturns the disk caches off.
⚙️ Generated exports
Per collection posts (type Post):
| Export | What |
| ------------------------------- | --------------------------------------------------------------------------------------------------------- |
| allPosts | list; light by default (generate.listOmit, default ["body"]) |
| getPost(idOrQuery) | async, lazy-loads one full document; null if missing. Localized: { locale, slug } or { locale, id } |
| Post, Posts, PostListItem | types |
| PostId, PostSlug | literal unions with generate.emitIds / emitSlugs |
Also: locales, defaultLocale, type Locale, and per singleton settings / getSettings() / settingsAll.
generate options: split (light default, full, list-only), listOmit, listSort: { by, order }, lookupBy, and export names (listName, getterName, typeName on the definition).
🔭 Views
| Helper | Emits | Best for |
| ------------- | ------------------------- | ------------------------------- |
| defineView | T[] | featured / top-N / merged feeds |
| defineIndex | Record<Key, T> | detail lookup by slug/sku |
| defineGroup | { key, count, items }[] | facet / SEO landing pages |
import { createDerivedHelpers } from "@anhur/core";
const content = [posts, products] as const;
const { defineView, defineIndex, defineGroup } = createDerivedHelpers(content);
const featured = defineView({
name: "featuredProducts",
from: products,
where: (doc) => doc.featured === true,
generate: { listSort: { by: "price" }, limit: 12 },
});
const bySku = defineIndex({ name: "productBySku", from: products, key: "sku" });
const byAuthor = defineGroup({
name: "postsByAuthor",
from: posts,
by: (doc) => doc.author.name,
});
export default defineConfig({ content, views: [featured, bySku, byAuthor] });Views run on the final documents (after transforms, references and prepare). createDerivedHelpers(content) types doc with embedded references resolved. Indexes and groups emit literal key unions (ProductBySkuKey).
🎯 Scopes
A scope is an extra output with only some of the documents: a public build without drafts, a build per audience. The main output keeps every document.
export default defineConfig({
content: [items, families],
scopes: [
{
name: "public",
outputDir: ".anhur/public",
where: {
// `doc` is typed for the source. References are still ids here.
items: (doc, ctx) => {
if (!doc.partOf) return doc.status !== "draft";
const parent = ctx
.documents(items)
.find((item) => item._meta.id === doc.partOf);
return parent?.status !== "draft";
},
},
},
],
});- Documents are loaded, validated, transformed and
prepared once. Each scope then picks its documents; references, uniqueness, views, plugin modules (such as the search index oforama()) and the written files are made again from what it keeps. - A source with no
whereentry keeps every document.ctx.documents(source)gives every document of a source before any scope picks, andctx.scopeis the scope name. - A kept document that points to a document the scope leaves out fails the build, as a reference to a draft does. A failing scope writes nothing: not the main output either.
- A callback that throws or returns something other than
trueorfalseis ascope-failederror on that document. - A singleton keeps the document its export always has (the only one, or the default locale's), unless it is
optional: true: dropping it is ascope-failederror. Other locales may be dropped; their getter then returnsnull. - Types: each scope writes its own
index.d.ts. Id, slug and index key unions name only the documents it keeps. Write a filter as a type predicate to narrow the scope's document types, lists and getters:items: (doc): doc is typeof doc & { status: "published" } => doc.status === "published". A plain boolean filter keeps the full type (correct, only wider), and so do views, indexes and groups.GetScopeTypeByName<typeof config, "public", "items">is the narrowed type. - Assets are shared. The asset plugin copies (and uploads) the files of every document into its one folder, also files that only documents a scope drops use. A scope's modules link only to the files of its own documents, but if a scope's deploy must not carry the others, deploy without the assets folder or keep those files out of the content.
- Anhur does not delete the folder of a scope you remove or move to another
outputDir. Delete it yourself, or it keeps the last files written there. - Each scope writes its own folder, separate from
outputDir,cacheDir, the assets folder and every other scope, and outside every content folder (only the main output folder is skipped when content is read). Import it from that folder (or with the Vite plugin,anhur/scopes/<name>). - Plugin
beforePublish/afterPublishhooks,onSuccessandcompleterun once per build, for the main output. BuildResult.scopeslists each scope's documents and files;writtenandremovedcount every output. The CLI prints one line per scope.
🖥️ CLI
anhur build # validate and write
anhur check # validate only, write nothing (CI)
anhur watch # rebuild on change; errors keep the last good output
anhur build --root site --config content/anhur.config.ts --json
anhur build --timings # time of each stage, and what came from a cacheExit code is 1 on errors; --json prints a machine-readable report with diagnostics.
🛠️ Programmatic API
import { build, check, createAnhur, watch } from "@anhur/core/build";
const result = await build({ rootDir: "site", mode: "build" });
result.documentCount;
result.written; // files that changed
result.timings; // [{ stage: "validate", ms: 412 }, …]
result.reuse; // { unchanged: 4998, compared: 0, validated: 2 }
result.notStored; // [{ source: "posts", reason: 'the field "views" (api) is not pure and has no cache' }]
const controller = await watch(
{ rootDir: "site" },
{
onBuild: (result) => console.log(result.documentCount),
onError: (error) => console.error(error.message),
},
);
await controller.close();createAnhur(options) keeps a session for repeated builds — what the Vite plugin uses. A session remembers the config, every validated document and what later stages made of it, so a rebuild only does work for changed files. Call close() when done.
🔌 Plugins
import { definePlugin } from "@anhur/core/plugin";
const sitemap = definePlugin({
name: "sitemap",
generate: (context) => {
const posts = context.sources.find((source) => source.name === "posts");
context.emitModule({
path: "sitemap.js",
code: `export const sitemapIds = ${JSON.stringify(posts?.documents.map((doc) => doc._meta.id) ?? [])};`,
exports: ["sitemapIds"], // re-exported from anhur/generated
dts: "export declare const sitemapIds: readonly string[];",
});
},
});Hooks: setup (validate options), loaders (new file types), generate (emit modules), beforePublish / afterPublish (side effects such as uploads). In a session, context.sources holds the same document objects for unchanged documents, so generate can skip work for a source whose documents are the same as last time. The lists are frozen: copy one before you sort it.
Custom fields use defineField(zodSchema, { kind, whenAbsent, compile, cache, pure, shares }) from @anhur/core/plugin:
| Option | Use |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| whenAbsent | "skip": leave a missing key to Zod. "compile": call compile with undefined (fields made from the body). |
| cache | { version, key }: keep the compiled value on disk. key(context) covers every option that changes the value. |
| pure | true when the value depends only on the input, the body, the document and what the field reports through its context. A field made with options passes { key: fingerprint(options) }: the engine knows compile by its source only. |
| shares | Keys of the values this field computes through context.share(key, compute), so another field of the document can use the same work (s.toc() reads the headings of the body m.body() compiles). Start a key with your plugin name. |
Documents of a source are restored from disk in the next session when every compiled field has pure or cache and the loader of the file is pure. A field without them (for example one that calls an API) runs in every new session, and so does every field of its source: result.notStored names it.
A custom loader sets pure: true when its result depends only on the text of the file:
defineConfig({
loaders: [
{
name: "toml",
test: /\.toml$/,
pure: true,
load: ({ raw }) => ({ data: parseToml(raw) }),
},
],
});A loader that reads anything else (a second file, git, the clock) leaves pure out.
License
MIT
