# `@hamur/content`

The first-party content module; the guide is [Content](/content). Add it to `modules`; it reads collections of Markdown, YAML and JSON files under `content/`, declared in `content.config.ts` at the app root, and the build writes each collection into the server bundle as JSON data.

```ts
// hamur.config.ts
import content from "@hamur/content"

export default defineConfig({
  modules: [content],
})
```

```ts
// content.config.ts
import { defineCollection, defineContentConfig } from "@hamur/content"
import * as v from "valibot"

export default defineContentConfig({
  collections: {
    blog: defineCollection({ type: "page", source: "blog/**/*.md", schema: v.object({ date: v.string() }) }),
    authors: defineCollection({ type: "data", source: "authors/*.yml", expose: false }),
  },
})
```

### `default`

The module, as `defineModule({ meta: { name: "content", configKey: "content", hooks: [...] } })`. Its setup imports `content.config.ts` (without it: `@hamur/content needs content.config.ts in <rootDir>`) and checks each collection: a name matches `[a-z][A-Za-z0-9]*` (`content.config.ts: collection name "my-blog" must match [a-z][A-Za-z0-9]*`), `type` is `"page"` or `"data"`, and exactly one of `source` and `loader` is set. Before the build it reads every collection; any error below fails the build. A collection's index, with a digest per entry, is written to `.hamur/content/<collection>.json`; the next build parses only the entries whose digest changed. Each collection becomes JSON chunks of `content.chunkSize` entries in the server bundle, imported together on the collection's first read in a process; a query of one collection imports no other collection's chunks. On a preset that puts the bundle in one module the chunks are in it, and the answer is the same. A collection reaches the client bundle only under `content.clientQuery: "local"`, and only when it is exposed.

The module adds `POST <baseURL>_hamur/content/query` (not on the `static` preset), the endpoint `queryCollection` uses in the browser under `content.clientQuery: "api"`; see `@hamur/content/query` below.

### `ContentOptions`

The `content` key of `hamur.config.ts`.

| Key           | Type                                       | Default                                     | Meaning                                                                                                                                                                                                                                                         |
| ------------- | ------------------------------------------ | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `clientQuery` | `"api" \| "local"`                         | `"api"`; `"local"` on the `static` preset   | how `queryCollection` runs in the browser: `"api"` posts the query to `/_hamur/content/query`, `"local"` downloads the collection's chunk once and runs the same engine there                                                                                   |
| `chunkSize`   | `number`                                   | `1000`                                      | entries per chunk of a collection in the server bundle, a positive integer; `hamur dev` and the client's `"local"` chunk keep one piece per collection                                                                                                          |
| `csv`         | `{ delimiter?: string; header?: boolean }` | `{ delimiter: ",", header: true }`          | how `.csv` files are read: RFC 4180 with quoted fields, doubled quotes, line breaks in quotes and CRLF or LF; every value is a string. `delimiter` is one character other than a quote or a line break; with `header: false` the columns are `"0"`, `"1"`, …    |
| `search`      | `{ collections: string[] } \| false`       | `false`                                     | the page collections that get a search index at build, for `useSearchCollection`; each must be exposed                                                                                                                                                          |
| `prerender`   | `boolean`                                  | `true` on the `static` preset, else `false` | adds the `path` of every page entry of every page collection, drafts left out, to the prerender routes, so `hamur generate` writes each page; see `useContentPage`                                                                                              |
| `raw`         | `boolean \| "body"`                        | `false`                                     | answers `GET <path>.md` of every page entry, `content-type: text/markdown; charset=utf-8`, with its source file (`true`) or the `body` its loader gave (`"body"`); `useContentPage` adds a `link` with `rel="alternate"` and `type="text/markdown"` to the head |
| `llms`        | `LlmsOptions`                              | none                                        | writes `/llms.txt` and `/llms-full.txt` from page collections                                                                                                                                                                                                   |
| `api`         | `{ rest?: boolean; graphql?: boolean }`    | `{ rest: false, graphql: false }`           | `rest` serves `GET <baseURL>api/_content/<collection>` for every exposed collection, listed in `/_hamur/openapi.json` when `server.openapi` is on; see below. `graphql` adds the collections to the app's GraphQL schema when `server.graphql` is on; see below |

`raw` and `llms` write public files at build, so every preset serves them and the `static` preset's output holds them (not in `hamur dev`). A page's file is `<path>.md`, `/` is `/index.md`. The bytes are the source file on disk (`true`) or the loader's `body` (`"body"`), frontmatter included; transformers and `content:file:*` hooks do not change them. A `raw` that is neither fails with `content.raw must be a boolean or "body" (got "yes")`.

A `chunkSize` that is not a positive integer fails the build with `content.chunkSize must be a positive integer (got 0)`.

A value other than `"api"` or `"local"` fails the build with `content.clientQuery must be "api" or "local" (got "sql")`, and `"api"` on the `static` preset with `content.clientQuery "api" needs a server; the static preset uses "local"`.

A `prerender` that is not a boolean fails with `content.prerender must be a boolean (got "yes")`.

`content.api` that is not an object fails with `content.api must be { rest?: boolean, graphql?: boolean } (got true)`, another key with `content.api has no key "openapi"; it takes rest and graphql`, a non-boolean with `content.api.rest must be a boolean (got "yes")`, and `rest` on the `static` preset with `content.api.rest needs a server; the static preset serves no route`. `graphql: true` with `server.graphql` off fails with `content.api.graphql needs server.graphql on`.

A `search` that is not `false` or `{ collections: string[] }` fails with `content.search must be false or { collections: string[] }`; a name that is no collection with `content.search.collections[0] "nope" is not a collection of content.config.ts`; an `expose: false` collection with `content.search.collections[0] "authors" is not exposed to the client (expose: false); the search index is served to the browser`; a data collection with `content.search.collections[0] "authors" is not a page collection; only pages have sections`.

### `LlmsOptions`

`content.llms`: `{ title, description?, sections: Array<{ title, collection, where? }> }`. `/llms.txt` is the llmstxt.org file: `# title`, `> description`, then per section `## title` and `- [entry title](URL): entry description`, with each URL made of `site.url`, `app.baseURL` and the entry's `path`. `where` is a `QueryCondition` or an array of them joined by `AND`; without it a section lists every page of its collection, drafts left out. `/llms-full.txt` is the source of every listed page, joined by a line `---`.

Without `site.url` the build fails with `content.llms needs site.url for absolute page URLs`; a `collection` that is no collection fails with `content.llms.sections[0].collection "nope" is not a collection of content.config.ts`, a data collection with `content.llms.sections[0].collection "authors" is not a page collection`.

### `defineContentConfig`

`defineContentConfig({ collections })` returns its argument, typed as `ContentConfig`, keeping each collection's own type so typegen can read its schema (`HamurContentCollections`). It is the default export of `content.config.ts`.

### `defineTransformer`

`defineTransformer({ name, extensions, parse?, transform? })` returns its argument, typed as `Transformer`. List the transformers in `defineContentConfig({ transformers: [adoc] })`; they are code, so they are not a key of `hamur.config.ts`.

```ts
const txt = defineTransformer({
  name: "txt",
  extensions: [".txt"],
  parse: ({ body }) => ({ title: body.split("\n")[0] }),
  transform: (entry) => (entry.extension === "txt" ? { ...entry, kind: "note" } : entry),
})
```

`parse(file)` reads a file of one of `extensions` into the entry's fields, so a `source` or `glob()` that matches `content/notes/a.txt` makes it an entry (an extension no transformer parses still fails). In a page collection a string `body` field of the result is the Markdown the page parses. `transform(entry)` runs on every freshly parsed entry of every collection after the schema, in list order, and returns the entry. Errors:

