# Read the content

How OrbPage's pages, menus and previews reach the shop, typed by its own sections, and what the shop does when a read fails.

Editors publish in the admin; the shop reads what is published through `@orbpage/client`. Every
read is typed by the sections the shop [declared](/docs/shop/sections), and no read ever throws.

Each locale's settings require a page URL template; its article template is optional. When set,
the article template's address is reserved from pages in that locale. Without it, that address
is available to pages and article links cannot resolve there. OrbPage does not yet support
creating or publishing articles; when that arrives, publishing must require an article template
in the article's locale.

## A client per shop

```ts
import { createClient } from "@orbpage/client";
import { sections } from "./sections";

const content = createClient({
  baseUrl: env.PAGE_URL, // where OrbPage answers, such as https://content.nordgrat.de
  sections,
});
```

On Cloudflare, `fetch` reaches OrbPage through a service binding instead of the internet, and
`delivery` sends published reads to OrbPage's cached delivery entrypoint, whose cache answers
without running OrbPage; previews and forms still go to `baseUrl`:

```ts continues
const bound = createClient({
  baseUrl: env.PAGE_URL,
  sections,
  fetch: (request) => env.PAGE.fetch(request),
  delivery: (request) => env.PAGE_DELIVERY.fetch(request),
});
```

Both bindings name OrbPage's Worker, `orbpage`; `PAGE_DELIVERY` names its `Delivery` entrypoint:

```jsonc
// The shop's wrangler.jsonc
"services": [
  { "binding": "PAGE", "service": "orbpage" },
  { "binding": "PAGE_DELIVERY", "service": "orbpage", "entrypoint": "Delivery" }
]
```

## A category's page

Every category has a page: its own content where an editor wrote some, its template's everywhere
else. The answer holds every slot the shop declares, in its order, each a list of typed sections:

```ts continues
const read = await content.categories.get("outdoor/rucksaecke", { locale: "de" });
if (read.ok) {
  read.content.slots.top; // the hero sections, typed by the declaration
  read.content.slots.main;
  read.content.template; // the template it follows
  read.content.meta.unresolved; // what was left out, such as a product no longer sold
} else {
  read.problem.code; // such as "entry_not_found", "unreachable" or "unexpected_response"
}
```

A category is named by the catalog's `ref`, such as `outdoor/rucksaecke`, never by its slug.

A read comes back as the answer or as the problem in its way: OrbPage's own problems, a proxy's
error page and a lost network all arrive as `{ ok: false, problem }` with a `code` and a `kind`.
Nordgrat shows the catalog's category without the editor's slots when OrbPage cannot answer:
the products are what a shopper came for.

A card, link or picture whose product, category, page or file did not resolve is left out, and
the page stays whole; `meta.unresolved` names each one, its section and the reason
(`not_found`, `discontinued`, `timeout`, `error`, `read_limit`), so an editor learns what to fix.

A picture can be marked decorative for one use without changing its library file or other uses.
That use is delivered with an empty `alt` and omitted from Markdown. A linked picture still needs
an accessible name: because its image alt is the link's name, a decorative linked image cannot be
published until the link is removed or the picture is described instead.

A form's short-answer field can carry an editor-chosen `purpose`, such as `name`, `organization`
or `postal-code`. Spread `constraintsOf(field)` from `@orbpage/client` onto the input to give the
browser its `autoComplete` hint along with the field's constraints. Email and phone fields get
their own hints; an unspecified short answer is never guessed from its label.

Running text may hold a table and a video. A table arrives as `div.op-table` around a real
`table`, with its caption, its first row as column headers and, where the editor chose, its first
column as row headers (`th` with `scope`); give the wrapper `overflow-x: auto` so a wide table
scrolls sideways on a phone. Markdown writes it as a GFM table. A video is never a frame: it
arrives as `figure.op-video`, a link to the video on YouTube or Vimeo holding its poster
(`.op-video__poster`, decorative) and its title (`.op-video__title`), which names the link. No
request reaches the video's host until a shopper follows it. To play it in place after consent,
read `data-op-provider` (`youtube` or `vimeo`) and `data-op-video` (its id) from the figure.
Markdown writes the title as a link to the video. A video without a poster cannot be published
until one is picked, or the owner publishes anyway.

## Pages, the home page and menus

```ts continues
const imprint = await content.pages.get("impressum", { locale: "de" });
const home = await content.home.get({ locale: "de" });
const footer = await content.menus.get("footer", { locale: "de" });
if (footer.ok) {
  for (const item of footer.content.items) item.label; // with its href, and its children
}
```

A page of the shop's own is read by its address in the locale; the home page has none. A menu's
item has its label and an address, unless it only heads its children. The shop decides where a page lives: Nordgrat puts its pages right under
the language, `/de/impressum`.

### Edit a page