| Message                                                                                                           | Cause                                                                       |
| ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `content.config.ts: transformers must be an array of defineTransformer({ … })`                                    | `transformers` is not an array                                              |
| `content.config.ts: transformers[0]: name must be a non-empty string`                                             | no name                                                                     |
| `content.config.ts: transformers[1]: name "adoc" is listed twice`                                                 | two with one name                                                           |
| `content.config.ts: transformers[0] "adoc": extensions must be an array of extensions with a dot, like [".adoc"]` | `extensions` is not `[".adoc"]`-shaped                                      |
| `content.config.ts: transformers[0] "adoc": parse must be a function`                                             | `parse` or `transform` is not a function                                    |
| `content.config.ts: transformers[0] "adoc": .md is a built-in content format`                                     | `parse` claims `.md`, `.yml`, `.yaml`, `.json`, `.json5`, `.toml` or `.csv` |
| `content.config.ts: transformers[1] "b": .adoc is already parsed by transformer "adoc"`                           | two `parse` for one extension                                               |
| `content/notes/a.txt: transformer "txt" failed: <message>`                                                        | `parse` or `transform` threw                                                |
| `content/notes/a.txt: transformer "txt" must return an object from parse`                                         | not an object (`from transform` likewise)                                   |

### `Transformer`

| Key          | Type                                                             | Meaning                                                                                         |
| ------------ | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `name`       | `string`                                                         | unique in the list; named by errors and part of the content index's key                         |
| `extensions` | `string[]`                                                       | extensions with a dot, `[".adoc"]`; with `parse`, they are read from every collection's sources |
| `parse`      | `(file: ContentFile) => Record<string, unknown> \| Promise<…>`   | optional; the file's entry fields                                                               |
| `transform`  | `(entry: ContentEntry) => Record<string, unknown> \| Promise<…>` | optional; the entry, reshaped                                                                   |

### `ContentFile`

`{ id, path, extension, body }`: the entry id the file gives, its path from the root (`content/notes/a.txt`), the extension without the dot and the file's text.

### Hooks

`meta.hooks` declares two build hooks, typed in `HamurHooks` when the module is installed, for a `hooks` key in `hamur.config.ts` or another module.

| Hook                       | Arguments                                                        | When                                                                                                                                                                                                             |
| -------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `content:file:beforeParse` | `{ file: ContentFile, collection: string }`                      | after a `source`, `glob()` or `file()` file is read, before it is parsed; assign `file.body` to change what is parsed (a non-string fails with `<file>: content:file:beforeParse must leave file.body a string`) |
| `content:file:afterParse`  | `{ file: ContentFile, entry: ContentEntry, collection: string }` | after the schema and the transformers; change `entry` in place, the result must still be JSON. `file.body` is the Markdown source of a page entry, `""` otherwise                                                |

A throwing hook fails the build with `content/a.md: content:file:afterParse failed: <message>`. Hooks run for the entries parsed in this build; the content index keeps an entry whose file text is unchanged with what the hooks gave it. The index is keyed on the transformers (name, extensions and the source text of `parse` and `transform`) and on which hooks are registered, so changing either drops it; the code of a hook, and what a transformer imports, cannot be hashed, so changing those needs `.hamur/content/` deleted or the file touched.

### `defineCollection`

`defineCollection(collection)` returns its argument, typed as `CollectionDefinition`.

### `defineLiveCollection`

`defineLiveCollection({ loader, schema? })` declares a **live collection** in `content.config.ts`: its entries are fetched at request time by the app's own loader, validated by `schema` (a Standard Schema), and never written into the content index. Read it from a handler with `getLiveCollection` and `getLiveEntry` of `@hamur/content/server`.

```ts
import { defineContentConfig, defineLiveCollection } from "@hamur/content"
import { $fetch } from "hamur/server"

export default defineContentConfig({
  collections: {
    posts: defineLiveCollection({
      loader: {
        name: "cms",
        async loadCollection(filter?: { tag?: string }) {
          const items = (await $fetch("https://cms.example.com/posts", { query: filter })) as Array<{
            id: string
            title: string
          }>
          return {
            entries: items.map((item) => ({ id: item.id, data: item })),
            cacheHint: { tags: ["posts"], maxAge: 300 },
          }
        },
        async loadEntry(filter: { id: string }) {
          const item = (await $fetch(`https://cms.example.com/posts/${filter.id}`)) as {
            id: string
            title: string
          } | null
          return item ? { id: item.id, data: item } : undefined
        },
      },
    }),
  },
})
```

The server bundle imports `content.config.ts` itself when it defines a live collection, so the loaders run in the server; there, `@hamur/content` resolves to its definers, and `glob`, `file` and `fromComponent` are inert stand-ins with no Node import, so the file bundles for Workers too. A live `schema` from `fromComponent` fails the build: `content.config.ts: live collection "posts": fromComponent is build-time only; pass the component's propsSchema itself`. A loader that is not `{ name?, loadCollection, loadEntry }` fails the build with `content.config.ts: live collection "posts": loader must be { name?: string, loadCollection(filter), loadEntry(filter) }`, a `schema` that is no Standard Schema with `content.config.ts: live collection "posts": schema must be a Standard Schema`.

### `LiveCollectionDefinition`, `LiveLoader`, `LiveLoaderEntry`

`LiveCollectionDefinition` is what `defineLiveCollection` returns: `{ live: true, loader, schema? }`. `LiveLoader` is `{ name?, loadCollection(filter), loadEntry(filter) }`: `loadCollection` returns `{ entries: LiveLoaderEntry[], cacheHint? }`, `loadEntry` one `LiveLoaderEntry` or `undefined`, each may be async. A `LiveLoaderEntry` is `{ id: string, data: object, body?: string | MdRoot, cacheHint?: CacheHint }`; a string `body` is Markdown.

### `CacheHint`

`{ tags?: string[], maxAge?: number, lastModified?: Date }`. With `maxAge` (seconds), a result is kept in the `cache` storage mount that long; `tags` and `lastModified` are passed through for the handler to use (for example as `cacheTag` tags or a `last-modified` header).

### `fromComponent`

`fromComponent<M>(path: string): PropsSchemaOf<M>` makes a component's props the schema of a collection: `defineCollection({ type: "data", source: "heroes/*.yml", schema: fromComponent<typeof import("./app/components/Hero.tsx")>("#app/components/Hero") })`. When `content.config.ts` loads, the build imports the component and uses its `propsSchema` export (a Standard Schema), so each entry is validated as the component's props: `content/heroes/bad.yml: title: Expected string`. Props are not read from each library's type information.

A `Hero.ts`, `Hero.tsx`, `Hero.js`, `Hero.jsx` or `Hero.mjs` exports `propsSchema` beside the component. A `.vue` or `.svelte` component cannot be imported without its compiler, so its schema lives in the sibling `Hero.props.ts` (or `.props.js`), which wins over `Hero.tsx` when both exist. A `#…` path resolves through the app's `package.json` `imports`. Errors:

| Message                                                                                                                     | Cause                                           |
| --------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------- |
| `fromComponent: #app/components/Hero exports no propsSchema`                                                                | the module has no `propsSchema` Standard Schema |
| `fromComponent: #app/components/Hero.vue is not importable at build; export propsSchema from #app/components/Hero.props.ts` | a `.vue` or `.svelte` file with no `.props.ts`  |
| `fromComponent: #app/components/Nope not found`                                                                             | no file matches                                 |

### `image`

`image(): StandardSchemaV1<unknown, ContentImage>` is the schema of an image field: `defineCollection({ type: "page", source: "blog/*.md", schema: z.object({ cover: image() }) })`. A relative path in frontmatter or data, resolved against the entry's file, becomes the image written to the output with its size read from the file header. The path is relative (`./a.png`, `../img/a.png`, `a.png`); a URL or a path starting with `/` fails with `content/blog/x.md: cover: https://example.com/a.png is not a relative path; image() reads files next to the entry`, a missing file with `content/blog/x.md: cover: ./a.png not found`. `src` is `<app.baseURL><app.buildAssetsDir>content-images/<name>-<8 hex>.<ext>`, immutable. The output is an `ImageMeta`, so `getImage(entry.cover)` and `<Img src={entry.cover}>` of `@hamur/image` accept it. Outside the build (on the server of a live collection) `image()` fails with `image() runs at build only`.

### `ContentImage`

`{ src: string; width: number; height: number; format: string }`: the output of `image()`.

### `PropsSchemaOf`

`PropsSchemaOf<M>` is the type of `M`'s `propsSchema` export, `StandardSchemaV1` when `M` has none. It is `fromComponent`'s return type, so the collection's item type, and with it `queryCollection`, follows the schema's output.

### `ContentConfig`

| Key            | Type                                   | Meaning                           |
| -------------- | -------------------------------------- | --------------------------------- |
| `collections`  | `Record<string, CollectionDefinition>` | the collections by name           |
| `transformers` | `Transformer[]`                        | optional; see `defineTransformer` |

### `CollectionDefinition`

| Key      | Type                       | Default                              | Meaning                                                                                                                                                         |
| -------- | -------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `type`   | `"page" \| "data"`         | —                                    | pages (a `path` and a Markdown `body`) or data                                                                                                                  |
| `source` | `CollectionSource`         | —                                    | the files of the collection; set this or `loader`                                                                                                               |
| `loader` | `ContentLoader`            | —                                    | a loader that fills the collection; set this or `source`                                                                                                        |
| `schema` | `StandardSchemaV1`         | none: every field is kept as written | validates each entry's frontmatter or data at build; its output replaces it                                                                                     |
| `expose` | `boolean`                  | `true`                               | `false` keeps the collection server-only: no client chunk, refused by `/_hamur/content/query`, and `queryCollection` in the browser throws; the server reads it |
| `order`  | `[field, "ASC" \| "DESC"]` | the source order                     | the collection's default order; stored with the collection, the entries stay in source order                                                                    |

A schema failure fails the build with the file below the root, the issue's path joined by `.` and its message: `content/blog/a.md: date: Expected string`. The output must be JSON: a `Date` is stored as its ISO string, and a function, a `Map` or another class instance fails (`content/blog/a.md: date: a schema output must be JSON (got function)`).

### `CollectionSource`

`string | SourceOptions | RemoteSourceOptions | Array<string | SourceOptions | RemoteSourceOptions>`. A string is `{ include: string }`. Each source's files come in source order, the sources in the order given, and a file matched twice is read once.

### `SourceOptions`

| Key       | Type       | Default | Meaning                                        |
| --------- | ---------- | ------- | ---------------------------------------------- |
| `include` | `string`   | —       | a glob (`Bun.Glob`) relative to `cwd`          |
| `exclude` | `string[]` | `[]`    | globs relative to `cwd` left out               |
| `prefix`  | `string`   | `"/"`   | the path prefix of a page collection's entries |
| `cwd`     | `string`   | `""`    | a directory relative to `<rootDir>/content`    |

The files read are `.md` (frontmatter and body), `.yml`, `.yaml` (`Bun.YAML`), `.json`, `.json5` (`Bun.JSON5`), `.toml` (`Bun.TOML`) and `.csv` (a Hamur parser, see `ContentOptions`); any other extension a glob matches fails (`content/blog/a.txt: .txt is not a content format (md, yml, yaml, json, json5, toml, csv)`). A file is one entry; an array file (YAML, JSON, JSON5) or a `.csv`, whose rows are objects, gives one entry per item in a data collection, with ids `<stem>/<index>`, and fails in a page collection. A parse error is `content/data/a.csv:3:14: unterminated quoted field`: file, line, column, message.

**Source order** compares paths segment by segment: a segment with a number prefix (`1.hello.md`) comes before one without, prefixes compare as numbers (`2.b` before `10.a`), then names in code-point order.

**Path** of a page: `prefix` and the file's path below `cwd`, each segment without its number prefix, the extension dropped and a last `index` segment dropped: `content/blog/1.hello.md` is `/blog/hello` and `content/blog/index.md` is `/blog`. A frontmatter `path` that starts with `/` replaces it. Two entries of one collection with one path fail: `content: content/blog/1.hello.md and content/blog/hello.md both have path /blog/hello`.

**Drafts**: a page whose frontmatter has `draft: true` stays in `hamur dev` and is left out of every build, which logs `[content] blog: 2 drafts left out`.

### `RemoteSourceOptions`

A source in a GitHub or GitLab repository, downloaded as a tarball at build:

```ts
docs: defineCollection({ type: "page", source: { repository: "https://github.com/org/docs", branch: "main", include: "docs/**/*.md", auth: { token: process.env.DOCS_TOKEN! } } }),
```

| Key                            | Type                | Default            | Meaning                                                                                                                 |
| ------------------------------ | ------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------- |
| `repository`                   | `string`            | —                  | `https://github.com/<org>/<repo>` or `https://gitlab.com/<group>/<project>`; only `https:` on those two hosts           |
| `branch`, `tag`                | `string`            | the default branch | the ref to download; set one, not both                                                                                  |
| `include`, `exclude`, `prefix` |                     |                    | as in `SourceOptions`, relative to the repository's root                                                                |
| `auth`                         | `{ token: string }` | none               | sent as `Authorization: Bearer` (GitHub) or `PRIVATE-TOKEN` (GitLab), never in a URL, a log, an error or the cache path |

The files are unpacked with `Bun.Archive` below `<cacheDir>/content/<sha256 of repository and ref>/` and read by the same loader as local files. Each build downloads again; when the fetch throws or answers 5xx or 429, the build reads the cached copy and logs `[content] using the cached copy of https://github.com/org/docs`. Errors: `content: cannot fetch https://github.com/org/docs (404)` for any other failed status, `content: cannot fetch https://github.com/org/docs and no cached copy exists (<reason>)`, `content: https://gitea.example/x is not a GitHub or GitLab repository URL`, `content: https://github.com/org/docs: archive entry "../x.md" leaves the repository` (an entry with `..` or an absolute path), `content: cannot fetch https://github.com/org/docs (the archive is larger than 104857600 bytes)`, and `content: cannot read the archive of https://github.com/org/docs (larger than 524288000 bytes unpacked)` (500 MB unpacked). `hamur dev` does not watch a remote source.

### `DataEntry`