A new page's address follows its title until the editor chooses another address. **Follow the
title** restores that link while the page has never been published in that locale. Changing a published
page's title never changes its address automatically, including after withdrawal or archive
and restore. An intentional address edit remains possible in Settings.

Creation refuses an address another active page owns in that locale. Saving a draft keeps
unfinished work and reports address collisions beside the address; publishing checks again
and refuses a collision. Invalid address syntax cannot be saved: the work stays in the editor
with advice at the field.

Settings show a live search-result preview, a search title and a multiline description. The
preview uses that locale's configured site name and origin, never the admin's Channel label.
`GET /api/languages` includes these as `sites[locale]` alongside the existing `locales` and
`urlTemplates`, so the preview needs no additional read. The
60/160 character counts suggest where search results may be cut; exceeding them does not block
saving or publication. The existing contract's storage caps still apply.

Close the shop preview to use the whole editor width. Drag its divider, use the arrow keys,
Home or End, or double-click to restore the initial split.

### Read the inbox

Staff with Content edit see paginated summaries: form, sender's email or phone when supplied,
received date and file count. Rows never show message bodies. Open a row, by click or keyboard,
to read every answer and access its files. Opening a submission uses the already loaded
answers; files are fetched only when opened. Delete offers Undo before the submission is removed.

### Delete or archive a page

In the admin, a page's action menu offers **Delete** until it has ever been published, in any
language. Deleting permanently removes its drafts and frees its addresses, so it asks once.
After the first publication, the action is **Archive** instead: every language goes offline,
even one the site no longer serves. Its addresses become available, and its drafts and immutable
versions remain readable. The home page cannot be deleted or archived. Forms, inbox answers and private uploads are separate
and are never deleted with a page.

The pages list switches between active and archived pages. Archive offers Undo; Restore returns
the same identity as drafts only, and refuses if another active page now holds one of its draft
addresses. Nothing republishes automatically. Archived pages cannot be edited, published,
rolled back or previewed.

Archive also invalidates outstanding draft/publish intents in every language and permanently
revokes earlier page preview tokens, even after Restore. A fresh preview keeps working across
ordinary draft saves; explicitly publishing after Restore uses the newly read draft revision.

Links and picked-page cards to the original identity stop resolving; they never follow a new page that reuses its address.
An explicit `path` or `url` link still means its literal address, not a page identity.

For callers, `GET /api/pages` lists active pages; `?state=archived` lists archived pages.
`GET /api/pages/{page}/{locale}` and its versions remain available for archived history.
Summaries carry `state`, `everPublished` and a page-wide `revision`, raised by saves and
publication changes in any language. With Content edit, send that revision to
`DELETE /api/pages/{page}`, `POST /api/pages/{page}/archive` or
`POST /api/pages/{page}/restore`. A changed page answers `page_stale`; deleting published history
answers `page_published`. Restore can answer `page_address_taken`. All support an
`Idempotency-Key` for retries of the same intent.
Replaying creation or withdrawal after a draft was deleted answers `entry_not_found`, never
recreates it or retargets a replacement page at the same address.

The DOM-free client exports `deletePage`, `archivePage` and `restorePage`; each takes a page id
and `{ baseUrl, token, revision, idempotencyKey }`, with an optional `fetch` transport. Archive
and restore return the page summary in `content`; delete returns its `id`.

### Links to routes the shop owns

Editors can enter a site path such as `/booking?service=oil#time`, including in menus and
running text. It is stored as `{ kind: "path", path: "/booking?service=oil#time" }`, so it
follows the site's origin for the delivered locale without a page entry for that route.
Paths start with one `/`; network paths, backslashes, control characters, dot segments and
ambiguous path escapes are refused. Query strings and fragments keep their spelling.

Delivery uses absolute addresses by default. Ask for `links: "path"` on a page, home,
category or menu read (also on a preview) to get own links as root-relative paths throughout
section settings, cards, running-text HTML and Markdown:

```ts continues
const local = await content.pages.get("impressum", { links: "path", include: ["markdown"] });
const localFooter = await content.menus.get("footer", { links: "path" });
```

The HTTP parameter is `links=path`. Page and article identities use their locale's URL
template; category and product addresses become paths only when their origin is the site's
origin. External `url` links keep their full address, including business links,
`mailto:` and `tel:`; media addresses are unchanged. Same-origin URL links also become paths.
Use a `path` link, not an absolute URL,
when a hand-entered route should follow the environment.

## Re-declare and migrate

A shop that changes its sections, or takes over another shop's site, moves the old content
across in three steps. [Write content from code](/docs/page/write-content) shows the calls.

1. **Read what no longer fits.** `declareSections(sections, { ...options, check: true })` lists
   `misfits`: each `category`, `template` or `page` (by its `key`), locale and `state` whose
   draft or live version the new declaration would not read, with the `issues`.
2. **Declare.** A misfit live version still delivers what fits; a misfit draft must be fixed
   before it saves again. A menu the declaration drops stays stored and delivers
   `entry_not_found`.
3. **Overwrite or archive each one.**

| Choice    | What it keeps                                   | When                                    |
| --------- | ----------------------------------------------- | --------------------------------------- |
| Overwrite | The id, the address, history and links to it    | The new shop has a page at that address |
| Archive   | Drafts and versions; the page goes offline      | Nothing replaces the page               |
| Leave it  | Everything; delivery shows only what still fits | The old content does no harm            |

Overwrite with `applyPage`, `applyMenu` or a template's or category's save and publish,
`basedOn` the current draft revision. Archive with `archivePage` and a staff token.

`ensurePage` treats an address an archived page held as taken and answers `entry_archived`, so
a seed never quietly replaces archived content. Overwrite a page whose address the new shop
reuses, such as an imprint, instead of archiving it first. To bring an archived page back, call
`restorePage`, then apply its new body.

## What OrbPage does not hold yet

OrbPage holds pages, the home page, category content, templates, menus and forms. Not possible
today:

- **Site-wide snippets,** such as an announcement bar shown on every page.
- **Content per product,** such as the story of how a piece is made.

Keep such text in the shop's own code until OrbPage holds it. Do not put it in a menu: a menu's
labels are links, and editors would find the text in the wrong place.

## The options every read takes

| Option         | What it does                                                                                              |
| -------------- | --------------------------------------------------------------------------------------------------------- |
| `locale`       | The locale to read; absent, the client's `locale`, else the site's default.                               |
| `fallback`     | `"default"` serves the default locale where the page has no translation; the answer says which it served. |
| `signal`       | Ends the wait, such as `request.signal` or `AbortSignal.timeout(2000)`; the read is then `unreachable`.   |
| `headingLevel` | The level a text's first heading maps to; 2 by default, never 1.                                          |
| `links`        | `"path"` writes own links as paths; `"absolute"` (the default) keeps absolute addresses.                  |
| `format: "md"` | Markdown instead of JSON, for agents and a page's Markdown twin.                                          |
| `include`      | `["markdown"]` embeds the Markdown under `content.rendered`, beside the JSON.                             |
| `preview`      | A preview token: the editor's draft, read past every cache.                                               |

Every answer carries `cacheControl` and `age`, so the shop's own page cache keeps a page no
longer than its content.

## Previews

The admin shows an editor's draft inside the shop, in a frame. The shop answers the frame's
start at `previewPath`, and then reads with the token the frame carries:

```ts continues
import { previewPath, previewTokenOf, startPreview } from "@orbpage/client";
import type { StartPreview } from "@orbpage/client";

async function handle(request: Request): Promise<Response> {
  if (new URL(request.url).pathname === previewPath) {
    return startPreview(request, {
      studio: env.ADMIN_URL, // the only origin a token is taken from
      content,
      pathOf: async ({ shows, locale }) =>
        shows.kind === "category" ? `/${locale}/c/${shows.category}` : `/${locale}`,
    });
  }
  const preview = previewTokenOf(request);
  const draft = await content.categories.get("outdoor/rucksaecke", { locale: "de", preview });
  return Response.json(draft.ok ? draft.content.slots : {});
}
```

`startPreview` checks that the post came from the admin, asks OrbPage which page the token shows,
keeps the token in the frame's cookie until it ends and sends the frame there. A token OrbPage
refuses (`preview_token_expired`) is a plain answer: read the published page and say so. In the
frame, `sectionMark`, `slotMark` and `AddToSlot` from `@orbpage/react` let the editor point at a
section and add one to a slot.

### Set up previews

A preview works once each of these holds:

1. **The site knows the shop's address.** The admin posts the token to the locale's `origin`
   plus `previewPath` (`/preview`). Set each locale's `origin` with `manageContent`'s
   `configure`, as the owner or with the operator key.
2. **The shop answers `/preview`** with `startPreview`, its `studio` the admin's origin.
3. **`pathOf` knows every page a token shows.** `shows.kind` is `category`, with its
   `category` ref, or `page`, with `home`, `page` and the draft's `slug` (absent on the home page).
4. **Every read passes the token** from `previewTokenOf(request)` as `preview`, and the answer
   goes out through `previewed(response, studio)`, so no cache keeps it.
5. **The page mounts `PreviewBridge`** from `@orbpage/react` while it renders a preview, with
   the admin's origin, the current path and a function that reads the page again.

```ts continues
const pathOf: StartPreview["pathOf"] = async ({ shows, locale }) => {
  if (shows.kind === "category") return `/${locale}/c/${shows.category}`;
  if (shows.home) return `/${locale}`;
  return `/${locale}/${shows.slug ?? ""}`;
};
```

Inside `PageLayout`, keep `sectionMark(section.id)` on each section and `slotMark(name)` on each
slot, so a click in the frame opens that section's editor.