An entry of a data collection: `collection` (the collection's name, set by the build), `id` (the stem, or `<stem>/<index>` for an item of a JSON or YAML array file), `stem` (the path below `cwd` without its extension, number prefixes kept: `blog/1.hello`), `extension` (`"yml"`), and the fields of the file, through the schema. A `.md` file gives its frontmatter and drops its body.

A field named `collection`, `id`, `stem`, `extension`, `body`, `excerpt`, `headings` or `toc` fails: `content/blog/a.md: frontmatter field "body" is reserved`.

### `PageEntry`

A `DataEntry` with the page fields:

| Field                                       | Type                                                   | From                                                                                                                       |
| ------------------------------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| `path`                                      | `string`                                               | the path rule above                                                                                                        |
| `title`, `description`                      | `string \| undefined`                                  | frontmatter, else the first `h1` and the first paragraph                                                                   |
| `seo`                                       | `{ title?, description?, … }`                          | `title` and `description`, with frontmatter `seo` over them                                                                |
| `navigation`                                | `boolean \| { title?, icon? }`                         | frontmatter `navigation`, default `true`                                                                                   |
| `draft`                                     | `boolean`                                              | frontmatter `draft`, default `false`                                                                                       |
| `navigationDirs`                            | `Record<string, Record<string, unknown>> \| undefined` | the `.navigation.yml` data of the directories above the page, by directory stem; only a page below such a directory has it |
| `body`                                      | `MdRoot`                                               | the Markdown AST of `hamur/markdown`                                                                                       |
| `excerpt`, `headings`, `toc`, `readingTime` |                                                        | the parsed document                                                                                                        |

A page collection also reads a `.yml`, `.yaml`, `.json`, `.json5` or `.toml` file holding one object (its fields are the frontmatter of an empty body); an array file fails with `content/blog/list.yml: a page collection entry is one document; move the file to a data collection`. The `markdown` config key applies to every page except its `remarkPlugins` and `rehypePlugins`, which run on Markdown pages and `.md` imports only.

### `glob`

`glob({ pattern, base?, exclude?, prefix? })` returns the loader a `source` stands for: it reads the `.md`, `.yml`, `.yaml`, `.json`, `.json5`, `.toml` and `.csv` files matching `pattern` (`Bun.Glob`) below `base`, a directory relative to `<rootDir>/content`. `exclude` and `prefix` are those of `SourceOptions`. Entries, ids, paths and errors are the ones described under `SourceOptions`.

### `GlobOptions`

The argument of `glob`: `{ pattern: string; base?: string; exclude?: string[]; prefix?: string }`.

### `file`

`file(path)` returns a loader for one `.json`, `.json5`, `.yml`, `.yaml`, `.toml` or `.csv` file, `path` relative to `<rootDir>/content`. An array (a `.csv` is always one) gives one entry per item, whose id is its string `id` field, else its index; an object gives one entry per key. Each item is an object. A missing file fails with `content/people.json: file not found`.

```ts
authors: defineCollection({ type: "data", loader: file("authors.json"), schema: v.object({ name: v.string() }) }),
```

### `ContentLoader`

`{ name: string; load(ctx: LoaderContext): Promise<void> }`. A loader runs at build and at the start of `hamur dev`, never while the app serves requests. `name` appears in errors: a schema failure of one of its entries is `content: loader "cms", entry "x": date: Expected string`, and any other error its `load` throws is `content: loader "cms" failed: <message>`.

```ts
const cms: ContentLoader = {
  name: "cms",
  async load({ store, parseData, digest }) {
    const posts = (await (await fetch("https://cms.example/posts")).json()) as Array<{
      id: string
      etag: string
      title: string
    }>
    for (const { id, etag, ...data } of posts)
      store.set({ id, data: await parseData({ id, data }), digest: digest(etag) })
  },
}
```

### `LoaderContext`

| Key                                | Meaning                                                                                                              |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `collection`, `type`, `rootDir`    | the collection's name and type, and the app root                                                                     |
| `store`                            | `set(entry: LoaderEntry)` (an entry with the same `id` is replaced), `delete(id)`, `keys()`, `clear()`               |
| `meta`                             | `get(key)` and `set(key, value)`: strings kept for the collection between builds, in the index                       |
| `parseData({ id, data, file? })`   | validates `data` through the collection's schema and returns the output, or throws the loader's schema failure above |
| `parseMarkdown(source, { file? })` | `parseMarkdown` of `hamur/markdown` with the `markdown` key and `site.url`                                           |
| `digest(value)`                    | a hash string of a string or bytes                                                                                   |
| `csv`                              | `{ delimiter, header }`: `content.csv` with its defaults                                                             |
| `logger`                           | the `content` build logger                                                                                           |

### `LoaderEntry`

What `store.set` takes: `{ id, data, body?, file?, digest?, stem?, path?, navigationDirs? }`. `data` is validated through the schema unless it is what `parseData` returned. `body` is Markdown source with its frontmatter, which a page collection parses into the page fields; a page without one has an empty body. `file` is an absolute path whose extension is the entry's `extension` and which errors name; without it the entry's `extension` is `""`. `stem` defaults to `id`, and `path` of a page to `/<id>` (frontmatter `path` replaces it). An entry whose `digest` equals the one under the same `id` in the last build is not parsed again: its index entry is reused. `navigationDirs` is the `.navigation.yml` data of the directories above a page by directory stem, which the `glob` loader sets; it becomes the entry's `navigationDirs`.

### `ContentEntry`

`PageEntry | DataEntry`.

### `DataFields`, `PageFields`

`DataFields` is the four fields every entry has (`collection`, `id`, `stem`, `extension`); `PageFields` adds the page fields of `PageEntry`. `DataEntry` and `PageEntry` are these with an index signature (`[field: string]: unknown`), which an untyped entry needs; the typed item of a collection is built on the two without it, so its field names are the collection's own.

### `HamurContentCollections`

An empty interface that typegen fills in `.hamur/types/content.d.ts`, one item type per collection of `content.config.ts`:

```ts
declare module "@hamur/content" {
  interface HamurContentCollections {
    blog: CollectionItemOf<(typeof config)["collections"]["blog"]>
  }
}
```

With it filled, `queryCollection`, `queryCollectionNavigation`, `queryCollectionItemSurroundings` and `queryCollectionSearchSections` take only these collection names, and `where`, `andWhere`, `orWhere`, `order` and `select` take only the item's field names. A dotted path (`"author.name"`) is checked by its first segment only: `author` must be a field, whatever follows is `string`. Without it (before the first `hamur typegen`, or an app without `content.config.ts` types) every name is a `string`, every field a `string`, and the item is `ContentEntry`.

Typegen also writes, for each collection whose schema has a JSON Schema (`~standard.jsonSchema`, the schema's input in draft 2020-12), `.hamur/content/schemas/<collection>.schema.json`, and `.hamur/content/schemas.json`, which maps each schema file (from the root) to the globs of its collection's sources (`content/<cwd>/<include>`), the shape of an editor's `yaml.schemas`. A collection with a loader has a schema file and no globs. A schema without JSON Schema gets no file and one warning, `[content] blog: schema has no JSON Schema; no editor schema written`.

### `HamurLiveCollections`

An empty interface that typegen fills in `.hamur/types/content.d.ts`, one entry per live collection, its definition's type: `posts: (typeof config)["collections"]["posts"]`. With it filled, `getLiveCollection` and `getLiveEntry` take only these names, their filters are the parameter types of `loadCollection` and `loadEntry`, and the entries' `data` is the schema's output (else the loader's `data`) with every `Date` written as `string`. Live collections are not in `HamurContentCollections`, so `queryCollection` does not take them.

### `LiveCollectionName`, `LiveCollectionItem`, `LiveCollectionFilter`, `LiveEntryFilter`

`LiveCollectionName` is the union of the names in `HamurLiveCollections`, `string` while it is empty. `LiveCollectionItem<"posts">` is the `data` type of its entries, `Record<string, unknown>` while it is empty. `LiveCollectionFilter<"posts">` and `LiveEntryFilter<"posts">` are the parameter types of `loadCollection` and `loadEntry`.

### `LiveCollectionItemOf`

`LiveCollectionItemOf<Definition>` is the `data` type of a live collection definition's entries: `Serialized<StandardSchemaV1.InferOutput<schema>>`, or `Serialized` of the loader's `data` without a schema.

### `CollectionName`, `CollectionItem`, `CollectionField`

`CollectionName` is the union of the names in `HamurContentCollections`, `string` while it is empty. `CollectionItem<"blog">` is the item type of that collection, `ContentEntry` while it is empty. `CollectionField<"blog">` is `keyof CollectionItem<"blog">` as strings; a schema whose output has an open index signature (`Record<string, unknown>`) makes it `string`.

### `CollectionItemOf`, `Serialized`

`CollectionItemOf<Definition>` is the item type typegen writes: `PageFields` (page) or `DataFields` (data) and `Serialized<StandardSchemaV1.InferOutput<schema>>`, or `Record<string, unknown>` without a schema. `Serialized<T>` is `T` with every `Date` written as `string`, as the index stores it.

## `@hamur/content/query`

`queryCollection` for pages, `load` functions and any code that runs on both sides. It imports no Node or Bun API and not the store, so it is safe in the browser; the root `@hamur/content` is the module and imports the build.

### `queryCollection`

`queryCollection(name)` returns a `CollectionQueryBuilder` over one collection; `name` is one of `CollectionName`. `queryCollection<{ title: string }>(name)` types the entry yourself, with every field a `string`. On the server it reads the collection in process, `expose: false` collections included. In the browser it posts the query to the endpoint (`content.clientQuery: "api"`) or downloads the collection's chunk once and runs the same engine (`"local"`).

```ts
import { queryCollection } from "@hamur/content/query"

const posts = await queryCollection("blog")
  .where("date", ">", "2026-01-01")
  .andWhere((q) => q.where("draft", "=", false).orWhere("tags", "IN", ["news"]))
  .select("title", "path", "date")
  .order("date", "DESC")
  .limit(10)
  .all()
```

In the browser, a collection with `expose: false` throws at the call: `queryCollection("authors"): the collection is not exposed to the client (expose: false)`, and a name that is no collection throws `queryCollection: unknown collection "nope"`.

### `queryCollectionNavigation`

`queryCollectionNavigation(name, extraFields?)` returns the page collection's `NavigationItem[]`, a tree by directory. It runs one `select` query, so it works on the server, under `"api"` and under `"local"`, and an `expose: false` collection throws in the browser as `queryCollection` does.

```ts
import { queryCollectionNavigation } from "@hamur/content/query"

const tree = await queryCollectionNavigation("docs", ["description"])
```

A directory is an item with `children`. Its title is, first found: `title` in the directory's `.navigation.yml`, `navigation.title` of its `index` page, the `index` page's title, the directory name without its number prefix with `-` as spaces and the first letter upper case. Its `icon` is the `.navigation.yml` `icon`, else the `index` page's `navigation.icon`; its `path` is the `index` page's, else the directory's. A directory with an `index` page and nothing else is a leaf; one with neither is left out. Siblings sort by number prefix (numerically, before none), then name; a numeric `order` in `.navigation.yml` stands in for the directory's prefix. A page whose frontmatter has `navigation: false` is left out, and an `index` page with it hides its whole directory; `navigation: { title, icon }` renames a page. The `index` of the collection's top directory is the first item.

`extraFields` names fields of the collection's entries to copy onto each item (a directory takes them from its `index` page, then from its `.navigation.yml`); each is checked as in a `select`, so it must be a field some entry has. A page without the field has no key. An extra field named `title`, `path`, `stem`, `icon` or `children` is ignored.

### `NavigationItem`

`{ title: string; path: string; stem: string; icon?: string; children?: NavigationItem[]; [field: string]: unknown }`.

### `queryCollectionItemSurroundings`

`queryCollectionItemSurroundings(name, path, { before?, after?, fields? })` returns `[...previous, ...next]` around the page with that `path`, in the collection's order (its `order`, else source order, which honours number prefixes). `before` and `after` default to 1 and are non-negative integers; the result has `before + after` items, `null` where the collection ends or the path is unknown. Each item is `{ id, path, ...fields }`.

```ts
import { queryCollectionItemSurroundings } from "@hamur/content/query"

const [previous, next] = await queryCollectionItemSurroundings("docs", "/docs/guide/config", { fields: ["title"] })
```

### `SurroundingsOptions`

`{ before?: number; after?: number; fields?: string[] }`.

### `findPageHeadline`, `findPageBreadcrumb`, `findPageChildren`, `findPageSiblings`

Pure functions over the tree `queryCollectionNavigation` returns, each by an item's `path`; they also come from `@hamur/content/server`.

| Function                         | Returns                                                                                          |
| -------------------------------- | ------------------------------------------------------------------------------------------------ |
| `findPageHeadline(tree, path)`   | the title of the item's parent, `undefined` at the top level or for an unknown path              |
| `findPageBreadcrumb(tree, path)` | the items from the top level down to the item, each without `children`; `[]` for an unknown path |
| `findPageChildren(tree, path)`   | the item's `children`; `[]` for a leaf or an unknown path                                        |
| `findPageSiblings(tree, path)`   | the items beside it, itself left out; `[]` for an unknown path                                   |

### `CollectionQueryBuilder`

| Method                                                        | Meaning                                                                                                                                                                                                                                                                                            |
| ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `where(field, operator, value?)`, `andWhere(…)`, `orWhere(…)` | add a condition joined by AND (`where`, `andWhere`) or OR; given a callback `(q) => q.where(…)…` instead, add the group it builds. Clauses combine left to right: `a OR b AND c` is `(a OR b) AND c`                                                                                               |
| `path(path)`                                                  | `where("path", "=", path)`                                                                                                                                                                                                                                                                         |
| `select(...fields)`                                           | return only these fields and `id`; a dotted field returns its object with that key; `id` is always the entry's own, so a path under it is left out. Calls add up, and the result type narrows to `QueryResult`: after `select("title", "author.name")` it is `{ id: string; title: …; author: … }` |
| `order(field, "ASC" \| "DESC")`                               | sort; calls stack, the first sorts first. Without one, the collection's `order`, else source order                                                                                                                                                                                                 |
| `limit(n)`, `skip(n)`                                         | page the result; `n` is a non-negative integer                                                                                                                                                                                                                                                     |
| `all()`                                                       | `Promise<QueryResult<T, S>[]>`: the entries, or after `select` the selected fields                                                                                                                                                                                                                 |
| `first()`                                                     | `Promise<QueryResult<T, S> \| undefined>`: `all()` with `limit(1)`                                                                                                                                                                                                                                 |
| `count()`                                                     | `Promise<number>`: the matching entries; `select`, `order`, `skip` and `limit` do not apply                                                                                                                                                                                                        |

A field is a name or a dotted path into an object (`author.name`); its first segment must be a field of the collection (`collection`, `id`, `stem`, `extension`, a page's fields, or a key some entry has), else the query fails with `queryCollection: unknown field "nope" in collection "blog"`. No segment may be `__proto__`, `constructor` or `prototype`: `queryCollection: a field may not name "__proto__" (got "id.__proto__.toString")`. Every result is a copy, so editing it changes neither the collection nor the next query.

### `QueryOperator`

| Operator                 | Value                                                                     | Matches                                                                 |
| ------------------------ | ------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| `=`, `<>`                | a string, number, boolean or null; for `=` and `<>` also an array of them | equal, not equal                                                        |
| `>`, `>=`, `<`, `<=`     | a string, number, boolean or null                                         | ordered comparison                                                      |
| `IN`, `NOT IN`           | an array of at most 1000 strings, numbers, booleans or nulls              | equal to one, to none; on an array field, any element                   |
| `BETWEEN`, `NOT BETWEEN` | `[low, high]`                                                             | `>= low AND <= high`, its negation                                      |
| `IS NULL`, `IS NOT NULL` | none                                                                      | null or missing; present and not null                                   |
| `LIKE`, `NOT LIKE`       | a string of at most 200 characters                                        | `%` any run, `_` one character, case-insensitive for ASCII letters only |

The engine follows SQLite's rules. A comparison with null or a missing field is never true, `<>` and `NOT IN` included, and `NOT IN` a list holding null is never true; `NOT IN []` is always true, on a null field too. Values of different JSON types are never equal (`<>` is true between them) and order by type: boolean, number, string, array, object. Strings compare by code point, numbers as numbers, booleans as 0 and 1, arrays and objects by their JSON text. `LIKE` reads a number as its text, a boolean as `0` or `1`. `order` puts nulls first ascending and last descending, and keeps source order between equal values.

An operator outside the table throws `queryCollection: unknown operator "=="` at `where`; a value of the wrong shape throws there too: `queryCollection: BETWEEN takes [low, high] (got 3)`, `queryCollection: IN takes an array (got "a")`, `queryCollection: LIKE takes a string (got 3)`.

`CollectionQueryBuilder<T = ContentEntry, S extends string = never, K extends string = string>`: `T` is the entry type, `S` the top-level keys `select` named, `K` the field names `where`, `order` and `select` take (`FieldPath<K>`: a name, or a name followed by `.` and a path). `queryCollection("blog")` gives `K` the collection's own fields once `HamurContentCollections` is filled.

### `QueryResult`, `FieldHead`, `FieldPath`

`QueryResult<T, S>` is `T` while `S` is `never`, else `{ id: string }` and, for each key `K` of `S`, `T[K]` (`unknown` for a key `T` does not have). `FieldHead<"author.name">` is `"author"`, the key a dotted path writes. `FieldPath<K>` is ``K | `${K}.${string}` ``.

### `CollectionQuery`

The JSON description of the builder's calls that the browser posts: `{ where?: QueryClause[]; select?: string[]; order?: Array<[field, "ASC" | "DESC"]>; limit?: number; skip?: number; count?: boolean }`.

### `QueryClause`, `QueryCondition`, `QueryGroup`, `QueryDirection`, `QueryGroupBuilder`

A `QueryCondition` is `{ field, operator, value? }`, a `QueryGroup` is `{ where: QueryClause[] }`, and a `QueryClause` is either with `join: "AND" | "OR"`. `QueryDirection` is `"ASC" | "DESC"`. `QueryGroupBuilder<K>` is what a group callback gets: `where`, `andWhere` and `orWhere`.

### `POST /_hamur/content/query`

The endpoint of `content.clientQuery: "api"`, not served on the `static` preset. The body is `{ collection, query }` with `query` a `CollectionQuery`; the answer is the result as JSON: the entries, or the number for `count`. It checks the query strictly and answers 400 `{ message }` for:

| Case                                                                                                  | Message                                                                               |
| ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| a name that is no collection                                                                          | `unknown collection "nope"`                                                           |
| a collection with `expose: false`                                                                     | `collection "authors" is not exposed`                                                 |
| a field the collection does not have                                                                  | `unknown field "nope" in collection "blog"`                                           |
| an operator outside the table                                                                         | `unknown operator "=="`                                                               |
| a bad `limit` or `skip`                                                                               | `limit must be a non-negative integer`                                                |
| a value of the wrong shape                                                                            | as `where` throws it, without `queryCollection: `                                     |
| a key the body or the query does not have                                                             | `unknown key "code"; the body is { collection, query }`, `unknown query key "$where"` |
| more than 100 conditions, groups nested more than 8 deep, more than 100 `select` or 10 `order` fields | `a query takes at most 100 conditions`, `groups nest at most 8 deep`, …               |

A body above `server.maxBodySize` answers 413.

### `GET /api/_content/<collection>`

Served with `content.api.rest`, one route per exposed collection (not on the `static` preset). It answers the collection's entries as a JSON array, run by the same engine as `queryCollection`:

| Parameter                      | Meaning                                                                                                                           |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| `where[field]=value`           | `field = value`; `field` is a name or a dotted path                                                                               |
| `where[field][operator]=value` | an operator of the `QueryOperator` table, URL-encoded, in any case: `where[date][%3E%3D]=2026-01-01`, `where[tags][in]=["a","b"]` |
| `order=field:desc`             | comma-separated or repeated `field`, `field:asc` or `field:desc`; the collection's `order` without it                             |
| `limit`, `skip`                | non-negative integers; `limit` is at most 100, and 100 without one                                                                |

A value is read as JSON when it is a number, boolean, `null`, a quoted string or an array, else as text: `where[n]=3` is the number 3, `where[title]="3"` the string. A repeated parameter gives an array; `IN` and `NOT IN` take one value as a list of one; `IS NULL` and `IS NOT NULL` take an empty value. Several `where` parameters must all match.

It answers 400 `{ status, message }` with the endpoint's messages (`unknown field "nope" in collection "blog"`, `unknown operator "=="`, `a field may not name "__proto__" (got "id.__proto__")`, …), and for `unknown query parameter "select"; use where[field], where[field][operator], order, limit and skip` and `order takes field, field:asc or field:desc (got "n:up")`. An unknown collection and one with `expose: false` both answer 404 `unknown collection "authors"`.

With `server.openapi` on, each route is in `/_hamur/openapi.json` as `getContent<Name>` with tag `content`: `order`, `limit` and `skip` as query parameters, and as the 200 answer an array of the component `Content<Name>`: the collection schema's JSON Schema output (when the schema implements Standard JSON Schema) with the entry fields added to its `properties` and `required`, and without `additionalProperties` at its root, so a strict schema still describes the entries the route answers.

### GraphQL: `content.graphql`

With `content.api.graphql` and `server.graphql` on, the module adds `.hamur/content/content.graphql` and its resolvers to the app's schema (through `addServerGraphQL` of `hamur/kit`), whether or not the app has its own `server/graphql/`. For each exposed collection it has a type named after the collection with its first letter upper-cased, and two `Query` fields:

```graphql
type Query {
  blog(where: [ContentWhere!], order: [ContentOrder!], limit: Int, skip: Int): [Blog!]!
  blogItem(path: String!): Blog
}
input ContentWhere {
  field: String!
  operator: String! = "="
  value: String
}
input ContentOrder {
  field: String!
  direction: ContentDirection = ASC
}
enum ContentDirection {
  ASC
  DESC
}
```

A data collection's item field takes `id` instead of `path`. A type's fields are the entry fields and the properties of the collection schema's JSON Schema output: strings, integers, numbers and booleans as `String`, `Int`, `Float` and `Boolean`, arrays as lists, objects with properties as generated types (`BlogAuthor`), and anything else, the page's `body`, `toc` and `seo` included, as a `String` holding the value's JSON text. The queries run like the REST routes: `value` is read the same way, `limit` is at most 100, and a refused query is a field error with the REST message (`unknown field "nope" in collection "blog"`). A type or root field the app already has fails the build naming both files, and so does a clash among the generated names (`content.api.graphql: two generated types are named "BlogAuthor"; rename a collection or a field`).

### `queryCollectionSearchSections`

`queryCollectionSearchSections(name, options?)` splits every page of a collection at its headings and returns `SearchSection[]`. It runs one `select("path", "title", "body")` query, so it works on the server, under `"api"` and under `"local"`, adds no endpoint, and an `expose: false` collection throws in the browser as `queryCollection` does.

```ts
import { queryCollectionSearchSections } from "@hamur/content/query"

const sections = await queryCollectionSearchSections("docs", {
  ignoredTags: ["code"],
  minHeading: "h2",
  maxHeading: "h3",
})
```

A heading whose depth is in `[minHeading, maxHeading]` starts a section whose `id` is `<path>#<heading id>`. The text before the first such heading is a section with the page's `path` as `id` and the page's title, left out when it has no text and `minHeading` is `"h1"`. A heading outside the range is text of the section above. `titles` are the titles of the headings above the section that are in the range, outermost first; `level` is the heading's depth, 1 for the text before the first heading. `content` is the section's text with a space between blocks; the text of an element in `ignoredTags` (`"code"`, `"pre"`) is left out, and raw HTML always is.

A `minHeading` or `maxHeading` that is not `"h1"` to `"h6"` throws `queryCollectionSearchSections: minHeading must be "h1" to "h6" (got "h7")`, a `minHeading` deeper than `maxHeading` throws `queryCollectionSearchSections: minHeading h4 is deeper than maxHeading h2`, and a data collection fails with the engine's `queryCollection: unknown field "body" in collection "authors"`.

### `SearchSection`

`{ id: string; title: string; titles: string[]; content: string; level: number }`.

### `SearchSectionsOptions`

`{ ignoredTags?: string[]; minHeading?: HeadingTag; maxHeading?: HeadingTag }`, defaults none, `"h1"` and `"h6"`.

### `HeadingTag`

`"h1" | "h2" | "h3" | "h4" | "h5" | "h6"`.

## `@hamur/content/server`

### `queryCollection`

`queryCollection(event, name)` from a handler: the same `CollectionQueryBuilder`, over any collection, `expose: false` ones included. A name that is no collection fails with `queryCollection: unknown collection "nope"`.

```ts
import { queryCollection } from "@hamur/content/server"
import { defineHandler } from "hamur/server"

export const authorNames = defineHandler({
  route: "/api/authors",
  method: "GET",
  handler: (_, { event }) => queryCollection(event, "authors").select("name").all(),
})
```

### `queryCollectionNavigation`

`queryCollectionNavigation(event, name, extraFields?)`: the tree of `@hamur/content/query`, from a handler, over any collection.

### `queryCollectionItemSurroundings`

`queryCollectionItemSurroundings(event, name, path, options?)`: the entries around `path`, from a handler, over any collection.

### `queryCollectionSearchSections`

`queryCollectionSearchSections(event, name, options?)`: the sections of `@hamur/content/query`, from a handler, over any collection. `SearchSection`, `SearchSectionsOptions` and `HeadingTag` come from here too.

### `searchCollection`

`searchCollection(event, name, query, { limit? })` ranks `query` with the collection's search index, the file the browser loads, so a handler and `useSearchCollection` give one answer for one query. It returns `SearchHit[]` (`{ id, title, titles, level, score }`, best first); `limit` defaults to `20`. `SearchHit` and `SearchOptions` come from here too. A collection that `content.search.collections` does not list throws `searchCollection("docs"): add "docs" to content.search.collections`.

### `findPageHeadline`, `findPageBreadcrumb`, `findPageChildren`, `findPageSiblings`

The same pure functions as in `@hamur/content/query`.

### `getLiveCollection`

`getLiveCollection(name, filter?)` runs the live collection's `loadCollection(filter)` now and returns `{ entries, error, cacheHint }`. It never throws for what the loader or the schema does: an entry the schema rejects gives `error` with the issue (`getLiveCollection("posts"): entry "x": title: Expected string`), a loader that throws gives `error` (`getLiveCollection("posts"): loader "cms" failed: <message>`), and `entries` is then `undefined`. Each entry is `{ id, data, body?, cacheHint? }`: `data` is the schema's output as JSON (a `Date` becomes its ISO string). `cacheHint` merges the collection's and every entry's: every tag once, the shortest `maxAge`, the latest `lastModified`. A name that is no live collection throws `getLiveCollection("blog"): "blog" is not a live collection of content.config.ts`.

```ts
import { getLiveCollection } from "@hamur/content/server"
import { createError, defineHandler } from "hamur/server"

export const posts = defineHandler({
  route: "/api/posts",
  method: "GET",
  handler: async (input: { tag?: string }) => {
    const { entries, error } = await getLiveCollection("posts", { tag: input.tag })
    if (error) throw createError({ status: 502, message: error.message })
    return entries.map((entry) => entry.data)
  },
})
```

A result with `cacheHint.maxAge` is kept in the `cache` storage mount under `content:live:<collection>:<hash>` (the hash covers the call and its filter, the filter's keys in any order) for `maxAge` seconds, and the next call with the same filter returns it without running the loader. Without `maxAge`, and for an error, nothing is kept. A cache that cannot be read or written is a miss: the result is loaded and returned, and the server logger warns once.

A filter is plain JSON: a `Map`, `Set`, `Date`, BigInt, `NaN`, `Infinity`, function, `undefined` in an array or a cycle gives `error` (`getLiveCollection("posts"): the filter must be plain JSON (got Map at filter.tags)`) and the loader does not run. A key whose value is `undefined` is the same as an absent key.

A string `body` is Markdown, parsed with `parseMarkdown` (its defaults, not the `markdown` key) where `Bun.markdown` exists, so on the bun preset and in `hamur dev`. Elsewhere it is the entry's error: `getLiveEntry("posts"): entry "x" has a Markdown body, which only the bun preset parses at run time; return a Markdown AST`. A Markdown AST is passed through.

### `getLiveEntry`

`getLiveEntry(name, filter)` runs `loadEntry(filter)` and returns `{ entry, error, cacheHint }`, with the same errors and cache as `getLiveCollection` (under a different key than a collection call with the same filter). A loader that returns `undefined` gives `{ entry: undefined, error: undefined }`.

### `LiveEntry`, `LiveCollectionResult`, `LiveEntryResult`

`LiveEntry<T>` is `{ id, data: T, body?: MdRoot, cacheHint? }`. `LiveCollectionResult<T>` is `{ entries: LiveEntry<T>[], error: undefined, cacheHint }` or `{ entries: undefined, error: Error, cacheHint }`; `LiveEntryResult<T>` the same with `entry`. The error's `cause` is the schema's issues or what the loader threw.

### `refreshContent`

`refreshContent({ collections? })` drops the cached live results of the collections named (default every live collection), so the next read runs the loader again; a CMS webhook handler calls it. A load running when it is called returns its result to its own caller and stores nothing. A name that is no collection of `content.config.ts` throws `refreshContent: "nope" is not a collection of content.config.ts`; a name of a build-time collection is accepted and has no live results to drop.

```ts
import { refreshContent } from "@hamur/content/server"
import { defineHandler } from "hamur/server"

export const cmsWebhook = defineHandler({
  route: "/api/webhooks/cms",
  method: "POST",
  raw: true,
  handler: async () => {
    await refreshContent({ collections: ["posts"] })
    return new Response(null, { status: 204 })
  },
})
```

The cache is the `cache` mount, so with a shared driver (Redis, a KV) one instance's refresh drops every instance's results. The guard against a load in flight is per instance: another instance's load that was running during the refresh may still store its result, which then lives for its `maxAge`.

### `POST /_hamur/content/refresh`

In `hamur dev` only, never in a build: a CMS webhook target. The body is empty or `{ "collections": ["posts"] }`. It runs the loaders of the build-time collections named (default all) again, as a saved file does, so their pages update, then drops the live results like `refreshContent`, and answers `204`. An unknown name or another body answers `400`.

## `@hamur/content/render`

The root `@hamur/content` is the module and imports the build, while `@hamur/content/render` imports only `hamur/markdown`, so it is safe in the browser.

### `renderEntry`

`renderEntry(entry: ContentEntry): Promise<RenderedEntry>`, with `RenderedEntry` = `{ html: string, headings: MdHeading[], ast: MdRoot }`. It renders a page entry's `body` with `renderMarkdownAst`, so it runs on the server, in the browser and on every preset. `headings` are the entry's `{ depth, id, text }` items and `ast` is its `body`. It is named `renderEntry` because the adapters' server entries already export `render`.

A data entry throws `renderEntry needs a page collection entry (got data collection "authors")`.

### `RenderedEntry`

The type `renderEntry` resolves to.

## `@hamur/content/react`, `@hamur/content/vue`, `@hamur/content/preact`, `@hamur/content/svelte`, `@hamur/content/solid`, `@hamur/content/html`

Every entry exports `useContentPage`, `useSearchCollection`, `ContentRenderer` and the default prose components `ProseA`, `ProseH1` to `ProseH6`, `ProseP`, `ProseUl`, `ProseOl`, `ProseLi`, `ProseBlockquote`, `ProsePre`, `ProseCode`, `ProseImg`, `ProseTable`, `ProseHr`, `ProseStrong` and `ProseEm`, each in its library's form (the html entry's are functions that return a string). The UI library and its `@hamur/adapter-<library>` are peer dependencies.

### `ContentRenderer`

```tsx
import { ContentRenderer } from "@hamur/content/react"

;<ContentRenderer value={entry} excerpt tag="section" unwrap="p" components={{ ProseA: MyLink }} />
```

| Prop         | Type                                 | Default | Meaning                                                                                                   |
| ------------ | ------------------------------------ | ------- | --------------------------------------------------------------------------------------------------------- |
| `value`      | `PageFields \| MdRoot`               | —       | an entry renders its `body`; a Markdown AST renders as it is                                              |
| `components` | `Record<string, Component> \| false` | `{}`    | Markdown components by kebab-case name, and prose components by `Prose<Tag>` name; `false` registers none |
| `tag`        | `string`                             | `"div"` | the wrapper element                                                                                       |
| `excerpt`    | `boolean`                            | `false` | renders the entry's `excerpt` instead of its `body`; an entry without one, or an AST, renders nothing     |
| `unwrap`     | `string`                             | none    | space-separated tags whose element is dropped and whose children are kept (`"p"`)                         |

It renders through the adapter's `MarkdownRenderer`. Heading anchors are in the AST (`markdown.headingLinks`); there is no option for them. A missing `value` throws `ContentRenderer: value is required` under `hamur dev` and renders nothing in a production build. `html` nodes are left out: `ContentRenderer` gives `MarkdownRenderer` no `raw` writer.

A prose component renders one Markdown element in place of the plain element: `Prose<Tag>`, the tag in PascalCase. It is given the element's attributes as `MarkdownRenderer` writes them (URL values already checked) and its rendered children; a task-list item (`li` with `checked`) always renders as the plain element. The component under `components` wins, then the app's file `app/components/content/Prose<Tag>.<ext>` (also with `components: false`, and in every `MarkdownRenderer` and Markdown page); a tag with neither renders through the default prose component, which writes the plain element. A file `ProseFoo.<ext>` for a name that is not a Markdown element fails the build with `app/components/content/ProseFoo.tsx: "foo" is not a Markdown element; a Markdown component is named in kebab case in Markdown and in PascalCase here (Foo.tsx)`.

### `useContentPage`

`useContentPage(collection)` loads the entry of a page collection whose `path` equals the route path, through `useAsyncData` with the key `content:<collection>:<path>`, and applies `useSeoMeta` with the entry's `seo` (`title` and `description` from the entry when `seo` has none). It throws `createError({ status: 404, message: "Page not found: <path>" })` when there is no entry, so the route's error page renders; `useContentPage("authors")` on a data collection throws `useContentPage("authors"): a data collection has no paths`. A page that is a catch-all, `app/pages/[...slug].<ext>`, maps a collection to routes:

```tsx
// app/pages/[...slug].tsx
import { ContentRenderer, useContentPage } from "@hamur/content/react"

export default function Page() {
  const page = useContentPage("docs")
  return <ContentRenderer value={page} />
}
```

| Library      | Returns                                                                                                                             |
| ------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| React        | the entry; the component suspends until it loads                                                                                    |
| Vue          | `Promise<ComputedRef<entry>>`: `const page = await useContentPage("docs")` in `<script setup>`, which a page's `Suspense` waits for |
| Solid        | `Accessor<entry \| undefined>`; reading it throws the 404                                                                           |
| Preact, html | `entry \| undefined`, `undefined` while it loads                                                                                    |
| Svelte       | `{ readonly page }`, a getter that is `undefined` while the entry loads and throws the 404 when read                                |

The entry is typed from `HamurContentCollections`; before typegen has run it is a `PageEntry`. On a server render the entry reaches the browser through the payload, so hydration makes no query. With `content.prerender` on (the default on the `static` preset), `hamur generate` writes every page path with its `<title>`, and a path no entry has answers the 404 page.

### `ContentPage`

`ContentPage<N>` is the page fields of collection `N`'s item type, the type `useContentPage(N)` returns.

### `UseContentPageResult`

The type the svelte `useContentPage` returns: `{ readonly page: ContentPage<N> | undefined }`.

### `useSearchCollection`

`useSearchCollection(name, { immediate? })` searches the collection's search index in the browser; the collection must be in `content.search.collections`, else it throws `useSearchCollection("blog"): add "blog" to content.search.collections`. It returns `{ status, search, init }`.

```tsx
import { useSearchCollection } from "@hamur/content/react"

const { status, search } = useSearchCollection("docs")
const hits = await search("compo", { limit: 10 })
```

| Member                      | Meaning                                                                                                                                                                                                                                                                      |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`                    | `"idle"`, `"loading"`, `"ready"` or `"error"`, reactive in the library's form: a value of the hook's state in React and Preact, a read-only ref (`ComputedRef`) in Vue, an `Accessor` in Solid, a getter that a component reads reactively in Svelte, a plain getter in html |
| `search(query, { limit? })` | `Promise<SearchHit[]>`, at most `limit` hits (default `20`), best first; loads the index first when it is not loaded                                                                                                                                                         |
| `init()`                    | `Promise<void>` that loads the index; a load in flight is shared and a loaded index answers at once                                                                                                                                                                          |
| `onStatus(listener)`        | html only: calls `listener(status)` on each change and returns the function that stops it                                                                                                                                                                                    |

The index is one JSON chunk per collection that the bundler hashes and loads on the first `search()` or `init()`, or at mount with `immediate: true` (never on the server). Every hook for one name shares one index and one `status`. A failed load sets `status` to `"error"`, rejects that call and is tried again by the next. Terms are folded to lower case without diacritics (`normalize("NFD")` with the combining marks removed), the last term of a query also matches by prefix, and hits are ranked by BM25 with a title weight. `search` rejects with `search: limit must be a non-negative integer` for a bad `limit`.

### `UseSearchCollectionOptions`

`{ immediate?: boolean }`, default `false`.

### `UseSearchCollectionResult`

The type `useSearchCollection` returns, in each entry's form of `status`.

### `SearchHit`

`{ id: string; title: string; titles: string[]; level: number; score: number }`, with `id` a `SearchSection`'s id. A hit is a new object; changing it leaves the index alone.

### `SearchOptions`

`{ limit?: number }`.

### `SearchStatus`

`"idle" | "loading" | "ready" | "error"`.

### `ProseA`

An internal `href` (`/…`, not `//…`) renders as the adapter's `Link`, any other as `<a>`.

### `ProsePre`

Renders `<pre>`, with `data-filename` when the fence has a file name. A `ProsePre` of your own is given `language`, `filename`, `highlights` (a list of line numbers) and `code` (the source text) next to its children; the `code` element inside already holds `class="language-<language>"`.

### `ProseH1`, `ProseH2`, `ProseH3`, `ProseH4`, `ProseH5`, `ProseH6`, `ProseP`, `ProseUl`, `ProseOl`, `ProseLi`, `ProseBlockquote`, `ProseCode`, `ProseImg`, `ProseTable`, `ProseHr`, `ProseStrong`, `ProseEm`

Each renders the plain element of its name with the attributes and children it is given.
